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": 4,
"code_window": [
"\t\tvirtualDelegate: IListVirtualDelegate<T>,\n",
"\t\trenderers: IListRenderer<any /* TODO@joao */, any>[],\n",
"\t\tprivate _options: IListOptions<T> = DefaultOptions\n",
"\t) {\n",
"\t\tthis.focus = new Trait('focused');\n",
"\t\tthis.selection = new SelectionTrait();\n",
"\n",
"\t\tmixin(_options, defaultStyles, false);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.selection = new Trait('selected');\n",
"\t\tthis.focus = new FocusTrait(this.selection.contains);\n"
],
"file_path": "src/vs/base/browser/ui/list/listWidget.ts",
"type": "replace",
"edit_start_line_idx": 1200
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export function toBase64UrlEncoding(base64string: string) {
return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); // Need to use base64url encoding
}
| extensions/vscode-account/src/utils.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.00017417674825992435,
0.00017417674825992435,
0.00017417674825992435,
0.00017417674825992435,
0
] |
{
"id": 4,
"code_window": [
"\t\tvirtualDelegate: IListVirtualDelegate<T>,\n",
"\t\trenderers: IListRenderer<any /* TODO@joao */, any>[],\n",
"\t\tprivate _options: IListOptions<T> = DefaultOptions\n",
"\t) {\n",
"\t\tthis.focus = new Trait('focused');\n",
"\t\tthis.selection = new SelectionTrait();\n",
"\n",
"\t\tmixin(_options, defaultStyles, false);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.selection = new Trait('selected');\n",
"\t\tthis.focus = new FocusTrait(this.selection.contains);\n"
],
"file_path": "src/vs/base/browser/ui/list/listWidget.ts",
"type": "replace",
"edit_start_line_idx": 1200
} | /*---------------------------------------------------------------------------------------------
* 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 * as platform from 'vs/base/common/platform';
export namespace Schemas {
/**
* A schema that is used for models that exist in memory
* only and that have no correspondence on a server or such.
*/
export const inMemory = 'inmemory';
/**
* A schema that is used for setting files
*/
export const vscode = 'vscode';
/**
* A schema that is used for internal private files
*/
export const internal = 'private';
/**
* A walk-through document.
*/
export const walkThrough = 'walkThrough';
/**
* An embedded code snippet.
*/
export const walkThroughSnippet = 'walkThroughSnippet';
export const http = 'http';
export const https = 'https';
export const file = 'file';
export const mailto = 'mailto';
export const untitled = 'untitled';
export const data = 'data';
export const command = 'command';
export const vscodeRemote = 'vscode-remote';
export const vscodeRemoteResource = 'vscode-remote-resource';
export const userData = 'vscode-userdata';
}
class RemoteAuthoritiesImpl {
private readonly _hosts: { [authority: string]: string | undefined; } = Object.create(null);
private readonly _ports: { [authority: string]: number | undefined; } = Object.create(null);
private readonly _connectionTokens: { [authority: string]: string | undefined; } = Object.create(null);
private _preferredWebSchema: 'http' | 'https' = 'http';
private _delegate: ((uri: URI) => URI) | null = null;
setPreferredWebSchema(schema: 'http' | 'https') {
this._preferredWebSchema = schema;
}
setDelegate(delegate: (uri: URI) => URI): void {
this._delegate = delegate;
}
set(authority: string, host: string, port: number): void {
this._hosts[authority] = host;
this._ports[authority] = port;
}
setConnectionToken(authority: string, connectionToken: string): void {
this._connectionTokens[authority] = connectionToken;
}
rewrite(uri: URI): URI {
if (this._delegate) {
return this._delegate(uri);
}
const authority = uri.authority;
let host = this._hosts[authority];
if (host && host.indexOf(':') !== -1) {
host = `[${host}]`;
}
const port = this._ports[authority];
const connectionToken = this._connectionTokens[authority];
let query = `path=${encodeURIComponent(uri.path)}`;
if (typeof connectionToken === 'string') {
query += `&tkn=${encodeURIComponent(connectionToken)}`;
}
return URI.from({
scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
authority: `${host}:${port}`,
path: `/vscode-remote-resource`,
query
});
}
}
export const RemoteAuthorities = new RemoteAuthoritiesImpl();
| src/vs/base/common/network.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.0001790800306480378,
0.00017391087021678686,
0.00016600695380475372,
0.00017490620666649193,
0.000003561489393177908
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('focused')) {\n",
"\t\t\tconst base64Id = strings.safeBtoa(this.model.id);\n",
"\t\t\tthis.element.setAttribute('id', base64Id);\n",
"\t\t} else {\n",
"\t\t\tthis.element.removeAttribute('id');\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('selected')) {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "replace",
"edit_start_line_idx": 221
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Platform from 'vs/base/common/platform';
import * as Browser from 'vs/base/browser/browser';
import * as Lifecycle from 'vs/base/common/lifecycle';
import * as DOM from 'vs/base/browser/dom';
import * as Diff from 'vs/base/common/diff/diff';
import * as Touch from 'vs/base/browser/touch';
import * as strings from 'vs/base/common/strings';
import * as Mouse from 'vs/base/browser/mouseEvent';
import * as Keyboard from 'vs/base/browser/keyboardEvent';
import * as Model from 'vs/base/parts/tree/browser/treeModel';
import * as dnd from './treeDnd';
import { ArrayIterator, MappedIterator } from 'vs/base/common/iterator';
import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { HeightMap, IViewItem } from 'vs/base/parts/tree/browser/treeViewModel';
import * as _ from 'vs/base/parts/tree/browser/tree';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Event, Emitter } from 'vs/base/common/event';
import { DataTransfers, StaticDND, IDragAndDropData } from 'vs/base/browser/dnd';
import { DefaultTreestyler } from './treeDefaults';
import { Delayer, timeout } from 'vs/base/common/async';
export interface IRow {
element: HTMLElement | null;
templateId: string;
templateData: any;
}
function removeFromParent(element: HTMLElement): void {
try {
element.parentElement!.removeChild(element);
} catch (e) {
// this will throw if this happens due to a blur event, nasty business
}
}
export class RowCache implements Lifecycle.IDisposable {
private _cache: { [templateId: string]: IRow[]; } | null;
constructor(private context: _.ITreeContext) {
this._cache = { '': [] };
}
public alloc(templateId: string): IRow {
let result = this.cache(templateId).pop();
if (!result) {
let content = document.createElement('div');
content.className = 'content';
let row = document.createElement('div');
row.appendChild(content);
let templateData: any = null;
try {
templateData = this.context.renderer!.renderTemplate(this.context.tree, templateId, content);
} catch (err) {
console.error('Tree usage error: exception while rendering template');
console.error(err);
}
result = {
element: row,
templateId: templateId,
templateData
};
}
return result;
}
public release(templateId: string, row: IRow): void {
removeFromParent(row.element!);
this.cache(templateId).push(row);
}
private cache(templateId: string): IRow[] {
return this._cache![templateId] || (this._cache![templateId] = []);
}
public garbageCollect(): void {
if (this._cache) {
Object.keys(this._cache).forEach(templateId => {
this._cache![templateId].forEach(cachedRow => {
this.context.renderer!.disposeTemplate(this.context.tree, templateId, cachedRow.templateData);
cachedRow.element = null;
cachedRow.templateData = null;
});
delete this._cache![templateId];
});
}
}
public dispose(): void {
this.garbageCollect();
this._cache = null;
}
}
export interface IViewContext extends _.ITreeContext {
cache: RowCache;
horizontalScrolling: boolean;
}
export class ViewItem implements IViewItem {
private context: IViewContext;
public model: Model.Item;
public id: string;
protected row: IRow | null;
public top: number;
public height: number;
public width: number = 0;
public onDragStart!: (e: DragEvent) => void;
public needsRender: boolean = false;
public uri: string | null = null;
public unbindDragStart: Lifecycle.IDisposable = Lifecycle.Disposable.None;
public loadingTimer: any;
public _styles: any;
private _draggable: boolean = false;
constructor(context: IViewContext, model: Model.Item) {
this.context = context;
this.model = model;
this.id = this.model.id;
this.row = null;
this.top = 0;
this.height = model.getHeight();
this._styles = {};
model.getAllTraits().forEach(t => this._styles[t] = true);
if (model.isExpanded()) {
this.addClass('expanded');
}
}
set expanded(value: boolean) {
value ? this.addClass('expanded') : this.removeClass('expanded');
}
set loading(value: boolean) {
value ? this.addClass('codicon-loading') : this.removeClass('codicon-loading');
}
set draggable(value: boolean) {
this._draggable = value;
this.render(true);
}
get draggable() {
return this._draggable;
}
set dropTarget(value: boolean) {
value ? this.addClass('drop-target') : this.removeClass('drop-target');
}
public get element(): HTMLElement {
return (this.row && this.row.element)!;
}
private _templateId: string | undefined;
private get templateId(): string {
return this._templateId || (this._templateId = (this.context.renderer!.getTemplateId && this.context.renderer!.getTemplateId(this.context.tree, this.model.getElement())));
}
public addClass(name: string): void {
this._styles[name] = true;
this.render(true);
}
public removeClass(name: string): void {
delete this._styles[name]; // is this slow?
this.render(true);
}
public render(skipUserRender = false): void {
if (!this.model || !this.element) {
return;
}
let classes = ['monaco-tree-row'];
classes.push.apply(classes, Object.keys(this._styles));
if (this.model.hasChildren()) {
classes.push('has-children');
}
this.element.className = classes.join(' ');
this.element.draggable = this.draggable;
this.element.style.height = this.height + 'px';
// ARIA
this.element.setAttribute('role', 'treeitem');
const accessibility = this.context.accessibilityProvider!;
const ariaLabel = accessibility.getAriaLabel(this.context.tree, this.model.getElement());
if (ariaLabel) {
this.element.setAttribute('aria-label', ariaLabel);
}
if (accessibility.getPosInSet && accessibility.getSetSize) {
this.element.setAttribute('aria-setsize', accessibility.getSetSize());
this.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));
}
if (this.model.hasTrait('focused')) {
const base64Id = strings.safeBtoa(this.model.id);
this.element.setAttribute('id', base64Id);
} else {
this.element.removeAttribute('id');
}
if (this.model.hasTrait('selected')) {
this.element.setAttribute('aria-selected', 'true');
} else {
this.element.setAttribute('aria-selected', 'false');
}
if (this.model.hasChildren()) {
this.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));
} else {
this.element.removeAttribute('aria-expanded');
}
this.element.setAttribute('aria-level', String(this.model.getDepth()));
if (this.context.options.paddingOnRow) {
this.element.style.paddingLeft = this.context.options.twistiePixels! + ((this.model.getDepth() - 1) * this.context.options.indentPixels!) + 'px';
} else {
this.element.style.paddingLeft = ((this.model.getDepth() - 1) * this.context.options.indentPixels!) + 'px';
(<HTMLElement>this.row!.element!.firstElementChild).style.paddingLeft = this.context.options.twistiePixels + 'px';
}
let uri = this.context.dnd!.getDragURI(this.context.tree, this.model.getElement());
if (uri !== this.uri) {
if (this.unbindDragStart) {
this.unbindDragStart.dispose();
}
if (uri) {
this.uri = uri;
this.draggable = true;
this.unbindDragStart = DOM.addDisposableListener(this.element, 'dragstart', (e) => {
this.onDragStart(e);
});
} else {
this.uri = null;
}
}
if (!skipUserRender && this.element) {
let paddingLeft: number = 0;
if (this.context.horizontalScrolling) {
const style = window.getComputedStyle(this.element);
paddingLeft = parseFloat(style.paddingLeft!);
}
if (this.context.horizontalScrolling) {
this.element.style.width = Browser.isFirefox ? '-moz-fit-content' : 'fit-content';
}
try {
this.context.renderer!.renderElement(this.context.tree, this.model.getElement(), this.templateId, this.row!.templateData);
} catch (err) {
console.error('Tree usage error: exception while rendering element');
console.error(err);
}
if (this.context.horizontalScrolling) {
this.width = DOM.getContentWidth(this.element) + paddingLeft;
this.element.style.width = '';
}
}
}
updateWidth(): any {
if (!this.context.horizontalScrolling || !this.element) {
return;
}
const style = window.getComputedStyle(this.element);
const paddingLeft = parseFloat(style.paddingLeft!);
this.element.style.width = Browser.isFirefox ? '-moz-fit-content' : 'fit-content';
this.width = DOM.getContentWidth(this.element) + paddingLeft;
this.element.style.width = '';
}
public insertInDOM(container: HTMLElement, afterElement: HTMLElement | null): void {
if (!this.row) {
this.row = this.context.cache.alloc(this.templateId);
// used in reverse lookup from HTMLElement to Item
(<any>this.element)[TreeView.BINDING] = this;
}
if (this.element.parentElement) {
return;
}
if (afterElement === null) {
container.appendChild(this.element);
} else {
try {
container.insertBefore(this.element, afterElement);
} catch (e) {
console.warn('Failed to locate previous tree element');
container.appendChild(this.element);
}
}
this.render();
}
public removeFromDOM(): void {
if (!this.row) {
return;
}
this.unbindDragStart.dispose();
this.uri = null;
(<any>this.element)[TreeView.BINDING] = null;
this.context.cache.release(this.templateId, this.row);
this.row = null;
}
public dispose(): void {
this.row = null;
}
}
class RootViewItem extends ViewItem {
constructor(context: IViewContext, model: Model.Item, wrapper: HTMLElement) {
super(context, model);
this.row = {
element: wrapper,
templateData: null,
templateId: null!
};
}
public render(): void {
if (!this.model || !this.element) {
return;
}
let classes = ['monaco-tree-wrapper'];
classes.push.apply(classes, Object.keys(this._styles));
if (this.model.hasChildren()) {
classes.push('has-children');
}
this.element.className = classes.join(' ');
}
public insertInDOM(container: HTMLElement, afterElement: HTMLElement): void {
// noop
}
public removeFromDOM(): void {
// noop
}
}
function reactionEquals(one: _.IDragOverReaction, other: _.IDragOverReaction | null): boolean {
if (!one && !other) {
return true;
} else if (!one || !other) {
return false;
} else if (one.accept !== other.accept) {
return false;
} else if (one.bubble !== other.bubble) {
return false;
} else if (one.effect !== other.effect) {
return false;
} else {
return true;
}
}
export class TreeView extends HeightMap {
static readonly BINDING = 'monaco-tree-row';
static readonly LOADING_DECORATION_DELAY = 800;
private static counter: number = 0;
private instance: number;
private context: IViewContext;
private modelListeners: Lifecycle.IDisposable[];
private model: Model.TreeModel | null = null;
private viewListeners: Lifecycle.IDisposable[];
private domNode: HTMLElement;
private wrapper: HTMLElement;
private styleElement: HTMLStyleElement;
private treeStyler: _.ITreeStyler;
private rowsContainer: HTMLElement;
private scrollableElement: ScrollableElement;
private msGesture: MSGesture | undefined;
private lastPointerType: string = '';
private horizontalScrolling: boolean;
private contentWidthUpdateDelayer = new Delayer<void>(50);
private lastRenderTop: number;
private lastRenderHeight: number;
private inputItem!: ViewItem;
private items: { [id: string]: ViewItem; };
private isRefreshing = false;
private refreshingPreviousChildrenIds: { [id: string]: string[] } = {};
private currentDragAndDropData: IDragAndDropData | null = null;
private currentDropElement: any;
private currentDropElementReaction!: _.IDragOverReaction;
private currentDropTarget: ViewItem | null = null;
private shouldInvalidateDropReaction: boolean;
private currentDropTargets: ViewItem[] | null = null;
private currentDropDisposable: Lifecycle.IDisposable = Lifecycle.Disposable.None;
private gestureDisposable: Lifecycle.IDisposable = Lifecycle.Disposable.None;
private dragAndDropScrollInterval: number | null = null;
private dragAndDropScrollTimeout: number | null = null;
private dragAndDropMouseY: number | null = null;
private didJustPressContextMenuKey: boolean;
private highlightedItemWasDraggable: boolean = false;
private onHiddenScrollTop: number | null = null;
private readonly _onDOMFocus = new Emitter<void>();
readonly onDOMFocus: Event<void> = this._onDOMFocus.event;
private readonly _onDOMBlur = new Emitter<void>();
readonly onDOMBlur: Event<void> = this._onDOMBlur.event;
private readonly _onDidScroll = new Emitter<void>();
readonly onDidScroll: Event<void> = this._onDidScroll.event;
constructor(context: _.ITreeContext, container: HTMLElement) {
super();
TreeView.counter++;
this.instance = TreeView.counter;
const horizontalScrollMode = typeof context.options.horizontalScrollMode === 'undefined' ? ScrollbarVisibility.Hidden : context.options.horizontalScrollMode;
this.horizontalScrolling = horizontalScrollMode !== ScrollbarVisibility.Hidden;
this.context = {
dataSource: context.dataSource,
renderer: context.renderer,
controller: context.controller,
dnd: context.dnd,
filter: context.filter,
sorter: context.sorter,
tree: context.tree,
accessibilityProvider: context.accessibilityProvider,
options: context.options,
cache: new RowCache(context),
horizontalScrolling: this.horizontalScrolling
};
this.modelListeners = [];
this.viewListeners = [];
this.items = {};
this.domNode = document.createElement('div');
this.domNode.className = `monaco-tree no-focused-item monaco-tree-instance-${this.instance}`;
// to allow direct tabbing into the tree instead of first focusing the tree
this.domNode.tabIndex = context.options.preventRootFocus ? -1 : 0;
this.styleElement = DOM.createStyleSheet(this.domNode);
this.treeStyler = context.styler || new DefaultTreestyler(this.styleElement, `monaco-tree-instance-${this.instance}`);
// ARIA
this.domNode.setAttribute('role', 'tree');
if (this.context.options.ariaLabel) {
this.domNode.setAttribute('aria-label', this.context.options.ariaLabel);
}
if (this.context.options.alwaysFocused) {
DOM.addClass(this.domNode, 'focused');
}
if (!this.context.options.paddingOnRow) {
DOM.addClass(this.domNode, 'no-row-padding');
}
this.wrapper = document.createElement('div');
this.wrapper.className = 'monaco-tree-wrapper';
this.scrollableElement = new ScrollableElement(this.wrapper, {
alwaysConsumeMouseWheel: true,
horizontal: horizontalScrollMode,
vertical: (typeof context.options.verticalScrollMode !== 'undefined' ? context.options.verticalScrollMode : ScrollbarVisibility.Auto),
useShadows: context.options.useShadows
});
this.scrollableElement.onScroll((e) => {
this.render(e.scrollTop, e.height, e.scrollLeft, e.width, e.scrollWidth);
this._onDidScroll.fire();
});
this.gestureDisposable = Touch.Gesture.addTarget(this.wrapper);
this.rowsContainer = document.createElement('div');
this.rowsContainer.className = 'monaco-tree-rows';
if (context.options.showTwistie) {
this.rowsContainer.className += ' show-twisties';
}
let focusTracker = DOM.trackFocus(this.domNode);
this.viewListeners.push(focusTracker.onDidFocus(() => this.onFocus()));
this.viewListeners.push(focusTracker.onDidBlur(() => this.onBlur()));
this.viewListeners.push(focusTracker);
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'keydown', (e) => this.onKeyDown(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'keyup', (e) => this.onKeyUp(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'mousedown', (e) => this.onMouseDown(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'mouseup', (e) => this.onMouseUp(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'auxclick', (e: MouseEvent) => {
if (e && e.button === 1) {
this.onMouseMiddleClick(e);
}
}));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'click', (e) => this.onClick(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'contextmenu', (e) => this.onContextMenu(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, Touch.EventType.Tap, (e) => this.onTap(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, Touch.EventType.Change, (e) => this.onTouchChange(e)));
this.viewListeners.push(DOM.addDisposableListener(window, 'dragover', (e) => this.onDragOver(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'drop', (e) => this.onDrop(e)));
this.viewListeners.push(DOM.addDisposableListener(window, 'dragend', (e) => this.onDragEnd(e)));
this.viewListeners.push(DOM.addDisposableListener(window, 'dragleave', (e) => this.onDragOver(e)));
this.wrapper.appendChild(this.rowsContainer);
this.domNode.appendChild(this.scrollableElement.getDomNode());
container.appendChild(this.domNode);
this.lastRenderTop = 0;
this.lastRenderHeight = 0;
this.didJustPressContextMenuKey = false;
this.currentDropTarget = null;
this.currentDropTargets = [];
this.shouldInvalidateDropReaction = false;
this.dragAndDropScrollInterval = null;
this.dragAndDropScrollTimeout = null;
this.onRowsChanged();
this.layout();
this.setupMSGesture();
this.applyStyles(context.options);
}
public applyStyles(styles: _.ITreeStyles): void {
this.treeStyler.style(styles);
}
protected createViewItem(item: Model.Item): IViewItem {
return new ViewItem(this.context, item);
}
public getHTMLElement(): HTMLElement {
return this.domNode;
}
public focus(): void {
this.domNode.focus();
}
public isFocused(): boolean {
return document.activeElement === this.domNode;
}
public blur(): void {
this.domNode.blur();
}
public onVisible(): void {
this.scrollTop = this.onHiddenScrollTop!;
this.onHiddenScrollTop = null;
this.setupMSGesture();
}
private setupMSGesture(): void {
if ((<any>window).MSGesture) {
this.msGesture = new MSGesture();
setTimeout(() => this.msGesture!.target = this.wrapper, 100); // TODO@joh, TODO@IETeam
}
}
public onHidden(): void {
this.onHiddenScrollTop = this.scrollTop;
}
private isTreeVisible(): boolean {
return this.onHiddenScrollTop === null;
}
public layout(height?: number, width?: number): void {
if (!this.isTreeVisible()) {
return;
}
this.viewHeight = height || DOM.getContentHeight(this.wrapper); // render
this.scrollHeight = this.getContentHeight();
if (this.horizontalScrolling) {
this.viewWidth = width || DOM.getContentWidth(this.wrapper);
}
}
private render(scrollTop: number, viewHeight: number, scrollLeft: number, viewWidth: number, scrollWidth: number): void {
let i: number;
let stop: number;
let renderTop = scrollTop;
let renderBottom = scrollTop + viewHeight;
let thisRenderBottom = this.lastRenderTop + this.lastRenderHeight;
// when view scrolls down, start rendering from the renderBottom
for (i = this.indexAfter(renderBottom) - 1, stop = this.indexAt(Math.max(thisRenderBottom, renderTop)); i >= stop; i--) {
this.insertItemInDOM(<ViewItem>this.itemAtIndex(i));
}
// when view scrolls up, start rendering from either this.renderTop or renderBottom
for (i = Math.min(this.indexAt(this.lastRenderTop), this.indexAfter(renderBottom)) - 1, stop = this.indexAt(renderTop); i >= stop; i--) {
this.insertItemInDOM(<ViewItem>this.itemAtIndex(i));
}
// when view scrolls down, start unrendering from renderTop
for (i = this.indexAt(this.lastRenderTop), stop = Math.min(this.indexAt(renderTop), this.indexAfter(thisRenderBottom)); i < stop; i++) {
this.removeItemFromDOM(<ViewItem>this.itemAtIndex(i));
}
// when view scrolls up, start unrendering from either renderBottom this.renderTop
for (i = Math.max(this.indexAfter(renderBottom), this.indexAt(this.lastRenderTop)), stop = this.indexAfter(thisRenderBottom); i < stop; i++) {
this.removeItemFromDOM(<ViewItem>this.itemAtIndex(i));
}
let topItem = this.itemAtIndex(this.indexAt(renderTop));
if (topItem) {
this.rowsContainer.style.top = (topItem.top - renderTop) + 'px';
}
if (this.horizontalScrolling) {
this.rowsContainer.style.left = -scrollLeft + 'px';
this.rowsContainer.style.width = `${Math.max(scrollWidth, viewWidth)}px`;
}
this.lastRenderTop = renderTop;
this.lastRenderHeight = renderBottom - renderTop;
}
public setModel(newModel: Model.TreeModel): void {
this.releaseModel();
this.model = newModel;
this.model.onRefresh(this.onRefreshing, this, this.modelListeners);
this.model.onDidRefresh(this.onRefreshed, this, this.modelListeners);
this.model.onSetInput(this.onClearingInput, this, this.modelListeners);
this.model.onDidSetInput(this.onSetInput, this, this.modelListeners);
this.model.onDidFocus(this.onModelFocusChange, this, this.modelListeners);
this.model.onRefreshItemChildren(this.onItemChildrenRefreshing, this, this.modelListeners);
this.model.onDidRefreshItemChildren(this.onItemChildrenRefreshed, this, this.modelListeners);
this.model.onDidRefreshItem(this.onItemRefresh, this, this.modelListeners);
this.model.onExpandItem(this.onItemExpanding, this, this.modelListeners);
this.model.onDidExpandItem(this.onItemExpanded, this, this.modelListeners);
this.model.onCollapseItem(this.onItemCollapsing, this, this.modelListeners);
this.model.onDidRevealItem(this.onItemReveal, this, this.modelListeners);
this.model.onDidAddTraitItem(this.onItemAddTrait, this, this.modelListeners);
this.model.onDidRemoveTraitItem(this.onItemRemoveTrait, this, this.modelListeners);
}
private onRefreshing(): void {
this.isRefreshing = true;
}
private onRefreshed(): void {
this.isRefreshing = false;
this.onRowsChanged();
}
private onRowsChanged(scrollTop: number = this.scrollTop): void {
if (this.isRefreshing) {
return;
}
this.scrollTop = scrollTop;
this.updateScrollWidth();
}
private updateScrollWidth(): void {
if (!this.horizontalScrolling) {
return;
}
this.contentWidthUpdateDelayer.trigger(() => {
const keys = Object.keys(this.items);
let scrollWidth = 0;
for (const key of keys) {
scrollWidth = Math.max(scrollWidth, this.items[key].width);
}
this.scrollWidth = scrollWidth + 10 /* scrollbar */;
});
}
public focusNextPage(eventPayload?: any): void {
let lastPageIndex = this.indexAt(this.scrollTop + this.viewHeight);
lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
let lastPageElement = this.itemAtIndex(lastPageIndex).model.getElement();
let currentlyFocusedElement = this.model!.getFocus();
if (currentlyFocusedElement !== lastPageElement) {
this.model!.setFocus(lastPageElement, eventPayload);
} else {
let previousScrollTop = this.scrollTop;
this.scrollTop += this.viewHeight;
if (this.scrollTop !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(() => {
this.focusNextPage(eventPayload);
}, 0);
}
}
}
public focusPreviousPage(eventPayload?: any): void {
let firstPageIndex: number;
if (this.scrollTop === 0) {
firstPageIndex = this.indexAt(this.scrollTop);
} else {
firstPageIndex = this.indexAfter(this.scrollTop - 1);
}
let firstPageElement = this.itemAtIndex(firstPageIndex).model.getElement();
let currentlyFocusedElement = this.model!.getFocus();
if (currentlyFocusedElement !== firstPageElement) {
this.model!.setFocus(firstPageElement, eventPayload);
} else {
let previousScrollTop = this.scrollTop;
this.scrollTop -= this.viewHeight;
if (this.scrollTop !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(() => {
this.focusPreviousPage(eventPayload);
}, 0);
}
}
}
public get viewHeight() {
const scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.height;
}
public set viewHeight(height: number) {
this.scrollableElement.setScrollDimensions({ height });
}
private set scrollHeight(scrollHeight: number) {
scrollHeight = scrollHeight + (this.horizontalScrolling ? 10 : 0);
this.scrollableElement.setScrollDimensions({ scrollHeight });
}
public get viewWidth(): number {
const scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.width;
}
public set viewWidth(viewWidth: number) {
this.scrollableElement.setScrollDimensions({ width: viewWidth });
}
private set scrollWidth(scrollWidth: number) {
this.scrollableElement.setScrollDimensions({ scrollWidth });
}
public get scrollTop(): number {
const scrollPosition = this.scrollableElement.getScrollPosition();
return scrollPosition.scrollTop;
}
public set scrollTop(scrollTop: number) {
const scrollHeight = this.getContentHeight() + (this.horizontalScrolling ? 10 : 0);
this.scrollableElement.setScrollDimensions({ scrollHeight });
this.scrollableElement.setScrollPosition({ scrollTop });
}
public getScrollPosition(): number {
const height = this.getContentHeight() - this.viewHeight;
return height <= 0 ? 1 : this.scrollTop / height;
}
public setScrollPosition(pos: number): void {
const height = this.getContentHeight() - this.viewHeight;
this.scrollTop = height * pos;
}
// Events
private onClearingInput(e: Model.IInputEvent): void {
let item = <Model.Item>e.item;
if (item) {
this.onRemoveItems(new MappedIterator(item.getNavigator(), item => item && item.id));
this.onRowsChanged();
}
}
private onSetInput(e: Model.IInputEvent): void {
this.context.cache.garbageCollect();
this.inputItem = new RootViewItem(this.context, <Model.Item>e.item, this.wrapper);
}
private onItemChildrenRefreshing(e: Model.IItemChildrenRefreshEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem && this.context.options.showLoading) {
viewItem.loadingTimer = setTimeout(() => {
viewItem.loadingTimer = 0;
viewItem.loading = true;
}, TreeView.LOADING_DECORATION_DELAY);
}
if (!e.isNested) {
let childrenIds: string[] = [];
let navigator = item.getNavigator();
let childItem: Model.Item | null;
while (childItem = navigator.next()) {
childrenIds.push(childItem.id);
}
this.refreshingPreviousChildrenIds[item.id] = childrenIds;
}
}
private onItemChildrenRefreshed(e: Model.IItemChildrenRefreshEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem) {
if (viewItem.loadingTimer) {
clearTimeout(viewItem.loadingTimer);
viewItem.loadingTimer = 0;
}
viewItem.loading = false;
}
if (!e.isNested) {
let previousChildrenIds = this.refreshingPreviousChildrenIds[item.id];
let afterModelItems: Model.Item[] = [];
let navigator = item.getNavigator();
let childItem: Model.Item | null;
while (childItem = navigator.next()) {
afterModelItems.push(childItem);
}
let skipDiff = Math.abs(previousChildrenIds.length - afterModelItems.length) > 1000;
let diff: Diff.IDiffChange[] = [];
let doToInsertItemsAlreadyExist: boolean = false;
if (!skipDiff) {
const lcs = new Diff.LcsDiff(
{
getElements: () => previousChildrenIds
},
{
getElements: () => afterModelItems.map(item => item.id)
},
null
);
diff = lcs.ComputeDiff(false).changes;
// this means that the result of the diff algorithm would result
// in inserting items that were already registered. this can only
// happen if the data provider returns bad ids OR if the sorting
// of the elements has changed
doToInsertItemsAlreadyExist = diff.some(d => {
if (d.modifiedLength > 0) {
for (let i = d.modifiedStart, len = d.modifiedStart + d.modifiedLength; i < len; i++) {
if (this.items.hasOwnProperty(afterModelItems[i].id)) {
return true;
}
}
}
return false;
});
}
// 50 is an optimization number, at some point we're better off
// just replacing everything
if (!skipDiff && !doToInsertItemsAlreadyExist && diff.length < 50) {
for (const diffChange of diff) {
if (diffChange.originalLength > 0) {
this.onRemoveItems(new ArrayIterator(previousChildrenIds, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength));
}
if (diffChange.modifiedLength > 0) {
let beforeItem: Model.Item | null = afterModelItems[diffChange.modifiedStart - 1] || item;
beforeItem = beforeItem.getDepth() > 0 ? beforeItem : null;
this.onInsertItems(new ArrayIterator(afterModelItems, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength), beforeItem ? beforeItem.id : null);
}
}
} else if (skipDiff || diff.length) {
this.onRemoveItems(new ArrayIterator(previousChildrenIds));
this.onInsertItems(new ArrayIterator(afterModelItems), item.getDepth() > 0 ? item.id : null);
}
if (skipDiff || diff.length) {
this.onRowsChanged();
}
}
}
private onItemRefresh(item: Model.Item): void {
this.onItemsRefresh([item]);
}
private onItemsRefresh(items: Model.Item[]): void {
this.onRefreshItemSet(items.filter(item => this.items.hasOwnProperty(item.id)));
this.onRowsChanged();
}
private onItemExpanding(e: Model.IItemExpandEvent): void {
let viewItem = this.items[e.item.id];
if (viewItem) {
viewItem.expanded = true;
}
}
private onItemExpanded(e: Model.IItemExpandEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.expanded = true;
let height = this.onInsertItems(item.getNavigator(), item.id) || 0;
let scrollTop = this.scrollTop;
if (viewItem.top + viewItem.height <= this.scrollTop) {
scrollTop += height;
}
this.onRowsChanged(scrollTop);
}
}
private onItemCollapsing(e: Model.IItemCollapseEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.expanded = false;
this.onRemoveItems(new MappedIterator(item.getNavigator(), item => item && item.id));
this.onRowsChanged();
}
}
private onItemReveal(e: Model.IItemRevealEvent): void {
let item = <Model.Item>e.item;
let relativeTop = <number>e.relativeTop;
let viewItem = this.items[item.id];
if (viewItem) {
if (relativeTop !== null) {
relativeTop = relativeTop < 0 ? 0 : relativeTop;
relativeTop = relativeTop > 1 ? 1 : relativeTop;
// y = mx + b
let m = viewItem.height - this.viewHeight;
this.scrollTop = m * relativeTop + viewItem.top;
} else {
let viewItemBottom = viewItem.top + viewItem.height;
let wrapperBottom = this.scrollTop + this.viewHeight;
if (viewItem.top < this.scrollTop) {
this.scrollTop = viewItem.top;
} else if (viewItemBottom >= wrapperBottom) {
this.scrollTop = viewItemBottom - this.viewHeight;
}
}
}
}
private onItemAddTrait(e: Model.IItemTraitEvent): void {
let item = <Model.Item>e.item;
let trait = <string>e.trait;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.addClass(trait);
}
if (trait === 'highlighted') {
DOM.addClass(this.domNode, trait);
// Ugly Firefox fix: input fields can't be selected if parent nodes are draggable
if (viewItem) {
this.highlightedItemWasDraggable = !!viewItem.draggable;
if (viewItem.draggable) {
viewItem.draggable = false;
}
}
}
}
private onItemRemoveTrait(e: Model.IItemTraitEvent): void {
let item = <Model.Item>e.item;
let trait = <string>e.trait;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.removeClass(trait);
}
if (trait === 'highlighted') {
DOM.removeClass(this.domNode, trait);
// Ugly Firefox fix: input fields can't be selected if parent nodes are draggable
if (this.highlightedItemWasDraggable) {
viewItem.draggable = true;
}
this.highlightedItemWasDraggable = false;
}
}
private onModelFocusChange(): void {
const focus = this.model && this.model.getFocus();
DOM.toggleClass(this.domNode, 'no-focused-item', !focus);
// ARIA
if (focus) {
this.domNode.setAttribute('aria-activedescendant', strings.safeBtoa(this.context.dataSource.getId(this.context.tree, focus)));
} else {
this.domNode.removeAttribute('aria-activedescendant');
}
}
// HeightMap "events"
public onInsertItem(item: ViewItem): void {
item.onDragStart = (e) => { this.onDragStart(item, e); };
item.needsRender = true;
this.refreshViewItem(item);
this.items[item.id] = item;
}
public onRefreshItem(item: ViewItem, needsRender = false): void {
item.needsRender = item.needsRender || needsRender;
this.refreshViewItem(item);
}
public onRemoveItem(item: ViewItem): void {
this.removeItemFromDOM(item);
item.dispose();
delete this.items[item.id];
}
// ViewItem refresh
private refreshViewItem(item: ViewItem): void {
item.render();
if (this.shouldBeRendered(item)) {
this.insertItemInDOM(item);
} else {
this.removeItemFromDOM(item);
}
}
// DOM Events
private onClick(e: MouseEvent): void {
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
let event = new Mouse.StandardMouseEvent(e);
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onClick(this.context.tree, item.model.getElement(), event);
}
private onMouseMiddleClick(e: MouseEvent): void {
if (!this.context.controller!.onMouseMiddleClick!) {
return;
}
let event = new Mouse.StandardMouseEvent(e);
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onMouseMiddleClick!(this.context.tree, item.model.getElement(), event);
}
private onMouseDown(e: MouseEvent): void {
this.didJustPressContextMenuKey = false;
if (!this.context.controller!.onMouseDown!) {
return;
}
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
let event = new Mouse.StandardMouseEvent(e);
if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) {
return;
}
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onMouseDown!(this.context.tree, item.model.getElement(), event);
}
private onMouseUp(e: MouseEvent): void {
if (!this.context.controller!.onMouseUp!) {
return;
}
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
let event = new Mouse.StandardMouseEvent(e);
if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) {
return;
}
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onMouseUp!(this.context.tree, item.model.getElement(), event);
}
private onTap(e: Touch.GestureEvent): void {
let item = this.getItemAround(<HTMLElement>e.initialTarget);
if (!item) {
return;
}
this.context.controller!.onTap(this.context.tree, item.model.getElement(), e);
}
private onTouchChange(event: Touch.GestureEvent): void {
event.preventDefault();
event.stopPropagation();
this.scrollTop -= event.translationY;
}
private onContextMenu(keyboardEvent: KeyboardEvent): void;
private onContextMenu(mouseEvent: MouseEvent): void;
private onContextMenu(event: KeyboardEvent | MouseEvent): void {
let resultEvent: _.ContextMenuEvent;
let element: any;
if (event instanceof KeyboardEvent || this.didJustPressContextMenuKey) {
this.didJustPressContextMenuKey = false;
let keyboardEvent = new Keyboard.StandardKeyboardEvent(<KeyboardEvent>event);
element = this.model!.getFocus();
let position: DOM.IDomNodePagePosition;
if (!element) {
element = this.model!.getInput();
position = DOM.getDomNodePagePosition(this.inputItem.element);
} else {
const id = this.context.dataSource.getId(this.context.tree, element);
const viewItem = this.items[id!];
position = DOM.getDomNodePagePosition(viewItem.element);
}
resultEvent = new _.KeyboardContextMenuEvent(position.left + position.width, position.top, keyboardEvent);
} else {
let mouseEvent = new Mouse.StandardMouseEvent(<MouseEvent>event);
let item = this.getItemAround(mouseEvent.target);
if (!item) {
return;
}
element = item.model.getElement();
resultEvent = new _.MouseContextMenuEvent(mouseEvent);
}
this.context.controller!.onContextMenu(this.context.tree, element, resultEvent);
}
private onKeyDown(e: KeyboardEvent): void {
let event = new Keyboard.StandardKeyboardEvent(e);
this.didJustPressContextMenuKey = event.keyCode === KeyCode.ContextMenu || (event.shiftKey && event.keyCode === KeyCode.F10);
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return; // Ignore event if target is a form input field (avoids browser specific issues)
}
if (this.didJustPressContextMenuKey) {
event.preventDefault();
event.stopPropagation();
}
this.context.controller!.onKeyDown(this.context.tree, event);
}
private onKeyUp(e: KeyboardEvent): void {
if (this.didJustPressContextMenuKey) {
this.onContextMenu(e);
}
this.didJustPressContextMenuKey = false;
this.context.controller!.onKeyUp(this.context.tree, new Keyboard.StandardKeyboardEvent(e));
}
private onDragStart(item: ViewItem, e: any): void {
if (this.model!.getHighlight()) {
return;
}
let element = item.model.getElement();
let selection = this.model!.getSelection();
let elements: any[];
if (selection.indexOf(element) > -1) {
elements = selection;
} else {
elements = [element];
}
e.dataTransfer.effectAllowed = 'copyMove';
e.dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify([item.uri]));
if (e.dataTransfer.setDragImage) {
let label: string;
if (this.context.dnd!.getDragLabel) {
label = this.context.dnd!.getDragLabel!(this.context.tree, elements);
} else {
label = String(elements.length);
}
const dragImage = document.createElement('div');
dragImage.className = 'monaco-tree-drag-image';
dragImage.textContent = label;
document.body.appendChild(dragImage);
e.dataTransfer.setDragImage(dragImage, -10, -10);
setTimeout(() => document.body.removeChild(dragImage), 0);
}
this.currentDragAndDropData = new dnd.ElementsDragAndDropData(elements);
StaticDND.CurrentDragAndDropData = new dnd.ExternalElementsDragAndDropData(elements);
this.context.dnd!.onDragStart(this.context.tree, this.currentDragAndDropData, new Mouse.DragMouseEvent(e));
}
private setupDragAndDropScrollInterval(): void {
let viewTop = DOM.getTopLeftOffset(this.wrapper).top;
if (!this.dragAndDropScrollInterval) {
this.dragAndDropScrollInterval = window.setInterval(() => {
if (this.dragAndDropMouseY === null) {
return;
}
let diff = this.dragAndDropMouseY - viewTop;
let scrollDiff = 0;
let upperLimit = this.viewHeight - 35;
if (diff < 35) {
scrollDiff = Math.max(-14, 0.2 * (diff - 35));
} else if (diff > upperLimit) {
scrollDiff = Math.min(14, 0.2 * (diff - upperLimit));
}
this.scrollTop += scrollDiff;
}, 10);
this.cancelDragAndDropScrollTimeout();
this.dragAndDropScrollTimeout = window.setTimeout(() => {
this.cancelDragAndDropScrollInterval();
this.dragAndDropScrollTimeout = null;
}, 1000);
}
}
private cancelDragAndDropScrollInterval(): void {
if (this.dragAndDropScrollInterval) {
window.clearInterval(this.dragAndDropScrollInterval);
this.dragAndDropScrollInterval = null;
}
this.cancelDragAndDropScrollTimeout();
}
private cancelDragAndDropScrollTimeout(): void {
if (this.dragAndDropScrollTimeout) {
window.clearTimeout(this.dragAndDropScrollTimeout);
this.dragAndDropScrollTimeout = null;
}
}
private onDragOver(e: DragEvent): boolean {
e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
let event = new Mouse.DragMouseEvent(e);
let viewItem = this.getItemAround(event.target);
if (!viewItem || (event.posx === 0 && event.posy === 0 && event.browserEvent.type === DOM.EventType.DRAG_LEAVE)) {
// dragging outside of tree
if (this.currentDropTarget) {
// clear previously hovered element feedback
this.currentDropTargets!.forEach(i => i.dropTarget = false);
this.currentDropTargets = [];
this.currentDropDisposable.dispose();
}
this.cancelDragAndDropScrollInterval();
this.currentDropTarget = null;
this.currentDropElement = null;
this.dragAndDropMouseY = null;
return false;
}
// dragging inside the tree
this.setupDragAndDropScrollInterval();
this.dragAndDropMouseY = event.posy;
if (!this.currentDragAndDropData) {
// just started dragging
if (StaticDND.CurrentDragAndDropData) {
this.currentDragAndDropData = StaticDND.CurrentDragAndDropData;
} else {
if (!event.dataTransfer.types) {
return false;
}
this.currentDragAndDropData = new dnd.DesktopDragAndDropData();
}
}
this.currentDragAndDropData.update((event.browserEvent as DragEvent).dataTransfer!);
let element: any;
let item: Model.Item | null = viewItem.model;
let reaction: _.IDragOverReaction | null;
// check the bubble up behavior
do {
element = item ? item.getElement() : this.model!.getInput();
reaction = this.context.dnd!.onDragOver(this.context.tree, this.currentDragAndDropData, element, event);
if (!reaction || reaction.bubble !== _.DragOverBubble.BUBBLE_UP) {
break;
}
item = item && item.parent;
} while (item);
if (!item) {
this.currentDropElement = null;
return false;
}
let canDrop = reaction && reaction.accept;
if (canDrop) {
this.currentDropElement = item.getElement();
event.preventDefault();
event.dataTransfer.dropEffect = reaction!.effect === _.DragOverEffect.COPY ? 'copy' : 'move';
} else {
this.currentDropElement = null;
}
// item is the model item where drop() should be called
// can be null
let currentDropTarget = item.id === this.inputItem.id ? this.inputItem : this.items[item.id];
if (this.shouldInvalidateDropReaction || this.currentDropTarget !== currentDropTarget || !reactionEquals(this.currentDropElementReaction, reaction)) {
this.shouldInvalidateDropReaction = false;
if (this.currentDropTarget) {
this.currentDropTargets!.forEach(i => i.dropTarget = false);
this.currentDropTargets = [];
this.currentDropDisposable.dispose();
}
this.currentDropTarget = currentDropTarget;
this.currentDropElementReaction = reaction!;
if (canDrop) {
// setup hover feedback for drop target
if (this.currentDropTarget) {
this.currentDropTarget.dropTarget = true;
this.currentDropTargets!.push(this.currentDropTarget);
}
if (reaction!.bubble === _.DragOverBubble.BUBBLE_DOWN) {
let nav = item.getNavigator();
let child: Model.Item | null;
while (child = nav.next()) {
viewItem = this.items[child.id];
if (viewItem) {
viewItem.dropTarget = true;
this.currentDropTargets!.push(viewItem);
}
}
}
if (reaction!.autoExpand) {
const timeoutPromise = timeout(500);
this.currentDropDisposable = Lifecycle.toDisposable(() => timeoutPromise.cancel());
timeoutPromise
.then(() => this.context.tree.expand(this.currentDropElement))
.then(() => this.shouldInvalidateDropReaction = true);
}
}
}
return true;
}
private onDrop(e: DragEvent): void {
if (this.currentDropElement) {
let event = new Mouse.DragMouseEvent(e);
event.preventDefault();
this.currentDragAndDropData!.update((event.browserEvent as DragEvent).dataTransfer!);
this.context.dnd!.drop(this.context.tree, this.currentDragAndDropData!, this.currentDropElement, event);
this.onDragEnd(e);
}
this.cancelDragAndDropScrollInterval();
}
private onDragEnd(e: DragEvent): void {
if (this.currentDropTarget) {
this.currentDropTargets!.forEach(i => i.dropTarget = false);
this.currentDropTargets = [];
}
this.currentDropDisposable.dispose();
this.cancelDragAndDropScrollInterval();
this.currentDragAndDropData = null;
StaticDND.CurrentDragAndDropData = undefined;
this.currentDropElement = null;
this.currentDropTarget = null;
this.dragAndDropMouseY = null;
}
private onFocus(): void {
if (!this.context.options.alwaysFocused) {
DOM.addClass(this.domNode, 'focused');
}
this._onDOMFocus.fire();
}
private onBlur(): void {
if (!this.context.options.alwaysFocused) {
DOM.removeClass(this.domNode, 'focused');
}
this.domNode.removeAttribute('aria-activedescendant'); // ARIA
this._onDOMBlur.fire();
}
// DOM changes
private insertItemInDOM(item: ViewItem): void {
let elementAfter: HTMLElement | null = null;
let itemAfter = <ViewItem>this.itemAfter(item);
if (itemAfter && itemAfter.element) {
elementAfter = itemAfter.element;
}
item.insertInDOM(this.rowsContainer, elementAfter);
}
private removeItemFromDOM(item: ViewItem): void {
if (!item) {
return;
}
item.removeFromDOM();
}
// Helpers
private shouldBeRendered(item: ViewItem): boolean {
return item.top < this.lastRenderTop + this.lastRenderHeight && item.top + item.height > this.lastRenderTop;
}
private getItemAround(element: HTMLElement): ViewItem | undefined {
let candidate: ViewItem = this.inputItem;
let el: HTMLElement | null = element;
do {
if ((<any>el)[TreeView.BINDING]) {
candidate = (<any>el)[TreeView.BINDING];
}
if (el === this.wrapper || el === this.domNode) {
return candidate;
}
if (el === this.scrollableElement.getDomNode() || el === document.body) {
return undefined;
}
} while (el = el.parentElement);
return undefined;
}
// Cleanup
private releaseModel(): void {
if (this.model) {
this.modelListeners = Lifecycle.dispose(this.modelListeners);
this.model = null;
}
}
public dispose(): void {
// TODO@joao: improve
this.scrollableElement.dispose();
this.releaseModel();
this.viewListeners = Lifecycle.dispose(this.viewListeners);
this._onDOMFocus.dispose();
this._onDOMBlur.dispose();
if (this.domNode.parentNode) {
this.domNode.parentNode.removeChild(this.domNode);
}
if (this.items) {
Object.keys(this.items).forEach(key => this.items[key].removeFromDOM());
}
if (this.context.cache) {
this.context.cache.dispose();
}
this.gestureDisposable.dispose();
super.dispose();
}
}
| src/vs/base/parts/tree/browser/treeView.ts | 1 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.9988447427749634,
0.012723040767014027,
0.00016186805441975594,
0.00016986855189315975,
0.11022235453128815
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('focused')) {\n",
"\t\t\tconst base64Id = strings.safeBtoa(this.model.id);\n",
"\t\t\tthis.element.setAttribute('id', base64Id);\n",
"\t\t} else {\n",
"\t\t\tthis.element.removeAttribute('id');\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('selected')) {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "replace",
"edit_start_line_idx": 221
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
| src/vs/css.d.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.00017421111988369375,
0.00017421111988369375,
0.00017421111988369375,
0.00017421111988369375,
0
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('focused')) {\n",
"\t\t\tconst base64Id = strings.safeBtoa(this.model.id);\n",
"\t\t\tthis.element.setAttribute('id', base64Id);\n",
"\t\t} else {\n",
"\t\t\tthis.element.removeAttribute('id');\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('selected')) {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "replace",
"edit_start_line_idx": 221
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ExtensionContext, languages, IndentAction } from 'vscode';
export function activate(_context: ExtensionContext): any {
languages.setLanguageConfiguration('python', {
onEnterRules: [
{
beforeText: /^\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\s*$/,
action: { indentAction: IndentAction.Indent }
}
]
});
} | extensions/python/src/pythonMain.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.00017352131544612348,
0.00017307515372522175,
0.00017262899200432003,
0.00017307515372522175,
4.461617209017277e-7
] |
{
"id": 5,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('focused')) {\n",
"\t\t\tconst base64Id = strings.safeBtoa(this.model.id);\n",
"\t\t\tthis.element.setAttribute('id', base64Id);\n",
"\t\t} else {\n",
"\t\t\tthis.element.removeAttribute('id');\n",
"\t\t}\n",
"\t\tif (this.model.hasTrait('selected')) {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "replace",
"edit_start_line_idx": 221
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, ServicesAccessor, registerEditorAction } from 'vs/editor/browser/editorExtensions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { Action } from 'vs/base/common/actions';
class InspectKeyMap extends EditorAction {
constructor() {
super({
id: 'workbench.action.inspectKeyMappings',
label: nls.localize('workbench.action.inspectKeyMap', "Developer: Inspect Key Mappings"),
alias: 'Developer: Inspect Key Mappings',
precondition: undefined
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const keybindingService = accessor.get(IKeybindingService);
const editorService = accessor.get(IEditorService);
editorService.openEditor({ contents: keybindingService._dumpDebugInfo(), options: { pinned: true } });
}
}
registerEditorAction(InspectKeyMap);
class InspectKeyMapJSON extends Action {
public static readonly ID = 'workbench.action.inspectKeyMappingsJSON';
public static readonly LABEL = nls.localize('workbench.action.inspectKeyMapJSON', "Inspect Key Mappings (JSON)");
constructor(
id: string,
label: string,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@IEditorService private readonly _editorService: IEditorService
) {
super(id, label);
}
public run(): Promise<any> {
return this._editorService.openEditor({ contents: this._keybindingService._dumpDebugInfoJSON(), options: { pinned: true } });
}
}
const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions);
registry.registerWorkbenchAction(SyncActionDescriptor.create(InspectKeyMapJSON, InspectKeyMapJSON.ID, InspectKeyMapJSON.LABEL), 'Developer: Inspect Key Mappings (JSON)', nls.localize('developer', "Developer"));
| src/vs/workbench/contrib/codeEditor/browser/inspectKeybindings.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.00017357822798658162,
0.00017255591228604317,
0.0001714369427645579,
0.00017247791402041912,
7.075510666254559e-7
] |
{
"id": 6,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'false');\n",
"\t\t}\n",
"\t\tif (this.model.hasChildren()) {\n",
"\t\t\tthis.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.element.removeAttribute('id');\n"
],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "add",
"edit_start_line_idx": 227
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Platform from 'vs/base/common/platform';
import * as Browser from 'vs/base/browser/browser';
import * as Lifecycle from 'vs/base/common/lifecycle';
import * as DOM from 'vs/base/browser/dom';
import * as Diff from 'vs/base/common/diff/diff';
import * as Touch from 'vs/base/browser/touch';
import * as strings from 'vs/base/common/strings';
import * as Mouse from 'vs/base/browser/mouseEvent';
import * as Keyboard from 'vs/base/browser/keyboardEvent';
import * as Model from 'vs/base/parts/tree/browser/treeModel';
import * as dnd from './treeDnd';
import { ArrayIterator, MappedIterator } from 'vs/base/common/iterator';
import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { HeightMap, IViewItem } from 'vs/base/parts/tree/browser/treeViewModel';
import * as _ from 'vs/base/parts/tree/browser/tree';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Event, Emitter } from 'vs/base/common/event';
import { DataTransfers, StaticDND, IDragAndDropData } from 'vs/base/browser/dnd';
import { DefaultTreestyler } from './treeDefaults';
import { Delayer, timeout } from 'vs/base/common/async';
export interface IRow {
element: HTMLElement | null;
templateId: string;
templateData: any;
}
function removeFromParent(element: HTMLElement): void {
try {
element.parentElement!.removeChild(element);
} catch (e) {
// this will throw if this happens due to a blur event, nasty business
}
}
export class RowCache implements Lifecycle.IDisposable {
private _cache: { [templateId: string]: IRow[]; } | null;
constructor(private context: _.ITreeContext) {
this._cache = { '': [] };
}
public alloc(templateId: string): IRow {
let result = this.cache(templateId).pop();
if (!result) {
let content = document.createElement('div');
content.className = 'content';
let row = document.createElement('div');
row.appendChild(content);
let templateData: any = null;
try {
templateData = this.context.renderer!.renderTemplate(this.context.tree, templateId, content);
} catch (err) {
console.error('Tree usage error: exception while rendering template');
console.error(err);
}
result = {
element: row,
templateId: templateId,
templateData
};
}
return result;
}
public release(templateId: string, row: IRow): void {
removeFromParent(row.element!);
this.cache(templateId).push(row);
}
private cache(templateId: string): IRow[] {
return this._cache![templateId] || (this._cache![templateId] = []);
}
public garbageCollect(): void {
if (this._cache) {
Object.keys(this._cache).forEach(templateId => {
this._cache![templateId].forEach(cachedRow => {
this.context.renderer!.disposeTemplate(this.context.tree, templateId, cachedRow.templateData);
cachedRow.element = null;
cachedRow.templateData = null;
});
delete this._cache![templateId];
});
}
}
public dispose(): void {
this.garbageCollect();
this._cache = null;
}
}
export interface IViewContext extends _.ITreeContext {
cache: RowCache;
horizontalScrolling: boolean;
}
export class ViewItem implements IViewItem {
private context: IViewContext;
public model: Model.Item;
public id: string;
protected row: IRow | null;
public top: number;
public height: number;
public width: number = 0;
public onDragStart!: (e: DragEvent) => void;
public needsRender: boolean = false;
public uri: string | null = null;
public unbindDragStart: Lifecycle.IDisposable = Lifecycle.Disposable.None;
public loadingTimer: any;
public _styles: any;
private _draggable: boolean = false;
constructor(context: IViewContext, model: Model.Item) {
this.context = context;
this.model = model;
this.id = this.model.id;
this.row = null;
this.top = 0;
this.height = model.getHeight();
this._styles = {};
model.getAllTraits().forEach(t => this._styles[t] = true);
if (model.isExpanded()) {
this.addClass('expanded');
}
}
set expanded(value: boolean) {
value ? this.addClass('expanded') : this.removeClass('expanded');
}
set loading(value: boolean) {
value ? this.addClass('codicon-loading') : this.removeClass('codicon-loading');
}
set draggable(value: boolean) {
this._draggable = value;
this.render(true);
}
get draggable() {
return this._draggable;
}
set dropTarget(value: boolean) {
value ? this.addClass('drop-target') : this.removeClass('drop-target');
}
public get element(): HTMLElement {
return (this.row && this.row.element)!;
}
private _templateId: string | undefined;
private get templateId(): string {
return this._templateId || (this._templateId = (this.context.renderer!.getTemplateId && this.context.renderer!.getTemplateId(this.context.tree, this.model.getElement())));
}
public addClass(name: string): void {
this._styles[name] = true;
this.render(true);
}
public removeClass(name: string): void {
delete this._styles[name]; // is this slow?
this.render(true);
}
public render(skipUserRender = false): void {
if (!this.model || !this.element) {
return;
}
let classes = ['monaco-tree-row'];
classes.push.apply(classes, Object.keys(this._styles));
if (this.model.hasChildren()) {
classes.push('has-children');
}
this.element.className = classes.join(' ');
this.element.draggable = this.draggable;
this.element.style.height = this.height + 'px';
// ARIA
this.element.setAttribute('role', 'treeitem');
const accessibility = this.context.accessibilityProvider!;
const ariaLabel = accessibility.getAriaLabel(this.context.tree, this.model.getElement());
if (ariaLabel) {
this.element.setAttribute('aria-label', ariaLabel);
}
if (accessibility.getPosInSet && accessibility.getSetSize) {
this.element.setAttribute('aria-setsize', accessibility.getSetSize());
this.element.setAttribute('aria-posinset', accessibility.getPosInSet(this.context.tree, this.model.getElement()));
}
if (this.model.hasTrait('focused')) {
const base64Id = strings.safeBtoa(this.model.id);
this.element.setAttribute('id', base64Id);
} else {
this.element.removeAttribute('id');
}
if (this.model.hasTrait('selected')) {
this.element.setAttribute('aria-selected', 'true');
} else {
this.element.setAttribute('aria-selected', 'false');
}
if (this.model.hasChildren()) {
this.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));
} else {
this.element.removeAttribute('aria-expanded');
}
this.element.setAttribute('aria-level', String(this.model.getDepth()));
if (this.context.options.paddingOnRow) {
this.element.style.paddingLeft = this.context.options.twistiePixels! + ((this.model.getDepth() - 1) * this.context.options.indentPixels!) + 'px';
} else {
this.element.style.paddingLeft = ((this.model.getDepth() - 1) * this.context.options.indentPixels!) + 'px';
(<HTMLElement>this.row!.element!.firstElementChild).style.paddingLeft = this.context.options.twistiePixels + 'px';
}
let uri = this.context.dnd!.getDragURI(this.context.tree, this.model.getElement());
if (uri !== this.uri) {
if (this.unbindDragStart) {
this.unbindDragStart.dispose();
}
if (uri) {
this.uri = uri;
this.draggable = true;
this.unbindDragStart = DOM.addDisposableListener(this.element, 'dragstart', (e) => {
this.onDragStart(e);
});
} else {
this.uri = null;
}
}
if (!skipUserRender && this.element) {
let paddingLeft: number = 0;
if (this.context.horizontalScrolling) {
const style = window.getComputedStyle(this.element);
paddingLeft = parseFloat(style.paddingLeft!);
}
if (this.context.horizontalScrolling) {
this.element.style.width = Browser.isFirefox ? '-moz-fit-content' : 'fit-content';
}
try {
this.context.renderer!.renderElement(this.context.tree, this.model.getElement(), this.templateId, this.row!.templateData);
} catch (err) {
console.error('Tree usage error: exception while rendering element');
console.error(err);
}
if (this.context.horizontalScrolling) {
this.width = DOM.getContentWidth(this.element) + paddingLeft;
this.element.style.width = '';
}
}
}
updateWidth(): any {
if (!this.context.horizontalScrolling || !this.element) {
return;
}
const style = window.getComputedStyle(this.element);
const paddingLeft = parseFloat(style.paddingLeft!);
this.element.style.width = Browser.isFirefox ? '-moz-fit-content' : 'fit-content';
this.width = DOM.getContentWidth(this.element) + paddingLeft;
this.element.style.width = '';
}
public insertInDOM(container: HTMLElement, afterElement: HTMLElement | null): void {
if (!this.row) {
this.row = this.context.cache.alloc(this.templateId);
// used in reverse lookup from HTMLElement to Item
(<any>this.element)[TreeView.BINDING] = this;
}
if (this.element.parentElement) {
return;
}
if (afterElement === null) {
container.appendChild(this.element);
} else {
try {
container.insertBefore(this.element, afterElement);
} catch (e) {
console.warn('Failed to locate previous tree element');
container.appendChild(this.element);
}
}
this.render();
}
public removeFromDOM(): void {
if (!this.row) {
return;
}
this.unbindDragStart.dispose();
this.uri = null;
(<any>this.element)[TreeView.BINDING] = null;
this.context.cache.release(this.templateId, this.row);
this.row = null;
}
public dispose(): void {
this.row = null;
}
}
class RootViewItem extends ViewItem {
constructor(context: IViewContext, model: Model.Item, wrapper: HTMLElement) {
super(context, model);
this.row = {
element: wrapper,
templateData: null,
templateId: null!
};
}
public render(): void {
if (!this.model || !this.element) {
return;
}
let classes = ['monaco-tree-wrapper'];
classes.push.apply(classes, Object.keys(this._styles));
if (this.model.hasChildren()) {
classes.push('has-children');
}
this.element.className = classes.join(' ');
}
public insertInDOM(container: HTMLElement, afterElement: HTMLElement): void {
// noop
}
public removeFromDOM(): void {
// noop
}
}
function reactionEquals(one: _.IDragOverReaction, other: _.IDragOverReaction | null): boolean {
if (!one && !other) {
return true;
} else if (!one || !other) {
return false;
} else if (one.accept !== other.accept) {
return false;
} else if (one.bubble !== other.bubble) {
return false;
} else if (one.effect !== other.effect) {
return false;
} else {
return true;
}
}
export class TreeView extends HeightMap {
static readonly BINDING = 'monaco-tree-row';
static readonly LOADING_DECORATION_DELAY = 800;
private static counter: number = 0;
private instance: number;
private context: IViewContext;
private modelListeners: Lifecycle.IDisposable[];
private model: Model.TreeModel | null = null;
private viewListeners: Lifecycle.IDisposable[];
private domNode: HTMLElement;
private wrapper: HTMLElement;
private styleElement: HTMLStyleElement;
private treeStyler: _.ITreeStyler;
private rowsContainer: HTMLElement;
private scrollableElement: ScrollableElement;
private msGesture: MSGesture | undefined;
private lastPointerType: string = '';
private horizontalScrolling: boolean;
private contentWidthUpdateDelayer = new Delayer<void>(50);
private lastRenderTop: number;
private lastRenderHeight: number;
private inputItem!: ViewItem;
private items: { [id: string]: ViewItem; };
private isRefreshing = false;
private refreshingPreviousChildrenIds: { [id: string]: string[] } = {};
private currentDragAndDropData: IDragAndDropData | null = null;
private currentDropElement: any;
private currentDropElementReaction!: _.IDragOverReaction;
private currentDropTarget: ViewItem | null = null;
private shouldInvalidateDropReaction: boolean;
private currentDropTargets: ViewItem[] | null = null;
private currentDropDisposable: Lifecycle.IDisposable = Lifecycle.Disposable.None;
private gestureDisposable: Lifecycle.IDisposable = Lifecycle.Disposable.None;
private dragAndDropScrollInterval: number | null = null;
private dragAndDropScrollTimeout: number | null = null;
private dragAndDropMouseY: number | null = null;
private didJustPressContextMenuKey: boolean;
private highlightedItemWasDraggable: boolean = false;
private onHiddenScrollTop: number | null = null;
private readonly _onDOMFocus = new Emitter<void>();
readonly onDOMFocus: Event<void> = this._onDOMFocus.event;
private readonly _onDOMBlur = new Emitter<void>();
readonly onDOMBlur: Event<void> = this._onDOMBlur.event;
private readonly _onDidScroll = new Emitter<void>();
readonly onDidScroll: Event<void> = this._onDidScroll.event;
constructor(context: _.ITreeContext, container: HTMLElement) {
super();
TreeView.counter++;
this.instance = TreeView.counter;
const horizontalScrollMode = typeof context.options.horizontalScrollMode === 'undefined' ? ScrollbarVisibility.Hidden : context.options.horizontalScrollMode;
this.horizontalScrolling = horizontalScrollMode !== ScrollbarVisibility.Hidden;
this.context = {
dataSource: context.dataSource,
renderer: context.renderer,
controller: context.controller,
dnd: context.dnd,
filter: context.filter,
sorter: context.sorter,
tree: context.tree,
accessibilityProvider: context.accessibilityProvider,
options: context.options,
cache: new RowCache(context),
horizontalScrolling: this.horizontalScrolling
};
this.modelListeners = [];
this.viewListeners = [];
this.items = {};
this.domNode = document.createElement('div');
this.domNode.className = `monaco-tree no-focused-item monaco-tree-instance-${this.instance}`;
// to allow direct tabbing into the tree instead of first focusing the tree
this.domNode.tabIndex = context.options.preventRootFocus ? -1 : 0;
this.styleElement = DOM.createStyleSheet(this.domNode);
this.treeStyler = context.styler || new DefaultTreestyler(this.styleElement, `monaco-tree-instance-${this.instance}`);
// ARIA
this.domNode.setAttribute('role', 'tree');
if (this.context.options.ariaLabel) {
this.domNode.setAttribute('aria-label', this.context.options.ariaLabel);
}
if (this.context.options.alwaysFocused) {
DOM.addClass(this.domNode, 'focused');
}
if (!this.context.options.paddingOnRow) {
DOM.addClass(this.domNode, 'no-row-padding');
}
this.wrapper = document.createElement('div');
this.wrapper.className = 'monaco-tree-wrapper';
this.scrollableElement = new ScrollableElement(this.wrapper, {
alwaysConsumeMouseWheel: true,
horizontal: horizontalScrollMode,
vertical: (typeof context.options.verticalScrollMode !== 'undefined' ? context.options.verticalScrollMode : ScrollbarVisibility.Auto),
useShadows: context.options.useShadows
});
this.scrollableElement.onScroll((e) => {
this.render(e.scrollTop, e.height, e.scrollLeft, e.width, e.scrollWidth);
this._onDidScroll.fire();
});
this.gestureDisposable = Touch.Gesture.addTarget(this.wrapper);
this.rowsContainer = document.createElement('div');
this.rowsContainer.className = 'monaco-tree-rows';
if (context.options.showTwistie) {
this.rowsContainer.className += ' show-twisties';
}
let focusTracker = DOM.trackFocus(this.domNode);
this.viewListeners.push(focusTracker.onDidFocus(() => this.onFocus()));
this.viewListeners.push(focusTracker.onDidBlur(() => this.onBlur()));
this.viewListeners.push(focusTracker);
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'keydown', (e) => this.onKeyDown(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'keyup', (e) => this.onKeyUp(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'mousedown', (e) => this.onMouseDown(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'mouseup', (e) => this.onMouseUp(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'auxclick', (e: MouseEvent) => {
if (e && e.button === 1) {
this.onMouseMiddleClick(e);
}
}));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'click', (e) => this.onClick(e)));
this.viewListeners.push(DOM.addDisposableListener(this.domNode, 'contextmenu', (e) => this.onContextMenu(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, Touch.EventType.Tap, (e) => this.onTap(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, Touch.EventType.Change, (e) => this.onTouchChange(e)));
this.viewListeners.push(DOM.addDisposableListener(window, 'dragover', (e) => this.onDragOver(e)));
this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'drop', (e) => this.onDrop(e)));
this.viewListeners.push(DOM.addDisposableListener(window, 'dragend', (e) => this.onDragEnd(e)));
this.viewListeners.push(DOM.addDisposableListener(window, 'dragleave', (e) => this.onDragOver(e)));
this.wrapper.appendChild(this.rowsContainer);
this.domNode.appendChild(this.scrollableElement.getDomNode());
container.appendChild(this.domNode);
this.lastRenderTop = 0;
this.lastRenderHeight = 0;
this.didJustPressContextMenuKey = false;
this.currentDropTarget = null;
this.currentDropTargets = [];
this.shouldInvalidateDropReaction = false;
this.dragAndDropScrollInterval = null;
this.dragAndDropScrollTimeout = null;
this.onRowsChanged();
this.layout();
this.setupMSGesture();
this.applyStyles(context.options);
}
public applyStyles(styles: _.ITreeStyles): void {
this.treeStyler.style(styles);
}
protected createViewItem(item: Model.Item): IViewItem {
return new ViewItem(this.context, item);
}
public getHTMLElement(): HTMLElement {
return this.domNode;
}
public focus(): void {
this.domNode.focus();
}
public isFocused(): boolean {
return document.activeElement === this.domNode;
}
public blur(): void {
this.domNode.blur();
}
public onVisible(): void {
this.scrollTop = this.onHiddenScrollTop!;
this.onHiddenScrollTop = null;
this.setupMSGesture();
}
private setupMSGesture(): void {
if ((<any>window).MSGesture) {
this.msGesture = new MSGesture();
setTimeout(() => this.msGesture!.target = this.wrapper, 100); // TODO@joh, TODO@IETeam
}
}
public onHidden(): void {
this.onHiddenScrollTop = this.scrollTop;
}
private isTreeVisible(): boolean {
return this.onHiddenScrollTop === null;
}
public layout(height?: number, width?: number): void {
if (!this.isTreeVisible()) {
return;
}
this.viewHeight = height || DOM.getContentHeight(this.wrapper); // render
this.scrollHeight = this.getContentHeight();
if (this.horizontalScrolling) {
this.viewWidth = width || DOM.getContentWidth(this.wrapper);
}
}
private render(scrollTop: number, viewHeight: number, scrollLeft: number, viewWidth: number, scrollWidth: number): void {
let i: number;
let stop: number;
let renderTop = scrollTop;
let renderBottom = scrollTop + viewHeight;
let thisRenderBottom = this.lastRenderTop + this.lastRenderHeight;
// when view scrolls down, start rendering from the renderBottom
for (i = this.indexAfter(renderBottom) - 1, stop = this.indexAt(Math.max(thisRenderBottom, renderTop)); i >= stop; i--) {
this.insertItemInDOM(<ViewItem>this.itemAtIndex(i));
}
// when view scrolls up, start rendering from either this.renderTop or renderBottom
for (i = Math.min(this.indexAt(this.lastRenderTop), this.indexAfter(renderBottom)) - 1, stop = this.indexAt(renderTop); i >= stop; i--) {
this.insertItemInDOM(<ViewItem>this.itemAtIndex(i));
}
// when view scrolls down, start unrendering from renderTop
for (i = this.indexAt(this.lastRenderTop), stop = Math.min(this.indexAt(renderTop), this.indexAfter(thisRenderBottom)); i < stop; i++) {
this.removeItemFromDOM(<ViewItem>this.itemAtIndex(i));
}
// when view scrolls up, start unrendering from either renderBottom this.renderTop
for (i = Math.max(this.indexAfter(renderBottom), this.indexAt(this.lastRenderTop)), stop = this.indexAfter(thisRenderBottom); i < stop; i++) {
this.removeItemFromDOM(<ViewItem>this.itemAtIndex(i));
}
let topItem = this.itemAtIndex(this.indexAt(renderTop));
if (topItem) {
this.rowsContainer.style.top = (topItem.top - renderTop) + 'px';
}
if (this.horizontalScrolling) {
this.rowsContainer.style.left = -scrollLeft + 'px';
this.rowsContainer.style.width = `${Math.max(scrollWidth, viewWidth)}px`;
}
this.lastRenderTop = renderTop;
this.lastRenderHeight = renderBottom - renderTop;
}
public setModel(newModel: Model.TreeModel): void {
this.releaseModel();
this.model = newModel;
this.model.onRefresh(this.onRefreshing, this, this.modelListeners);
this.model.onDidRefresh(this.onRefreshed, this, this.modelListeners);
this.model.onSetInput(this.onClearingInput, this, this.modelListeners);
this.model.onDidSetInput(this.onSetInput, this, this.modelListeners);
this.model.onDidFocus(this.onModelFocusChange, this, this.modelListeners);
this.model.onRefreshItemChildren(this.onItemChildrenRefreshing, this, this.modelListeners);
this.model.onDidRefreshItemChildren(this.onItemChildrenRefreshed, this, this.modelListeners);
this.model.onDidRefreshItem(this.onItemRefresh, this, this.modelListeners);
this.model.onExpandItem(this.onItemExpanding, this, this.modelListeners);
this.model.onDidExpandItem(this.onItemExpanded, this, this.modelListeners);
this.model.onCollapseItem(this.onItemCollapsing, this, this.modelListeners);
this.model.onDidRevealItem(this.onItemReveal, this, this.modelListeners);
this.model.onDidAddTraitItem(this.onItemAddTrait, this, this.modelListeners);
this.model.onDidRemoveTraitItem(this.onItemRemoveTrait, this, this.modelListeners);
}
private onRefreshing(): void {
this.isRefreshing = true;
}
private onRefreshed(): void {
this.isRefreshing = false;
this.onRowsChanged();
}
private onRowsChanged(scrollTop: number = this.scrollTop): void {
if (this.isRefreshing) {
return;
}
this.scrollTop = scrollTop;
this.updateScrollWidth();
}
private updateScrollWidth(): void {
if (!this.horizontalScrolling) {
return;
}
this.contentWidthUpdateDelayer.trigger(() => {
const keys = Object.keys(this.items);
let scrollWidth = 0;
for (const key of keys) {
scrollWidth = Math.max(scrollWidth, this.items[key].width);
}
this.scrollWidth = scrollWidth + 10 /* scrollbar */;
});
}
public focusNextPage(eventPayload?: any): void {
let lastPageIndex = this.indexAt(this.scrollTop + this.viewHeight);
lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
let lastPageElement = this.itemAtIndex(lastPageIndex).model.getElement();
let currentlyFocusedElement = this.model!.getFocus();
if (currentlyFocusedElement !== lastPageElement) {
this.model!.setFocus(lastPageElement, eventPayload);
} else {
let previousScrollTop = this.scrollTop;
this.scrollTop += this.viewHeight;
if (this.scrollTop !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(() => {
this.focusNextPage(eventPayload);
}, 0);
}
}
}
public focusPreviousPage(eventPayload?: any): void {
let firstPageIndex: number;
if (this.scrollTop === 0) {
firstPageIndex = this.indexAt(this.scrollTop);
} else {
firstPageIndex = this.indexAfter(this.scrollTop - 1);
}
let firstPageElement = this.itemAtIndex(firstPageIndex).model.getElement();
let currentlyFocusedElement = this.model!.getFocus();
if (currentlyFocusedElement !== firstPageElement) {
this.model!.setFocus(firstPageElement, eventPayload);
} else {
let previousScrollTop = this.scrollTop;
this.scrollTop -= this.viewHeight;
if (this.scrollTop !== previousScrollTop) {
// Let the scroll event listener run
setTimeout(() => {
this.focusPreviousPage(eventPayload);
}, 0);
}
}
}
public get viewHeight() {
const scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.height;
}
public set viewHeight(height: number) {
this.scrollableElement.setScrollDimensions({ height });
}
private set scrollHeight(scrollHeight: number) {
scrollHeight = scrollHeight + (this.horizontalScrolling ? 10 : 0);
this.scrollableElement.setScrollDimensions({ scrollHeight });
}
public get viewWidth(): number {
const scrollDimensions = this.scrollableElement.getScrollDimensions();
return scrollDimensions.width;
}
public set viewWidth(viewWidth: number) {
this.scrollableElement.setScrollDimensions({ width: viewWidth });
}
private set scrollWidth(scrollWidth: number) {
this.scrollableElement.setScrollDimensions({ scrollWidth });
}
public get scrollTop(): number {
const scrollPosition = this.scrollableElement.getScrollPosition();
return scrollPosition.scrollTop;
}
public set scrollTop(scrollTop: number) {
const scrollHeight = this.getContentHeight() + (this.horizontalScrolling ? 10 : 0);
this.scrollableElement.setScrollDimensions({ scrollHeight });
this.scrollableElement.setScrollPosition({ scrollTop });
}
public getScrollPosition(): number {
const height = this.getContentHeight() - this.viewHeight;
return height <= 0 ? 1 : this.scrollTop / height;
}
public setScrollPosition(pos: number): void {
const height = this.getContentHeight() - this.viewHeight;
this.scrollTop = height * pos;
}
// Events
private onClearingInput(e: Model.IInputEvent): void {
let item = <Model.Item>e.item;
if (item) {
this.onRemoveItems(new MappedIterator(item.getNavigator(), item => item && item.id));
this.onRowsChanged();
}
}
private onSetInput(e: Model.IInputEvent): void {
this.context.cache.garbageCollect();
this.inputItem = new RootViewItem(this.context, <Model.Item>e.item, this.wrapper);
}
private onItemChildrenRefreshing(e: Model.IItemChildrenRefreshEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem && this.context.options.showLoading) {
viewItem.loadingTimer = setTimeout(() => {
viewItem.loadingTimer = 0;
viewItem.loading = true;
}, TreeView.LOADING_DECORATION_DELAY);
}
if (!e.isNested) {
let childrenIds: string[] = [];
let navigator = item.getNavigator();
let childItem: Model.Item | null;
while (childItem = navigator.next()) {
childrenIds.push(childItem.id);
}
this.refreshingPreviousChildrenIds[item.id] = childrenIds;
}
}
private onItemChildrenRefreshed(e: Model.IItemChildrenRefreshEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem) {
if (viewItem.loadingTimer) {
clearTimeout(viewItem.loadingTimer);
viewItem.loadingTimer = 0;
}
viewItem.loading = false;
}
if (!e.isNested) {
let previousChildrenIds = this.refreshingPreviousChildrenIds[item.id];
let afterModelItems: Model.Item[] = [];
let navigator = item.getNavigator();
let childItem: Model.Item | null;
while (childItem = navigator.next()) {
afterModelItems.push(childItem);
}
let skipDiff = Math.abs(previousChildrenIds.length - afterModelItems.length) > 1000;
let diff: Diff.IDiffChange[] = [];
let doToInsertItemsAlreadyExist: boolean = false;
if (!skipDiff) {
const lcs = new Diff.LcsDiff(
{
getElements: () => previousChildrenIds
},
{
getElements: () => afterModelItems.map(item => item.id)
},
null
);
diff = lcs.ComputeDiff(false).changes;
// this means that the result of the diff algorithm would result
// in inserting items that were already registered. this can only
// happen if the data provider returns bad ids OR if the sorting
// of the elements has changed
doToInsertItemsAlreadyExist = diff.some(d => {
if (d.modifiedLength > 0) {
for (let i = d.modifiedStart, len = d.modifiedStart + d.modifiedLength; i < len; i++) {
if (this.items.hasOwnProperty(afterModelItems[i].id)) {
return true;
}
}
}
return false;
});
}
// 50 is an optimization number, at some point we're better off
// just replacing everything
if (!skipDiff && !doToInsertItemsAlreadyExist && diff.length < 50) {
for (const diffChange of diff) {
if (diffChange.originalLength > 0) {
this.onRemoveItems(new ArrayIterator(previousChildrenIds, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength));
}
if (diffChange.modifiedLength > 0) {
let beforeItem: Model.Item | null = afterModelItems[diffChange.modifiedStart - 1] || item;
beforeItem = beforeItem.getDepth() > 0 ? beforeItem : null;
this.onInsertItems(new ArrayIterator(afterModelItems, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength), beforeItem ? beforeItem.id : null);
}
}
} else if (skipDiff || diff.length) {
this.onRemoveItems(new ArrayIterator(previousChildrenIds));
this.onInsertItems(new ArrayIterator(afterModelItems), item.getDepth() > 0 ? item.id : null);
}
if (skipDiff || diff.length) {
this.onRowsChanged();
}
}
}
private onItemRefresh(item: Model.Item): void {
this.onItemsRefresh([item]);
}
private onItemsRefresh(items: Model.Item[]): void {
this.onRefreshItemSet(items.filter(item => this.items.hasOwnProperty(item.id)));
this.onRowsChanged();
}
private onItemExpanding(e: Model.IItemExpandEvent): void {
let viewItem = this.items[e.item.id];
if (viewItem) {
viewItem.expanded = true;
}
}
private onItemExpanded(e: Model.IItemExpandEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.expanded = true;
let height = this.onInsertItems(item.getNavigator(), item.id) || 0;
let scrollTop = this.scrollTop;
if (viewItem.top + viewItem.height <= this.scrollTop) {
scrollTop += height;
}
this.onRowsChanged(scrollTop);
}
}
private onItemCollapsing(e: Model.IItemCollapseEvent): void {
let item = <Model.Item>e.item;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.expanded = false;
this.onRemoveItems(new MappedIterator(item.getNavigator(), item => item && item.id));
this.onRowsChanged();
}
}
private onItemReveal(e: Model.IItemRevealEvent): void {
let item = <Model.Item>e.item;
let relativeTop = <number>e.relativeTop;
let viewItem = this.items[item.id];
if (viewItem) {
if (relativeTop !== null) {
relativeTop = relativeTop < 0 ? 0 : relativeTop;
relativeTop = relativeTop > 1 ? 1 : relativeTop;
// y = mx + b
let m = viewItem.height - this.viewHeight;
this.scrollTop = m * relativeTop + viewItem.top;
} else {
let viewItemBottom = viewItem.top + viewItem.height;
let wrapperBottom = this.scrollTop + this.viewHeight;
if (viewItem.top < this.scrollTop) {
this.scrollTop = viewItem.top;
} else if (viewItemBottom >= wrapperBottom) {
this.scrollTop = viewItemBottom - this.viewHeight;
}
}
}
}
private onItemAddTrait(e: Model.IItemTraitEvent): void {
let item = <Model.Item>e.item;
let trait = <string>e.trait;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.addClass(trait);
}
if (trait === 'highlighted') {
DOM.addClass(this.domNode, trait);
// Ugly Firefox fix: input fields can't be selected if parent nodes are draggable
if (viewItem) {
this.highlightedItemWasDraggable = !!viewItem.draggable;
if (viewItem.draggable) {
viewItem.draggable = false;
}
}
}
}
private onItemRemoveTrait(e: Model.IItemTraitEvent): void {
let item = <Model.Item>e.item;
let trait = <string>e.trait;
let viewItem = this.items[item.id];
if (viewItem) {
viewItem.removeClass(trait);
}
if (trait === 'highlighted') {
DOM.removeClass(this.domNode, trait);
// Ugly Firefox fix: input fields can't be selected if parent nodes are draggable
if (this.highlightedItemWasDraggable) {
viewItem.draggable = true;
}
this.highlightedItemWasDraggable = false;
}
}
private onModelFocusChange(): void {
const focus = this.model && this.model.getFocus();
DOM.toggleClass(this.domNode, 'no-focused-item', !focus);
// ARIA
if (focus) {
this.domNode.setAttribute('aria-activedescendant', strings.safeBtoa(this.context.dataSource.getId(this.context.tree, focus)));
} else {
this.domNode.removeAttribute('aria-activedescendant');
}
}
// HeightMap "events"
public onInsertItem(item: ViewItem): void {
item.onDragStart = (e) => { this.onDragStart(item, e); };
item.needsRender = true;
this.refreshViewItem(item);
this.items[item.id] = item;
}
public onRefreshItem(item: ViewItem, needsRender = false): void {
item.needsRender = item.needsRender || needsRender;
this.refreshViewItem(item);
}
public onRemoveItem(item: ViewItem): void {
this.removeItemFromDOM(item);
item.dispose();
delete this.items[item.id];
}
// ViewItem refresh
private refreshViewItem(item: ViewItem): void {
item.render();
if (this.shouldBeRendered(item)) {
this.insertItemInDOM(item);
} else {
this.removeItemFromDOM(item);
}
}
// DOM Events
private onClick(e: MouseEvent): void {
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
let event = new Mouse.StandardMouseEvent(e);
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onClick(this.context.tree, item.model.getElement(), event);
}
private onMouseMiddleClick(e: MouseEvent): void {
if (!this.context.controller!.onMouseMiddleClick!) {
return;
}
let event = new Mouse.StandardMouseEvent(e);
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onMouseMiddleClick!(this.context.tree, item.model.getElement(), event);
}
private onMouseDown(e: MouseEvent): void {
this.didJustPressContextMenuKey = false;
if (!this.context.controller!.onMouseDown!) {
return;
}
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
let event = new Mouse.StandardMouseEvent(e);
if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) {
return;
}
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onMouseDown!(this.context.tree, item.model.getElement(), event);
}
private onMouseUp(e: MouseEvent): void {
if (!this.context.controller!.onMouseUp!) {
return;
}
if (this.lastPointerType && this.lastPointerType !== 'mouse') {
return;
}
let event = new Mouse.StandardMouseEvent(e);
if (event.ctrlKey && Platform.isNative && Platform.isMacintosh) {
return;
}
let item = this.getItemAround(event.target);
if (!item) {
return;
}
this.context.controller!.onMouseUp!(this.context.tree, item.model.getElement(), event);
}
private onTap(e: Touch.GestureEvent): void {
let item = this.getItemAround(<HTMLElement>e.initialTarget);
if (!item) {
return;
}
this.context.controller!.onTap(this.context.tree, item.model.getElement(), e);
}
private onTouchChange(event: Touch.GestureEvent): void {
event.preventDefault();
event.stopPropagation();
this.scrollTop -= event.translationY;
}
private onContextMenu(keyboardEvent: KeyboardEvent): void;
private onContextMenu(mouseEvent: MouseEvent): void;
private onContextMenu(event: KeyboardEvent | MouseEvent): void {
let resultEvent: _.ContextMenuEvent;
let element: any;
if (event instanceof KeyboardEvent || this.didJustPressContextMenuKey) {
this.didJustPressContextMenuKey = false;
let keyboardEvent = new Keyboard.StandardKeyboardEvent(<KeyboardEvent>event);
element = this.model!.getFocus();
let position: DOM.IDomNodePagePosition;
if (!element) {
element = this.model!.getInput();
position = DOM.getDomNodePagePosition(this.inputItem.element);
} else {
const id = this.context.dataSource.getId(this.context.tree, element);
const viewItem = this.items[id!];
position = DOM.getDomNodePagePosition(viewItem.element);
}
resultEvent = new _.KeyboardContextMenuEvent(position.left + position.width, position.top, keyboardEvent);
} else {
let mouseEvent = new Mouse.StandardMouseEvent(<MouseEvent>event);
let item = this.getItemAround(mouseEvent.target);
if (!item) {
return;
}
element = item.model.getElement();
resultEvent = new _.MouseContextMenuEvent(mouseEvent);
}
this.context.controller!.onContextMenu(this.context.tree, element, resultEvent);
}
private onKeyDown(e: KeyboardEvent): void {
let event = new Keyboard.StandardKeyboardEvent(e);
this.didJustPressContextMenuKey = event.keyCode === KeyCode.ContextMenu || (event.shiftKey && event.keyCode === KeyCode.F10);
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return; // Ignore event if target is a form input field (avoids browser specific issues)
}
if (this.didJustPressContextMenuKey) {
event.preventDefault();
event.stopPropagation();
}
this.context.controller!.onKeyDown(this.context.tree, event);
}
private onKeyUp(e: KeyboardEvent): void {
if (this.didJustPressContextMenuKey) {
this.onContextMenu(e);
}
this.didJustPressContextMenuKey = false;
this.context.controller!.onKeyUp(this.context.tree, new Keyboard.StandardKeyboardEvent(e));
}
private onDragStart(item: ViewItem, e: any): void {
if (this.model!.getHighlight()) {
return;
}
let element = item.model.getElement();
let selection = this.model!.getSelection();
let elements: any[];
if (selection.indexOf(element) > -1) {
elements = selection;
} else {
elements = [element];
}
e.dataTransfer.effectAllowed = 'copyMove';
e.dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify([item.uri]));
if (e.dataTransfer.setDragImage) {
let label: string;
if (this.context.dnd!.getDragLabel) {
label = this.context.dnd!.getDragLabel!(this.context.tree, elements);
} else {
label = String(elements.length);
}
const dragImage = document.createElement('div');
dragImage.className = 'monaco-tree-drag-image';
dragImage.textContent = label;
document.body.appendChild(dragImage);
e.dataTransfer.setDragImage(dragImage, -10, -10);
setTimeout(() => document.body.removeChild(dragImage), 0);
}
this.currentDragAndDropData = new dnd.ElementsDragAndDropData(elements);
StaticDND.CurrentDragAndDropData = new dnd.ExternalElementsDragAndDropData(elements);
this.context.dnd!.onDragStart(this.context.tree, this.currentDragAndDropData, new Mouse.DragMouseEvent(e));
}
private setupDragAndDropScrollInterval(): void {
let viewTop = DOM.getTopLeftOffset(this.wrapper).top;
if (!this.dragAndDropScrollInterval) {
this.dragAndDropScrollInterval = window.setInterval(() => {
if (this.dragAndDropMouseY === null) {
return;
}
let diff = this.dragAndDropMouseY - viewTop;
let scrollDiff = 0;
let upperLimit = this.viewHeight - 35;
if (diff < 35) {
scrollDiff = Math.max(-14, 0.2 * (diff - 35));
} else if (diff > upperLimit) {
scrollDiff = Math.min(14, 0.2 * (diff - upperLimit));
}
this.scrollTop += scrollDiff;
}, 10);
this.cancelDragAndDropScrollTimeout();
this.dragAndDropScrollTimeout = window.setTimeout(() => {
this.cancelDragAndDropScrollInterval();
this.dragAndDropScrollTimeout = null;
}, 1000);
}
}
private cancelDragAndDropScrollInterval(): void {
if (this.dragAndDropScrollInterval) {
window.clearInterval(this.dragAndDropScrollInterval);
this.dragAndDropScrollInterval = null;
}
this.cancelDragAndDropScrollTimeout();
}
private cancelDragAndDropScrollTimeout(): void {
if (this.dragAndDropScrollTimeout) {
window.clearTimeout(this.dragAndDropScrollTimeout);
this.dragAndDropScrollTimeout = null;
}
}
private onDragOver(e: DragEvent): boolean {
e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
let event = new Mouse.DragMouseEvent(e);
let viewItem = this.getItemAround(event.target);
if (!viewItem || (event.posx === 0 && event.posy === 0 && event.browserEvent.type === DOM.EventType.DRAG_LEAVE)) {
// dragging outside of tree
if (this.currentDropTarget) {
// clear previously hovered element feedback
this.currentDropTargets!.forEach(i => i.dropTarget = false);
this.currentDropTargets = [];
this.currentDropDisposable.dispose();
}
this.cancelDragAndDropScrollInterval();
this.currentDropTarget = null;
this.currentDropElement = null;
this.dragAndDropMouseY = null;
return false;
}
// dragging inside the tree
this.setupDragAndDropScrollInterval();
this.dragAndDropMouseY = event.posy;
if (!this.currentDragAndDropData) {
// just started dragging
if (StaticDND.CurrentDragAndDropData) {
this.currentDragAndDropData = StaticDND.CurrentDragAndDropData;
} else {
if (!event.dataTransfer.types) {
return false;
}
this.currentDragAndDropData = new dnd.DesktopDragAndDropData();
}
}
this.currentDragAndDropData.update((event.browserEvent as DragEvent).dataTransfer!);
let element: any;
let item: Model.Item | null = viewItem.model;
let reaction: _.IDragOverReaction | null;
// check the bubble up behavior
do {
element = item ? item.getElement() : this.model!.getInput();
reaction = this.context.dnd!.onDragOver(this.context.tree, this.currentDragAndDropData, element, event);
if (!reaction || reaction.bubble !== _.DragOverBubble.BUBBLE_UP) {
break;
}
item = item && item.parent;
} while (item);
if (!item) {
this.currentDropElement = null;
return false;
}
let canDrop = reaction && reaction.accept;
if (canDrop) {
this.currentDropElement = item.getElement();
event.preventDefault();
event.dataTransfer.dropEffect = reaction!.effect === _.DragOverEffect.COPY ? 'copy' : 'move';
} else {
this.currentDropElement = null;
}
// item is the model item where drop() should be called
// can be null
let currentDropTarget = item.id === this.inputItem.id ? this.inputItem : this.items[item.id];
if (this.shouldInvalidateDropReaction || this.currentDropTarget !== currentDropTarget || !reactionEquals(this.currentDropElementReaction, reaction)) {
this.shouldInvalidateDropReaction = false;
if (this.currentDropTarget) {
this.currentDropTargets!.forEach(i => i.dropTarget = false);
this.currentDropTargets = [];
this.currentDropDisposable.dispose();
}
this.currentDropTarget = currentDropTarget;
this.currentDropElementReaction = reaction!;
if (canDrop) {
// setup hover feedback for drop target
if (this.currentDropTarget) {
this.currentDropTarget.dropTarget = true;
this.currentDropTargets!.push(this.currentDropTarget);
}
if (reaction!.bubble === _.DragOverBubble.BUBBLE_DOWN) {
let nav = item.getNavigator();
let child: Model.Item | null;
while (child = nav.next()) {
viewItem = this.items[child.id];
if (viewItem) {
viewItem.dropTarget = true;
this.currentDropTargets!.push(viewItem);
}
}
}
if (reaction!.autoExpand) {
const timeoutPromise = timeout(500);
this.currentDropDisposable = Lifecycle.toDisposable(() => timeoutPromise.cancel());
timeoutPromise
.then(() => this.context.tree.expand(this.currentDropElement))
.then(() => this.shouldInvalidateDropReaction = true);
}
}
}
return true;
}
private onDrop(e: DragEvent): void {
if (this.currentDropElement) {
let event = new Mouse.DragMouseEvent(e);
event.preventDefault();
this.currentDragAndDropData!.update((event.browserEvent as DragEvent).dataTransfer!);
this.context.dnd!.drop(this.context.tree, this.currentDragAndDropData!, this.currentDropElement, event);
this.onDragEnd(e);
}
this.cancelDragAndDropScrollInterval();
}
private onDragEnd(e: DragEvent): void {
if (this.currentDropTarget) {
this.currentDropTargets!.forEach(i => i.dropTarget = false);
this.currentDropTargets = [];
}
this.currentDropDisposable.dispose();
this.cancelDragAndDropScrollInterval();
this.currentDragAndDropData = null;
StaticDND.CurrentDragAndDropData = undefined;
this.currentDropElement = null;
this.currentDropTarget = null;
this.dragAndDropMouseY = null;
}
private onFocus(): void {
if (!this.context.options.alwaysFocused) {
DOM.addClass(this.domNode, 'focused');
}
this._onDOMFocus.fire();
}
private onBlur(): void {
if (!this.context.options.alwaysFocused) {
DOM.removeClass(this.domNode, 'focused');
}
this.domNode.removeAttribute('aria-activedescendant'); // ARIA
this._onDOMBlur.fire();
}
// DOM changes
private insertItemInDOM(item: ViewItem): void {
let elementAfter: HTMLElement | null = null;
let itemAfter = <ViewItem>this.itemAfter(item);
if (itemAfter && itemAfter.element) {
elementAfter = itemAfter.element;
}
item.insertInDOM(this.rowsContainer, elementAfter);
}
private removeItemFromDOM(item: ViewItem): void {
if (!item) {
return;
}
item.removeFromDOM();
}
// Helpers
private shouldBeRendered(item: ViewItem): boolean {
return item.top < this.lastRenderTop + this.lastRenderHeight && item.top + item.height > this.lastRenderTop;
}
private getItemAround(element: HTMLElement): ViewItem | undefined {
let candidate: ViewItem = this.inputItem;
let el: HTMLElement | null = element;
do {
if ((<any>el)[TreeView.BINDING]) {
candidate = (<any>el)[TreeView.BINDING];
}
if (el === this.wrapper || el === this.domNode) {
return candidate;
}
if (el === this.scrollableElement.getDomNode() || el === document.body) {
return undefined;
}
} while (el = el.parentElement);
return undefined;
}
// Cleanup
private releaseModel(): void {
if (this.model) {
this.modelListeners = Lifecycle.dispose(this.modelListeners);
this.model = null;
}
}
public dispose(): void {
// TODO@joao: improve
this.scrollableElement.dispose();
this.releaseModel();
this.viewListeners = Lifecycle.dispose(this.viewListeners);
this._onDOMFocus.dispose();
this._onDOMBlur.dispose();
if (this.domNode.parentNode) {
this.domNode.parentNode.removeChild(this.domNode);
}
if (this.items) {
Object.keys(this.items).forEach(key => this.items[key].removeFromDOM());
}
if (this.context.cache) {
this.context.cache.dispose();
}
this.gestureDisposable.dispose();
super.dispose();
}
}
| src/vs/base/parts/tree/browser/treeView.ts | 1 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.9980667233467102,
0.007113163825124502,
0.00016358600987587124,
0.00017009679868351668,
0.07817014306783676
] |
{
"id": 6,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'false');\n",
"\t\t}\n",
"\t\tif (this.model.hasChildren()) {\n",
"\t\t\tthis.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.element.removeAttribute('id');\n"
],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "add",
"edit_start_line_idx": 227
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ISpliceable } from 'vs/base/common/sequence';
export interface ISpreadSpliceable<T> {
splice(start: number, deleteCount: number, ...elements: T[]): void;
}
export class CombinedSpliceable<T> implements ISpliceable<T> {
constructor(private spliceables: ISpliceable<T>[]) { }
splice(start: number, deleteCount: number, elements: T[]): void {
this.spliceables.forEach(s => s.splice(start, deleteCount, elements));
}
} | src/vs/base/browser/ui/list/splice.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.0001714024692773819,
0.00016837171278893948,
0.00016534095630049706,
0.00016837171278893948,
0.000003030756488442421
] |
{
"id": 6,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'false');\n",
"\t\t}\n",
"\t\tif (this.model.hasChildren()) {\n",
"\t\t\tthis.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.element.removeAttribute('id');\n"
],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "add",
"edit_start_line_idx": 227
} | /*---------------------------------------------------------------------------------------------
* 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 dom from 'vs/base/browser/dom';
import { generateUuid } from 'vs/base/common/uuid';
import { appendStylizedStringToContainer, handleANSIOutput, calcANSI8bitColor } from 'vs/workbench/contrib/debug/browser/debugANSIHandling';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices';
import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector';
import { Color, RGBA } from 'vs/base/common/color';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { TestThemeService, TestColorTheme } from 'vs/platform/theme/test/common/testThemeService';
import { ansiColorMap } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';
import { DebugModel } from 'vs/workbench/contrib/debug/common/debugModel';
import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';
import { NullOpenerService } from 'vs/platform/opener/common/opener';
suite('Debug - ANSI Handling', () => {
let model: DebugModel;
let session: DebugSession;
let linkDetector: LinkDetector;
let themeService: IThemeService;
/**
* Instantiate services for use by the functions being tested.
*/
setup(() => {
model = new DebugModel([], [], [], [], [], <any>{ isDirty: (e: any) => false });
session = new DebugSession(generateUuid(), { resolved: { name: 'test', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, NullOpenerService, undefined!, undefined!);
const instantiationService: TestInstantiationService = <TestInstantiationService>workbenchInstantiationService();
linkDetector = instantiationService.createInstance(LinkDetector);
const colors: { [id: string]: string; } = {};
for (let color in ansiColorMap) {
colors[color] = <any>ansiColorMap[color].defaults.dark;
}
const testTheme = new TestColorTheme(colors);
themeService = new TestThemeService(testTheme);
});
test('appendStylizedStringToContainer', () => {
const root: HTMLSpanElement = document.createElement('span');
let child: Node;
assert.equal(0, root.children.length);
appendStylizedStringToContainer(root, 'content1', ['class1', 'class2'], linkDetector, session);
appendStylizedStringToContainer(root, 'content2', ['class2', 'class3'], linkDetector, session);
assert.equal(2, root.children.length);
child = root.firstChild!;
if (child instanceof HTMLSpanElement) {
assert.equal('content1', child.textContent);
assert(dom.hasClass(child, 'class1'));
assert(dom.hasClass(child, 'class2'));
} else {
assert.fail('Unexpected assertion error');
}
child = root.lastChild!;
if (child instanceof HTMLSpanElement) {
assert.equal('content2', child.textContent);
assert(dom.hasClass(child, 'class2'));
assert(dom.hasClass(child, 'class3'));
} else {
assert.fail('Unexpected assertion error');
}
});
/**
* Apply an ANSI sequence to {@link #getSequenceOutput}.
*
* @param sequence The ANSI sequence to stylize.
* @returns An {@link HTMLSpanElement} that contains the stylized text.
*/
function getSequenceOutput(sequence: string): HTMLSpanElement {
const root: HTMLSpanElement = handleANSIOutput(sequence, linkDetector, themeService, session);
assert.equal(1, root.children.length);
const child: Node = root.lastChild!;
if (child instanceof HTMLSpanElement) {
return child;
} else {
assert.fail('Unexpected assertion error');
return null!;
}
}
/**
* Assert that a given ANSI sequence maintains added content following the ANSI code, and that
* the provided {@param assertion} passes.
*
* @param sequence The ANSI sequence to verify. The provided sequence should contain ANSI codes
* only, and should not include actual text content as it is provided by this function.
* @param assertion The function used to verify the output.
*/
function assertSingleSequenceElement(sequence: string, assertion: (child: HTMLSpanElement) => void): void {
const child: HTMLSpanElement = getSequenceOutput(sequence + 'content');
assert.equal('content', child.textContent);
assertion(child);
}
/**
* Assert that a given DOM element has the custom inline CSS style matching
* the color value provided.
* @param element The HTML span element to look at.
* @param colorType If `foreground`, will check the element's css `color`;
* if `background`, will check the element's css `backgroundColor`.
* @param color RGBA object to compare color to. If `undefined` or not provided,
* will assert that no value is set.
* @param message Optional custom message to pass to assertion.
*/
function assertInlineColor(element: HTMLSpanElement, colorType: 'background' | 'foreground', color?: RGBA | undefined, message?: string): void {
if (color !== undefined) {
const cssColor = Color.Format.CSS.formatRGB(
new Color(color)
);
if (colorType === 'background') {
const styleBefore = element.style.backgroundColor;
element.style.backgroundColor = cssColor;
assert(styleBefore === element.style.backgroundColor, message || `Incorrect ${colorType} color style found (found color: ${styleBefore}, expected ${cssColor}).`);
} else {
const styleBefore = element.style.color;
element.style.color = cssColor;
assert(styleBefore === element.style.color, message || `Incorrect ${colorType} color style found (found color: ${styleBefore}, expected ${cssColor}).`);
}
} else {
if (colorType === 'background') {
assert(!element.style.backgroundColor, message || `Defined ${colorType} color style found when it should not have been defined`);
} else {
assert(!element.style.color, message || `Defined ${colorType} color style found when it should not have been defined`);
}
}
}
test('Expected single sequence operation', () => {
// Bold code
assertSingleSequenceElement('\x1b[1m', (child) => {
assert(dom.hasClass(child, 'code-bold'), 'Bold formatting not detected after bold ANSI code.');
});
// Italic code
assertSingleSequenceElement('\x1b[3m', (child) => {
assert(dom.hasClass(child, 'code-italic'), 'Italic formatting not detected after italic ANSI code.');
});
// Underline code
assertSingleSequenceElement('\x1b[4m', (child) => {
assert(dom.hasClass(child, 'code-underline'), 'Underline formatting not detected after underline ANSI code.');
});
for (let i = 30; i <= 37; i++) {
const customClassName: string = 'code-foreground-colored';
// Foreground colour class
assertSingleSequenceElement('\x1b[' + i + 'm', (child) => {
assert(dom.hasClass(child, customClassName), `Custom foreground class not found on element after foreground ANSI code #${i}.`);
});
// Cancellation code removes colour class
assertSingleSequenceElement('\x1b[' + i + ';39m', (child) => {
assert(dom.hasClass(child, customClassName) === false, 'Custom foreground class still found after foreground cancellation code.');
assertInlineColor(child, 'foreground', undefined, 'Custom color style still found after foreground cancellation code.');
});
}
for (let i = 40; i <= 47; i++) {
const customClassName: string = 'code-background-colored';
// Foreground colour class
assertSingleSequenceElement('\x1b[' + i + 'm', (child) => {
assert(dom.hasClass(child, customClassName), `Custom background class not found on element after background ANSI code #${i}.`);
});
// Cancellation code removes colour class
assertSingleSequenceElement('\x1b[' + i + ';49m', (child) => {
assert(dom.hasClass(child, customClassName) === false, 'Custom background class still found after background cancellation code.');
assertInlineColor(child, 'foreground', undefined, 'Custom color style still found after background cancellation code.');
});
}
// Different codes do not cancel each other
assertSingleSequenceElement('\x1b[1;3;4;30;41m', (child) => {
assert.equal(5, child.classList.length, 'Incorrect number of classes found for different ANSI codes.');
assert(dom.hasClass(child, 'code-bold'));
assert(dom.hasClass(child, 'code-italic'), 'Different ANSI codes should not cancel each other.');
assert(dom.hasClass(child, 'code-underline'), 'Different ANSI codes should not cancel each other.');
assert(dom.hasClass(child, 'code-foreground-colored'), 'Different ANSI codes should not cancel each other.');
assert(dom.hasClass(child, 'code-background-colored'), 'Different ANSI codes should not cancel each other.');
});
// New foreground codes don't remove old background codes and vice versa
assertSingleSequenceElement('\x1b[40;31;42;33m', (child) => {
assert.equal(2, child.classList.length);
assert(dom.hasClass(child, 'code-background-colored'), 'New foreground ANSI code should not cancel existing background formatting.');
assert(dom.hasClass(child, 'code-foreground-colored'), 'New background ANSI code should not cancel existing foreground formatting.');
});
// Duplicate codes do not change output
assertSingleSequenceElement('\x1b[1;1;4;1;4;4;1;4m', (child) => {
assert(dom.hasClass(child, 'code-bold'), 'Duplicate formatting codes should have no effect.');
assert(dom.hasClass(child, 'code-underline'), 'Duplicate formatting codes should have no effect.');
});
// Extra terminating semicolon does not change output
assertSingleSequenceElement('\x1b[1;4;m', (child) => {
assert(dom.hasClass(child, 'code-bold'), 'Extra semicolon after ANSI codes should have no effect.');
assert(dom.hasClass(child, 'code-underline'), 'Extra semicolon after ANSI codes should have no effect.');
});
// Cancellation code removes multiple codes
assertSingleSequenceElement('\x1b[1;4;30;41;32;43;34;45;36;47;0m', (child) => {
assert.equal(0, child.classList.length, 'Cancellation ANSI code should clear ALL formatting.');
assertInlineColor(child, 'background', undefined, 'Cancellation ANSI code should clear ALL formatting.');
assertInlineColor(child, 'foreground', undefined, 'Cancellation ANSI code should clear ALL formatting.');
});
});
test('Expected single 8-bit color sequence operation', () => {
// Basic and bright color codes specified with 8-bit color code format
for (let i = 0; i <= 15; i++) {
// As these are controlled by theme, difficult to check actual color value
// Foreground codes should add standard classes
assertSingleSequenceElement('\x1b[38;5;' + i + 'm', (child) => {
assert(dom.hasClass(child, 'code-foreground-colored'), `Custom color class not found after foreground 8-bit color code 38;5;${i}`);
});
// Background codes should add standard classes
assertSingleSequenceElement('\x1b[48;5;' + i + 'm', (child) => {
assert(dom.hasClass(child, 'code-background-colored'), `Custom color class not found after background 8-bit color code 48;5;${i}`);
});
}
// 8-bit advanced colors
for (let i = 16; i <= 255; i++) {
// Foreground codes should add custom class and inline style
assertSingleSequenceElement('\x1b[38;5;' + i + 'm', (child) => {
assert(dom.hasClass(child, 'code-foreground-colored'), `Custom color class not found after foreground 8-bit color code 38;5;${i}`);
assertInlineColor(child, 'foreground', (calcANSI8bitColor(i) as RGBA), `Incorrect or no color styling found after foreground 8-bit color code 38;5;${i}`);
});
// Background codes should add custom class and inline style
assertSingleSequenceElement('\x1b[48;5;' + i + 'm', (child) => {
assert(dom.hasClass(child, 'code-background-colored'), `Custom color class not found after background 8-bit color code 48;5;${i}`);
assertInlineColor(child, 'background', (calcANSI8bitColor(i) as RGBA), `Incorrect or no color styling found after background 8-bit color code 48;5;${i}`);
});
}
// Bad (nonexistent) color should not render
assertSingleSequenceElement('\x1b[48;5;300m', (child) => {
assert.equal(0, child.classList.length, 'Bad ANSI color codes should have no effect.');
});
// Should ignore any codes after the ones needed to determine color
assertSingleSequenceElement('\x1b[48;5;100;42;77;99;4;24m', (child) => {
assert(dom.hasClass(child, 'code-background-colored'));
assert.equal(1, child.classList.length);
assertInlineColor(child, 'background', (calcANSI8bitColor(100) as RGBA));
});
});
test('Expected single 24-bit color sequence operation', () => {
// 24-bit advanced colors
for (let r = 0; r <= 255; r += 64) {
for (let g = 0; g <= 255; g += 64) {
for (let b = 0; b <= 255; b += 64) {
let color = new RGBA(r, g, b);
// Foreground codes should add class and inline style
assertSingleSequenceElement(`\x1b[38;2;${r};${g};${b}m`, (child) => {
assert(dom.hasClass(child, 'code-foreground-colored'), 'DOM should have "code-foreground-colored" class for advanced ANSI colors.');
assertInlineColor(child, 'foreground', color);
});
// Background codes should add class and inline style
assertSingleSequenceElement(`\x1b[48;2;${r};${g};${b}m`, (child) => {
assert(dom.hasClass(child, 'code-background-colored'), 'DOM should have "code-foreground-colored" class for advanced ANSI colors.');
assertInlineColor(child, 'background', color);
});
}
}
}
// Invalid color should not render
assertSingleSequenceElement('\x1b[38;2;4;4m', (child) => {
assert.equal(0, child.classList.length, `Invalid color code "38;2;4;4" should not add a class (classes found: ${child.classList}).`);
assert(!child.style.color, `Invalid color code "38;2;4;4" should not add a custom color CSS (found color: ${child.style.color}).`);
});
// Bad (nonexistent) color should not render
assertSingleSequenceElement('\x1b[48;2;150;300;5m', (child) => {
assert.equal(0, child.classList.length, `Nonexistent color code "48;2;150;300;5" should not add a class (classes found: ${child.classList}).`);
});
// Should ignore any codes after the ones needed to determine color
assertSingleSequenceElement('\x1b[48;2;100;42;77;99;200;75m', (child) => {
assert(dom.hasClass(child, 'code-background-colored'), `Color code with extra (valid) items "48;2;100;42;77;99;200;75" should still treat initial part as valid code and add class "code-background-custom".`);
assert.equal(1, child.classList.length, `Color code with extra items "48;2;100;42;77;99;200;75" should add one and only one class. (classes found: ${child.classList}).`);
assertInlineColor(child, 'background', new RGBA(100, 42, 77), `Color code "48;2;100;42;77;99;200;75" should style background-color as rgb(100,42,77).`);
});
});
/**
* Assert that a given ANSI sequence produces the expected number of {@link HTMLSpanElement} children. For
* each child, run the provided assertion.
*
* @param sequence The ANSI sequence to verify.
* @param assertions A set of assertions to run on the resulting children.
*/
function assertMultipleSequenceElements(sequence: string, assertions: Array<(child: HTMLSpanElement) => void>, elementsExpected?: number): void {
if (elementsExpected === undefined) {
elementsExpected = assertions.length;
}
const root: HTMLSpanElement = handleANSIOutput(sequence, linkDetector, themeService, session);
assert.equal(elementsExpected, root.children.length);
for (let i = 0; i < elementsExpected; i++) {
const child: Node = root.children[i];
if (child instanceof HTMLSpanElement) {
assertions[i](child);
} else {
assert.fail('Unexpected assertion error');
}
}
}
test('Expected multiple sequence operation', () => {
// Multiple codes affect the same text
assertSingleSequenceElement('\x1b[1m\x1b[3m\x1b[4m\x1b[32m', (child) => {
assert(dom.hasClass(child, 'code-bold'), 'Bold class not found after multiple different ANSI codes.');
assert(dom.hasClass(child, 'code-italic'), 'Italic class not found after multiple different ANSI codes.');
assert(dom.hasClass(child, 'code-underline'), 'Underline class not found after multiple different ANSI codes.');
assert(dom.hasClass(child, 'code-foreground-colored'), 'Foreground color class not found after multiple different ANSI codes.');
});
// Consecutive codes do not affect previous ones
assertMultipleSequenceElements('\x1b[1mbold\x1b[32mgreen\x1b[4munderline\x1b[3mitalic\x1b[0mnothing', [
(bold) => {
assert.equal(1, bold.classList.length);
assert(dom.hasClass(bold, 'code-bold'), 'Bold class not found after bold ANSI code.');
},
(green) => {
assert.equal(2, green.classList.length);
assert(dom.hasClass(green, 'code-bold'), 'Bold class not found after both bold and color ANSI codes.');
assert(dom.hasClass(green, 'code-foreground-colored'), 'Color class not found after color ANSI code.');
},
(underline) => {
assert.equal(3, underline.classList.length);
assert(dom.hasClass(underline, 'code-bold'), 'Bold class not found after bold, color, and underline ANSI codes.');
assert(dom.hasClass(underline, 'code-foreground-colored'), 'Color class not found after color and underline ANSI codes.');
assert(dom.hasClass(underline, 'code-underline'), 'Underline class not found after underline ANSI code.');
},
(italic) => {
assert.equal(4, italic.classList.length);
assert(dom.hasClass(italic, 'code-bold'), 'Bold class not found after bold, color, underline, and italic ANSI codes.');
assert(dom.hasClass(italic, 'code-foreground-colored'), 'Color class not found after color, underline, and italic ANSI codes.');
assert(dom.hasClass(italic, 'code-underline'), 'Underline class not found after underline and italic ANSI codes.');
assert(dom.hasClass(italic, 'code-italic'), 'Italic class not found after italic ANSI code.');
},
(nothing) => {
assert.equal(0, nothing.classList.length, 'One or more style classes still found after reset ANSI code.');
},
], 5);
// Different types of color codes still cancel each other
assertMultipleSequenceElements('\x1b[34msimple\x1b[38;2;100;100;100m24bit\x1b[38;5;3m8bitsimple\x1b[38;5;101m8bitadvanced', [
(simple) => {
assert.equal(1, simple.classList.length, 'Foreground ANSI color code should add one class.');
assert(dom.hasClass(simple, 'code-foreground-colored'), 'Foreground ANSI color codes should add custom foreground color class.');
},
(adv24Bit) => {
assert.equal(1, adv24Bit.classList.length, 'Multiple foreground ANSI color codes should only add a single class.');
assert(dom.hasClass(adv24Bit, 'code-foreground-colored'), 'Foreground ANSI color codes should add custom foreground color class.');
assertInlineColor(adv24Bit, 'foreground', new RGBA(100, 100, 100), '24-bit RGBA ANSI color code (100,100,100) should add matching color inline style.');
},
(adv8BitSimple) => {
assert.equal(1, adv8BitSimple.classList.length, 'Multiple foreground ANSI color codes should only add a single class.');
assert(dom.hasClass(adv8BitSimple, 'code-foreground-colored'), 'Foreground ANSI color codes should add custom foreground color class.');
// Won't assert color because it's theme based
},
(adv8BitAdvanced) => {
assert.equal(1, adv8BitAdvanced.classList.length, 'Multiple foreground ANSI color codes should only add a single class.');
assert(dom.hasClass(adv8BitAdvanced, 'code-foreground-colored'), 'Foreground ANSI color codes should add custom foreground color class.');
}
], 4);
});
/**
* Assert that the provided ANSI sequence exactly matches the text content of the resulting
* {@link HTMLSpanElement}.
*
* @param sequence The ANSI sequence to verify.
*/
function assertSequenceEqualToContent(sequence: string): void {
const child: HTMLSpanElement = getSequenceOutput(sequence);
assert(child.textContent === sequence);
}
test('Invalid codes treated as regular text', () => {
// Individual components of ANSI code start are printed
assertSequenceEqualToContent('\x1b');
assertSequenceEqualToContent('[');
// Unsupported sequence prints both characters
assertSequenceEqualToContent('\x1b[');
// Random strings are displayed properly
for (let i = 0; i < 50; i++) {
const uuid: string = generateUuid();
assertSequenceEqualToContent(uuid);
}
});
/**
* Assert that a given ANSI sequence maintains added content following the ANSI code, and that
* the expression itself is thrown away.
*
* @param sequence The ANSI sequence to verify. The provided sequence should contain ANSI codes
* only, and should not include actual text content as it is provided by this function.
*/
function assertEmptyOutput(sequence: string) {
const child: HTMLSpanElement = getSequenceOutput(sequence + 'content');
assert.equal('content', child.textContent);
assert.equal(0, child.classList.length);
}
test('Empty sequence output', () => {
const sequences: string[] = [
// No colour codes
'',
'\x1b[;m',
'\x1b[1;;m',
'\x1b[m',
'\x1b[99m'
];
sequences.forEach(sequence => {
assertEmptyOutput(sequence);
});
// Check other possible ANSI terminators
const terminators: string[] = 'ABCDHIJKfhmpsu'.split('');
terminators.forEach(terminator => {
assertEmptyOutput('\x1b[content' + terminator);
});
});
test('calcANSI8bitColor', () => {
// Invalid values
// Negative (below range), simple range, decimals
for (let i = -10; i <= 15; i += 0.5) {
assert(calcANSI8bitColor(i) === undefined, 'Values less than 16 passed to calcANSI8bitColor should return undefined.');
}
// In-range range decimals
for (let i = 16.5; i < 254; i += 1) {
assert(calcANSI8bitColor(i) === undefined, 'Floats passed to calcANSI8bitColor should return undefined.');
}
// Above range
for (let i = 256; i < 300; i += 0.5) {
assert(calcANSI8bitColor(i) === undefined, 'Values grather than 255 passed to calcANSI8bitColor should return undefined.');
}
// All valid colors
for (let red = 0; red <= 5; red++) {
for (let green = 0; green <= 5; green++) {
for (let blue = 0; blue <= 5; blue++) {
let colorOut: any = calcANSI8bitColor(16 + red * 36 + green * 6 + blue);
assert(colorOut.r === Math.round(red * (255 / 5)), 'Incorrect red value encountered for color');
assert(colorOut.g === Math.round(green * (255 / 5)), 'Incorrect green value encountered for color');
assert(colorOut.b === Math.round(blue * (255 / 5)), 'Incorrect balue value encountered for color');
}
}
}
// All grays
for (let i = 232; i <= 255; i++) {
let grayOut: any = calcANSI8bitColor(i);
assert(grayOut.r === grayOut.g);
assert(grayOut.r === grayOut.b);
assert(grayOut.r === Math.round((i - 232) / 23 * 255));
}
});
});
| src/vs/workbench/contrib/debug/test/electron-browser/debugANSIHandling.test.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.001336219604127109,
0.00019481562776491046,
0.00016364060866180807,
0.00017152867803815752,
0.00016166629211511463
] |
{
"id": 6,
"code_window": [
"\t\t\tthis.element.setAttribute('aria-selected', 'true');\n",
"\t\t} else {\n",
"\t\t\tthis.element.setAttribute('aria-selected', 'false');\n",
"\t\t}\n",
"\t\tif (this.model.hasChildren()) {\n",
"\t\t\tthis.element.setAttribute('aria-expanded', String(!!this._styles['expanded']));\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.element.removeAttribute('id');\n"
],
"file_path": "src/vs/base/parts/tree/browser/treeView.ts",
"type": "add",
"edit_start_line_idx": 227
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import './menuPreventer';
import './accessibility/accessibility';
import './diffEditorHelper';
import './inspectKeybindings';
import './largeFileOptimizations';
import './inspectEditorTokens/inspectEditorTokens';
import './saveParticipants';
import './toggleColumnSelection';
import './toggleMinimap';
import './toggleMultiCursorModifier';
import './toggleRenderControlCharacter';
import './toggleRenderWhitespace';
import './toggleWordWrap';
import './workbenchReferenceSearch';
| src/vs/workbench/contrib/codeEditor/browser/codeEditor.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f | [
0.00017690396634861827,
0.00017649770597927272,
0.0001760914601618424,
0.00017649770597927272,
4.062530933879316e-7
] |
{
"id": 0,
"code_window": [
"\t},\n",
"\t\"view.workbench.scm.scanWorkspaceForRepositories\": {\n",
"\t\t\"message\": \"Scanning workspace for git repositories...\"\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepository\": {\n",
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 332
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { workspace, WorkspaceFoldersChangeEvent, Uri, window, Event, EventEmitter, QuickPickItem, Disposable, SourceControl, SourceControlResourceGroup, TextEditor, Memento, commands, LogOutputChannel, l10n, ProgressLocation } from 'vscode';
import TelemetryReporter from '@vscode/extension-telemetry';
import { Operation, Repository, RepositoryState } from './repository';
import { memoize, sequentialize, debounce } from './decorators';
import { dispose, anyEvent, filterEvent, isDescendant, pathEquals, toDisposable, eventToPromise } from './util';
import { Git } from './git';
import * as path from 'path';
import * as fs from 'fs';
import { fromGitUri } from './uri';
import { APIState as State, CredentialsProvider, PushErrorHandler, PublishEvent, RemoteSourcePublisher, PostCommitCommandsProvider } from './api/git';
import { Askpass } from './askpass';
import { IPushErrorHandlerRegistry } from './pushError';
import { ApiRepository } from './api/api1';
import { IRemoteSourcePublisherRegistry } from './remotePublisher';
import { IPostCommitCommandsProviderRegistry } from './postCommitCommands';
class RepositoryPick implements QuickPickItem {
@memoize get label(): string {
return path.basename(this.repository.root);
}
@memoize get description(): string {
return [this.repository.headLabel, this.repository.syncLabel]
.filter(l => !!l)
.join(' ');
}
constructor(public readonly repository: Repository, public readonly index: number) { }
}
class UnsafeRepositorySet extends Set<string> {
constructor() {
super();
this.updateContextKey();
}
override add(value: string): this {
const result = super.add(value);
this.updateContextKey();
return result;
}
override delete(value: string): boolean {
const result = super.delete(value);
this.updateContextKey();
return result;
}
private updateContextKey(): void {
commands.executeCommand('setContext', 'git.unsafeRepositoryCount', this.size);
}
}
export interface ModelChangeEvent {
repository: Repository;
uri: Uri;
}
export interface OriginalResourceChangeEvent {
repository: Repository;
uri: Uri;
}
interface OpenRepository extends Disposable {
repository: Repository;
}
export class Model implements IRemoteSourcePublisherRegistry, IPostCommitCommandsProviderRegistry, IPushErrorHandlerRegistry {
private _onDidOpenRepository = new EventEmitter<Repository>();
readonly onDidOpenRepository: Event<Repository> = this._onDidOpenRepository.event;
private _onDidCloseRepository = new EventEmitter<Repository>();
readonly onDidCloseRepository: Event<Repository> = this._onDidCloseRepository.event;
private _onDidChangeRepository = new EventEmitter<ModelChangeEvent>();
readonly onDidChangeRepository: Event<ModelChangeEvent> = this._onDidChangeRepository.event;
private _onDidChangeOriginalResource = new EventEmitter<OriginalResourceChangeEvent>();
readonly onDidChangeOriginalResource: Event<OriginalResourceChangeEvent> = this._onDidChangeOriginalResource.event;
private openRepositories: OpenRepository[] = [];
get repositories(): Repository[] { return this.openRepositories.map(r => r.repository); }
private possibleGitRepositoryPaths = new Set<string>();
private _onDidChangeState = new EventEmitter<State>();
readonly onDidChangeState = this._onDidChangeState.event;
private _onDidPublish = new EventEmitter<PublishEvent>();
readonly onDidPublish = this._onDidPublish.event;
firePublishEvent(repository: Repository, branch?: string) {
this._onDidPublish.fire({ repository: new ApiRepository(repository), branch: branch });
}
private _state: State = 'uninitialized';
get state(): State { return this._state; }
setState(state: State): void {
this._state = state;
this._onDidChangeState.fire(state);
commands.executeCommand('setContext', 'git.state', state);
}
@memoize
get isInitialized(): Promise<void> {
if (this._state === 'initialized') {
return Promise.resolve();
}
return eventToPromise(filterEvent(this.onDidChangeState, s => s === 'initialized')) as Promise<any>;
}
private remoteSourcePublishers = new Set<RemoteSourcePublisher>();
private _onDidAddRemoteSourcePublisher = new EventEmitter<RemoteSourcePublisher>();
readonly onDidAddRemoteSourcePublisher = this._onDidAddRemoteSourcePublisher.event;
private _onDidRemoveRemoteSourcePublisher = new EventEmitter<RemoteSourcePublisher>();
readonly onDidRemoveRemoteSourcePublisher = this._onDidRemoveRemoteSourcePublisher.event;
private postCommitCommandsProviders = new Set<PostCommitCommandsProvider>();
private _onDidChangePostCommitCommandsProviders = new EventEmitter<void>();
readonly onDidChangePostCommitCommandsProviders = this._onDidChangePostCommitCommandsProviders.event;
private showRepoOnHomeDriveRootWarning = true;
private pushErrorHandlers = new Set<PushErrorHandler>();
private _unsafeRepositories = new UnsafeRepositorySet();
get unsafeRepositories(): Set<string> {
return this._unsafeRepositories;
}
private disposables: Disposable[] = [];
constructor(readonly git: Git, private readonly askpass: Askpass, private globalState: Memento, private logger: LogOutputChannel, private telemetryReporter: TelemetryReporter) {
workspace.onDidChangeWorkspaceFolders(this.onDidChangeWorkspaceFolders, this, this.disposables);
window.onDidChangeVisibleTextEditors(this.onDidChangeVisibleTextEditors, this, this.disposables);
workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this.disposables);
const fsWatcher = workspace.createFileSystemWatcher('**');
this.disposables.push(fsWatcher);
const onWorkspaceChange = anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate, fsWatcher.onDidDelete);
const onGitRepositoryChange = filterEvent(onWorkspaceChange, uri => /\/\.git/.test(uri.path));
const onPossibleGitRepositoryChange = filterEvent(onGitRepositoryChange, uri => !this.getRepository(uri));
onPossibleGitRepositoryChange(this.onPossibleGitRepositoryChange, this, this.disposables);
this.setState('uninitialized');
this.doInitialScan().finally(() => this.setState('initialized'));
}
private async doInitialScan(): Promise<void> {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
const initialScanFn = () => Promise.all([
this.onDidChangeWorkspaceFolders({ added: workspace.workspaceFolders || [], removed: [] }),
this.onDidChangeVisibleTextEditors(window.visibleTextEditors),
this.scanWorkspaceFolders()
]);
if (config.get<boolean>('showProgress', true)) {
await window.withProgress({ location: ProgressLocation.SourceControl }, initialScanFn);
} else {
await initialScanFn();
}
// Unsafe repositories notification
if (this._unsafeRepositories.size !== 0) {
this.showUnsafeRepositoryNotification();
}
/* __GDPR__
"git.repositoryInitialScan" : {
"owner": "lszomoru",
"autoRepositoryDetection": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Setting that controls the initial repository scan" },
"repositoryCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Number of repositories opened during initial repository scan" }
}
*/
this.telemetryReporter.sendTelemetryEvent('git.repositoryInitialScan', { autoRepositoryDetection: String(autoRepositoryDetection) }, { repositoryCount: this.openRepositories.length });
}
/**
* Scans each workspace folder, looking for git repositories. By
* default it scans one level deep but that can be changed using
* the git.repositoryScanMaxDepth setting.
*/
private async scanWorkspaceFolders(): Promise<void> {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
this.logger.trace(`[swsf] Scan workspace sub folders. autoRepositoryDetection=${autoRepositoryDetection}`);
if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'subFolders') {
return;
}
await Promise.all((workspace.workspaceFolders || []).map(async folder => {
const root = folder.uri.fsPath;
this.logger.trace(`[swsf] Workspace folder: ${root}`);
// Workspace folder children
const repositoryScanMaxDepth = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<number>('repositoryScanMaxDepth', 1);
const repositoryScanIgnoredFolders = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<string[]>('repositoryScanIgnoredFolders', []);
const subfolders = new Set(await this.traverseWorkspaceFolder(root, repositoryScanMaxDepth, repositoryScanIgnoredFolders));
// Repository scan folders
const scanPaths = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<string[]>('scanRepositories') || [];
this.logger.trace(`[swsf] Workspace scan settings: repositoryScanMaxDepth=${repositoryScanMaxDepth}; repositoryScanIgnoredFolders=[${repositoryScanIgnoredFolders.join(', ')}]; scanRepositories=[${scanPaths.join(', ')}]`);
for (const scanPath of scanPaths) {
if (scanPath === '.git') {
this.logger.trace('[swsf] \'.git\' not supported in \'git.scanRepositories\' setting.');
continue;
}
if (path.isAbsolute(scanPath)) {
const notSupportedMessage = l10n.t('Absolute paths not supported in "git.scanRepositories" setting.');
this.logger.warn(notSupportedMessage);
console.warn(notSupportedMessage);
continue;
}
subfolders.add(path.join(root, scanPath));
}
this.logger.trace(`[swsf] Workspace scan sub folders: [${[...subfolders].join(', ')}]`);
await Promise.all([...subfolders].map(f => this.openRepository(f)));
}));
}
private async traverseWorkspaceFolder(workspaceFolder: string, maxDepth: number, repositoryScanIgnoredFolders: string[]): Promise<string[]> {
const result: string[] = [];
const foldersToTravers = [{ path: workspaceFolder, depth: 0 }];
while (foldersToTravers.length > 0) {
const currentFolder = foldersToTravers.shift()!;
if (currentFolder.depth < maxDepth || maxDepth === -1) {
const children = await fs.promises.readdir(currentFolder.path, { withFileTypes: true });
const childrenFolders = children
.filter(dirent =>
dirent.isDirectory() && dirent.name !== '.git' &&
!repositoryScanIgnoredFolders.find(f => pathEquals(dirent.name, f)))
.map(dirent => path.join(currentFolder.path, dirent.name));
result.push(...childrenFolders);
foldersToTravers.push(...childrenFolders.map(folder => {
return { path: folder, depth: currentFolder.depth + 1 };
}));
}
}
return result;
}
private onPossibleGitRepositoryChange(uri: Uri): void {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
if (autoRepositoryDetection === false) {
return;
}
this.eventuallyScanPossibleGitRepository(uri.fsPath.replace(/\.git.*$/, ''));
}
private eventuallyScanPossibleGitRepository(path: string) {
this.possibleGitRepositoryPaths.add(path);
this.eventuallyScanPossibleGitRepositories();
}
@debounce(500)
private eventuallyScanPossibleGitRepositories(): void {
for (const path of this.possibleGitRepositoryPaths) {
this.openRepository(path);
}
this.possibleGitRepositoryPaths.clear();
}
private async onDidChangeWorkspaceFolders({ added, removed }: WorkspaceFoldersChangeEvent): Promise<void> {
const possibleRepositoryFolders = added
.filter(folder => !this.getOpenRepository(folder.uri));
const activeRepositoriesList = window.visibleTextEditors
.map(editor => this.getRepository(editor.document.uri))
.filter(repository => !!repository) as Repository[];
const activeRepositories = new Set<Repository>(activeRepositoriesList);
const openRepositoriesToDispose = removed
.map(folder => this.getOpenRepository(folder.uri))
.filter(r => !!r)
.filter(r => !activeRepositories.has(r!.repository))
.filter(r => !(workspace.workspaceFolders || []).some(f => isDescendant(f.uri.fsPath, r!.repository.root))) as OpenRepository[];
openRepositoriesToDispose.forEach(r => r.dispose());
this.logger.trace(`[swf] Scan workspace folders: [${possibleRepositoryFolders.map(p => p.uri.fsPath).join(', ')}]`);
await Promise.all(possibleRepositoryFolders.map(p => this.openRepository(p.uri.fsPath)));
}
private onDidChangeConfiguration(): void {
const possibleRepositoryFolders = (workspace.workspaceFolders || [])
.filter(folder => workspace.getConfiguration('git', folder.uri).get<boolean>('enabled') === true)
.filter(folder => !this.getOpenRepository(folder.uri));
const openRepositoriesToDispose = this.openRepositories
.map(repository => ({ repository, root: Uri.file(repository.repository.root) }))
.filter(({ root }) => workspace.getConfiguration('git', root).get<boolean>('enabled') !== true)
.map(({ repository }) => repository);
this.logger.trace(`[swf] Scan workspace folders: [${possibleRepositoryFolders.map(p => p.uri.fsPath).join(', ')}]`);
possibleRepositoryFolders.forEach(p => this.openRepository(p.uri.fsPath));
openRepositoriesToDispose.forEach(r => r.dispose());
}
private async onDidChangeVisibleTextEditors(editors: readonly TextEditor[]): Promise<void> {
if (!workspace.isTrusted) {
this.logger.trace('[svte] Workspace is not trusted.');
return;
}
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
this.logger.trace(`[svte] Scan visible text editors. autoRepositoryDetection=${autoRepositoryDetection}`);
if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors') {
return;
}
await Promise.all(editors.map(async editor => {
const uri = editor.document.uri;
if (uri.scheme !== 'file') {
return;
}
const repository = this.getRepository(uri);
if (repository) {
this.logger.trace(`[svte] Repository for editor resource ${uri.fsPath} already exists: ${repository.root}`);
return;
}
this.logger.trace(`[svte] Open repository for editor resource ${uri.fsPath}`);
await this.openRepository(path.dirname(uri.fsPath));
}));
}
@sequentialize
async openRepository(repoPath: string): Promise<void> {
this.logger.trace(`Opening repository: ${repoPath}`);
if (this.getRepositoryExact(repoPath)) {
this.logger.trace(`Repository for path ${repoPath} already exists`);
return;
}
const config = workspace.getConfiguration('git', Uri.file(repoPath));
const enabled = config.get<boolean>('enabled') === true;
if (!enabled) {
this.logger.trace('Git is not enabled');
return;
}
if (!workspace.isTrusted) {
// Check if the folder is a bare repo: if it has a file named HEAD && `rev-parse --show -cdup` is empty
try {
fs.accessSync(path.join(repoPath, 'HEAD'), fs.constants.F_OK);
const result = await this.git.exec(repoPath, ['-C', repoPath, 'rev-parse', '--show-cdup']);
if (result.stderr.trim() === '' && result.stdout.trim() === '') {
this.logger.trace(`Bare repository: ${repoPath}`);
return;
}
} catch {
// If this throw, we should be good to open the repo (e.g. HEAD doesn't exist)
}
}
try {
const rawRoot = await this.git.getRepositoryRoot(repoPath);
// This can happen whenever `path` has the wrong case sensitivity in
// case insensitive file systems
// https://github.com/microsoft/vscode/issues/33498
const repositoryRoot = Uri.file(rawRoot).fsPath;
this.logger.trace(`Repository root: ${repositoryRoot}`);
if (this.getRepositoryExact(repositoryRoot)) {
this.logger.trace(`Repository for path ${repositoryRoot} already exists`);
return;
}
if (this.shouldRepositoryBeIgnored(rawRoot)) {
this.logger.trace(`Repository for path ${repositoryRoot} is ignored`);
return;
}
// On Window, opening a git repository from the root of the HOMEDRIVE poses a security risk.
// We will only a open git repository from the root of the HOMEDRIVE if the user explicitly
// opens the HOMEDRIVE as a folder. Only show the warning once during repository discovery.
if (process.platform === 'win32' && process.env.HOMEDRIVE && pathEquals(`${process.env.HOMEDRIVE}\\`, repositoryRoot)) {
const isRepoInWorkspaceFolders = (workspace.workspaceFolders ?? []).find(f => pathEquals(f.uri.fsPath, repositoryRoot))!!;
if (!isRepoInWorkspaceFolders) {
if (this.showRepoOnHomeDriveRootWarning) {
window.showWarningMessage(l10n.t('Unable to automatically open the git repository at "{0}". To open that git repository, open it directly as a folder in VS Code.', repositoryRoot));
this.showRepoOnHomeDriveRootWarning = false;
}
this.logger.trace(`Repository for path ${repositoryRoot} is on the root of the HOMEDRIVE`);
return;
}
}
const dotGit = await this.git.getRepositoryDotGit(repositoryRoot);
const repository = new Repository(this.git.open(repositoryRoot, dotGit, this.logger), this, this, this, this.globalState, this.logger, this.telemetryReporter);
this.open(repository);
repository.status(); // do not await this, we want SCM to know about the repo asap
} catch (ex) {
// Handle unsafe repository
const match = /^fatal: detected dubious ownership in repository at \'([^']+)\'$/m.exec(ex.stderr);
if (match && match.length === 2) {
const unsafeRepositoryPath = path.normalize(match[1]);
this.logger.trace(`Unsafe repository: ${unsafeRepositoryPath}`);
// Show a notification if the unsafe repository is opened after the initial repository scan
if (this._state === 'initialized' && !this._unsafeRepositories.has(unsafeRepositoryPath)) {
this.showUnsafeRepositoryNotification();
}
this._unsafeRepositories.add(unsafeRepositoryPath);
return;
}
// noop
this.logger.trace(`Opening repository for path='${repoPath}' failed; ex=${ex}`);
}
}
private shouldRepositoryBeIgnored(repositoryRoot: string): boolean {
const config = workspace.getConfiguration('git');
const ignoredRepos = config.get<string[]>('ignoredRepositories') || [];
for (const ignoredRepo of ignoredRepos) {
if (path.isAbsolute(ignoredRepo)) {
if (pathEquals(ignoredRepo, repositoryRoot)) {
return true;
}
} else {
for (const folder of workspace.workspaceFolders || []) {
if (pathEquals(path.join(folder.uri.fsPath, ignoredRepo), repositoryRoot)) {
return true;
}
}
}
}
return false;
}
private open(repository: Repository): void {
this.logger.info(`Open repository: ${repository.root}`);
const onDidDisappearRepository = filterEvent(repository.onDidChangeState, state => state === RepositoryState.Disposed);
const disappearListener = onDidDisappearRepository(() => dispose());
const changeListener = repository.onDidChangeRepository(uri => this._onDidChangeRepository.fire({ repository, uri }));
const originalResourceChangeListener = repository.onDidChangeOriginalResource(uri => this._onDidChangeOriginalResource.fire({ repository, uri }));
const shouldDetectSubmodules = workspace
.getConfiguration('git', Uri.file(repository.root))
.get<boolean>('detectSubmodules') as boolean;
const submodulesLimit = workspace
.getConfiguration('git', Uri.file(repository.root))
.get<number>('detectSubmodulesLimit') as number;
const checkForSubmodules = () => {
if (!shouldDetectSubmodules) {
this.logger.trace('Automatic detection of git submodules is not enabled.');
return;
}
if (repository.submodules.length > submodulesLimit) {
window.showWarningMessage(l10n.t('The "{0}" repository has {1} submodules which won\'t be opened automatically. You can still open each one individually by opening a file within.', path.basename(repository.root), repository.submodules.length));
statusListener.dispose();
}
repository.submodules
.slice(0, submodulesLimit)
.map(r => path.join(repository.root, r.path))
.forEach(p => {
this.logger.trace(`Opening submodule: '${p}'`);
this.eventuallyScanPossibleGitRepository(p);
});
};
const updateMergeChanges = () => {
// set mergeChanges context
const mergeChanges: Uri[] = [];
for (const { repository } of this.openRepositories.values()) {
for (const state of repository.mergeGroup.resourceStates) {
mergeChanges.push(state.resourceUri);
}
}
commands.executeCommand('setContext', 'git.mergeChanges', mergeChanges);
};
const statusListener = repository.onDidRunGitStatus(() => {
checkForSubmodules();
updateMergeChanges();
});
checkForSubmodules();
const updateCommitInProgressContext = () => {
let commitInProgress = false;
for (const { repository } of this.openRepositories.values()) {
if (repository.operations.isRunning(Operation.Commit)) {
commitInProgress = true;
break;
}
}
commands.executeCommand('setContext', 'commitInProgress', commitInProgress);
};
const operationEvent = anyEvent(repository.onDidRunOperation as Event<any>, repository.onRunOperation as Event<any>);
const operationListener = operationEvent(() => updateCommitInProgressContext());
updateCommitInProgressContext();
const dispose = () => {
disappearListener.dispose();
changeListener.dispose();
originalResourceChangeListener.dispose();
statusListener.dispose();
operationListener.dispose();
repository.dispose();
this.openRepositories = this.openRepositories.filter(e => e !== openRepository);
this._onDidCloseRepository.fire(repository);
};
const openRepository = { repository, dispose };
this.openRepositories.push(openRepository);
updateMergeChanges();
this._onDidOpenRepository.fire(repository);
}
close(repository: Repository): void {
const openRepository = this.getOpenRepository(repository);
if (!openRepository) {
return;
}
this.logger.info(`Close repository: ${repository.root}`);
openRepository.dispose();
}
async pickRepository(): Promise<Repository | undefined> {
if (this.openRepositories.length === 0) {
throw new Error(l10n.t('There are no available repositories'));
}
const picks = this.openRepositories.map((e, index) => new RepositoryPick(e.repository, index));
const active = window.activeTextEditor;
const repository = active && this.getRepository(active.document.fileName);
const index = picks.findIndex(pick => pick.repository === repository);
// Move repository pick containing the active text editor to appear first
if (index > -1) {
picks.unshift(...picks.splice(index, 1));
}
const placeHolder = l10n.t('Choose a repository');
const pick = await window.showQuickPick(picks, { placeHolder });
return pick && pick.repository;
}
getRepository(sourceControl: SourceControl): Repository | undefined;
getRepository(resourceGroup: SourceControlResourceGroup): Repository | undefined;
getRepository(path: string): Repository | undefined;
getRepository(resource: Uri): Repository | undefined;
getRepository(hint: any): Repository | undefined {
const liveRepository = this.getOpenRepository(hint);
return liveRepository && liveRepository.repository;
}
private getRepositoryExact(repoPath: string): Repository | undefined {
const openRepository = this.openRepositories
.find(r => pathEquals(r.repository.root, repoPath));
return openRepository?.repository;
}
private getOpenRepository(repository: Repository): OpenRepository | undefined;
private getOpenRepository(sourceControl: SourceControl): OpenRepository | undefined;
private getOpenRepository(resourceGroup: SourceControlResourceGroup): OpenRepository | undefined;
private getOpenRepository(path: string): OpenRepository | undefined;
private getOpenRepository(resource: Uri): OpenRepository | undefined;
private getOpenRepository(hint: any): OpenRepository | undefined {
if (!hint) {
return undefined;
}
if (hint instanceof Repository) {
return this.openRepositories.filter(r => r.repository === hint)[0];
}
if (hint instanceof ApiRepository) {
return this.openRepositories.filter(r => r.repository === hint.repository)[0];
}
if (typeof hint === 'string') {
hint = Uri.file(hint);
}
if (hint instanceof Uri) {
let resourcePath: string;
if (hint.scheme === 'git') {
resourcePath = fromGitUri(hint).path;
} else {
resourcePath = hint.fsPath;
}
outer:
for (const liveRepository of this.openRepositories.sort((a, b) => b.repository.root.length - a.repository.root.length)) {
if (!isDescendant(liveRepository.repository.root, resourcePath)) {
continue;
}
for (const submodule of liveRepository.repository.submodules) {
const submoduleRoot = path.join(liveRepository.repository.root, submodule.path);
if (isDescendant(submoduleRoot, resourcePath)) {
continue outer;
}
}
return liveRepository;
}
return undefined;
}
for (const liveRepository of this.openRepositories) {
const repository = liveRepository.repository;
if (hint === repository.sourceControl) {
return liveRepository;
}
if (hint === repository.mergeGroup || hint === repository.indexGroup || hint === repository.workingTreeGroup) {
return liveRepository;
}
}
return undefined;
}
getRepositoryForSubmodule(submoduleUri: Uri): Repository | undefined {
for (const repository of this.repositories) {
for (const submodule of repository.submodules) {
const submodulePath = path.join(repository.root, submodule.path);
if (submodulePath === submoduleUri.fsPath) {
return repository;
}
}
}
return undefined;
}
registerRemoteSourcePublisher(publisher: RemoteSourcePublisher): Disposable {
this.remoteSourcePublishers.add(publisher);
this._onDidAddRemoteSourcePublisher.fire(publisher);
return toDisposable(() => {
this.remoteSourcePublishers.delete(publisher);
this._onDidRemoveRemoteSourcePublisher.fire(publisher);
});
}
getRemoteSourcePublishers(): RemoteSourcePublisher[] {
return [...this.remoteSourcePublishers.values()];
}
registerPostCommitCommandsProvider(provider: PostCommitCommandsProvider): Disposable {
this.postCommitCommandsProviders.add(provider);
this._onDidChangePostCommitCommandsProviders.fire();
return toDisposable(() => {
this.postCommitCommandsProviders.delete(provider);
this._onDidChangePostCommitCommandsProviders.fire();
});
}
getPostCommitCommandsProviders(): PostCommitCommandsProvider[] {
return [...this.postCommitCommandsProviders.values()];
}
registerCredentialsProvider(provider: CredentialsProvider): Disposable {
return this.askpass.registerCredentialsProvider(provider);
}
registerPushErrorHandler(handler: PushErrorHandler): Disposable {
this.pushErrorHandlers.add(handler);
return toDisposable(() => this.pushErrorHandlers.delete(handler));
}
getPushErrorHandlers(): PushErrorHandler[] {
return [...this.pushErrorHandlers];
}
private async showUnsafeRepositoryNotification(): Promise<void> {
const message = this._unsafeRepositories.size === 1 ?
l10n.t('The git repository in the current folder is potentially unsafe as the folder is owned by someone other than the current user.') :
l10n.t('The git repositories in the current folder are potentially unsafe as the folders are owned by someone other than the current user.');
const manageUnsafeRepositories = l10n.t('Manage Unsafe Repositories');
const learnMore = l10n.t('Learn More');
const choice = await window.showErrorMessage(message, manageUnsafeRepositories, learnMore);
if (choice === manageUnsafeRepositories) {
// Manage Unsafe Repositories
commands.executeCommand('git.manageUnsafeRepositories');
} else if (choice === learnMore) {
// Learn More
commands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-scm'));
}
}
dispose(): void {
const openRepositories = [...this.openRepositories];
openRepositories.forEach(r => r.dispose());
this.openRepositories = [];
this.possibleGitRepositoryPaths.clear();
this.disposables = dispose(this.disposables);
}
}
| extensions/git/src/model.ts | 1 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0075568766333162785,
0.0005556855467148125,
0.00016310566570609808,
0.00017567098257131875,
0.0011200645240023732
] |
{
"id": 0,
"code_window": [
"\t},\n",
"\t\"view.workbench.scm.scanWorkspaceForRepositories\": {\n",
"\t\t\"message\": \"Scanning workspace for git repositories...\"\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepository\": {\n",
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 332
} | /*---------------------------------------------------------------------------------------------
* 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/electron-sandbox/services';
/**
* 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/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0001712565717753023,
0.00016984081594273448,
0.0001688075135461986,
0.00016964957467280328,
8.934572974794719e-7
] |
{
"id": 0,
"code_window": [
"\t},\n",
"\t\"view.workbench.scm.scanWorkspaceForRepositories\": {\n",
"\t\t\"message\": \"Scanning workspace for git repositories...\"\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepository\": {\n",
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 332
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { IReference, dispose, Disposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ITextModel, shouldSynchronizeModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IFileService, FileOperation } from 'vs/platform/files/common/files';
import { ExtHostContext, ExtHostDocumentsShape, MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { toLocalResource, extUri, IExtUri } from 'vs/base/common/resources';
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { Emitter } from 'vs/base/common/event';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { ResourceMap } from 'vs/base/common/map';
import { IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
export class BoundModelReferenceCollection {
private _data = new Array<{ uri: URI; length: number; dispose(): void }>();
private _length = 0;
constructor(
private readonly _extUri: IExtUri,
private readonly _maxAge: number = 1000 * 60 * 3, // auto-dispse by age
private readonly _maxLength: number = 1024 * 1024 * 80, // auto-dispose by total length
private readonly _maxSize: number = 50 // auto-dispose by number of references
) {
//
}
dispose(): void {
this._data = dispose(this._data);
}
remove(uri: URI): void {
for (const entry of [...this._data] /* copy array because dispose will modify it */) {
if (this._extUri.isEqualOrParent(entry.uri, uri)) {
entry.dispose();
}
}
}
add(uri: URI, ref: IReference<any>, length: number = 0): void {
// const length = ref.object.textEditorModel.getValueLength();
const dispose = () => {
const idx = this._data.indexOf(entry);
if (idx >= 0) {
this._length -= length;
ref.dispose();
clearTimeout(handle);
this._data.splice(idx, 1);
}
};
const handle = setTimeout(dispose, this._maxAge);
const entry = { uri, length, dispose };
this._data.push(entry);
this._length += length;
this._cleanup();
}
private _cleanup(): void {
// clean-up wrt total length
while (this._length > this._maxLength) {
this._data[0].dispose();
}
// clean-up wrt number of documents
const extraSize = Math.ceil(this._maxSize * 1.2);
if (this._data.length >= extraSize) {
dispose(this._data.slice(0, extraSize - this._maxSize));
}
}
}
class ModelTracker extends Disposable {
private _knownVersionId: number;
constructor(
private readonly _model: ITextModel,
private readonly _onIsCaughtUpWithContentChanges: Emitter<URI>,
private readonly _proxy: ExtHostDocumentsShape,
private readonly _textFileService: ITextFileService,
) {
super();
this._knownVersionId = this._model.getVersionId();
this._store.add(this._model.onDidChangeContent((e) => {
this._knownVersionId = e.versionId;
this._proxy.$acceptModelChanged(this._model.uri, e, this._textFileService.isDirty(this._model.uri));
if (this.isCaughtUpWithContentChanges()) {
this._onIsCaughtUpWithContentChanges.fire(this._model.uri);
}
}));
}
isCaughtUpWithContentChanges(): boolean {
return (this._model.getVersionId() === this._knownVersionId);
}
}
export class MainThreadDocuments extends Disposable implements MainThreadDocumentsShape {
private _onIsCaughtUpWithContentChanges = this._store.add(new Emitter<URI>());
readonly onIsCaughtUpWithContentChanges = this._onIsCaughtUpWithContentChanges.event;
private readonly _proxy: ExtHostDocumentsShape;
private readonly _modelTrackers = new ResourceMap<ModelTracker>();
private readonly _modelReferenceCollection: BoundModelReferenceCollection;
constructor(
extHostContext: IExtHostContext,
@IModelService private readonly _modelService: IModelService,
@ITextFileService private readonly _textFileService: ITextFileService,
@IFileService private readonly _fileService: IFileService,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService private readonly _uriIdentityService: IUriIdentityService,
@IWorkingCopyFileService workingCopyFileService: IWorkingCopyFileService,
@IPathService private readonly _pathService: IPathService
) {
super();
this._modelReferenceCollection = this._store.add(new BoundModelReferenceCollection(_uriIdentityService.extUri));
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDocuments);
this._store.add(_modelService.onModelLanguageChanged(this._onModelModeChanged, this));
this._store.add(_textFileService.files.onDidSave(e => {
if (this._shouldHandleFileEvent(e.model.resource)) {
this._proxy.$acceptModelSaved(e.model.resource);
}
}));
this._store.add(_textFileService.files.onDidChangeDirty(m => {
if (this._shouldHandleFileEvent(m.resource)) {
this._proxy.$acceptDirtyStateChanged(m.resource, m.isDirty());
}
}));
this._store.add(workingCopyFileService.onDidRunWorkingCopyFileOperation(e => {
const isMove = e.operation === FileOperation.MOVE;
if (isMove || e.operation === FileOperation.DELETE) {
for (const pair of e.files) {
const removed = isMove ? pair.source : pair.target;
if (removed) {
this._modelReferenceCollection.remove(removed);
}
}
}
}));
}
override dispose(): void {
dispose(this._modelTrackers.values());
this._modelTrackers.clear();
super.dispose();
}
isCaughtUpWithContentChanges(resource: URI): boolean {
const tracker = this._modelTrackers.get(resource);
if (tracker) {
return tracker.isCaughtUpWithContentChanges();
}
return true;
}
private _shouldHandleFileEvent(resource: URI): boolean {
const model = this._modelService.getModel(resource);
return !!model && shouldSynchronizeModel(model);
}
handleModelAdded(model: ITextModel): void {
// Same filter as in mainThreadEditorsTracker
if (!shouldSynchronizeModel(model)) {
// don't synchronize too large models
return;
}
this._modelTrackers.set(model.uri, new ModelTracker(model, this._onIsCaughtUpWithContentChanges, this._proxy, this._textFileService));
}
private _onModelModeChanged(event: { model: ITextModel; oldLanguageId: string }): void {
const { model } = event;
if (!this._modelTrackers.has(model.uri)) {
return;
}
this._proxy.$acceptModelLanguageChanged(model.uri, model.getLanguageId());
}
handleModelRemoved(modelUrl: URI): void {
if (!this._modelTrackers.has(modelUrl)) {
return;
}
this._modelTrackers.get(modelUrl)!.dispose();
this._modelTrackers.delete(modelUrl);
}
// --- from extension host process
async $trySaveDocument(uri: UriComponents): Promise<boolean> {
const target = await this._textFileService.save(URI.revive(uri));
return Boolean(target);
}
async $tryOpenDocument(uriData: UriComponents): Promise<URI> {
const inputUri = URI.revive(uriData);
if (!inputUri.scheme || !(inputUri.fsPath || inputUri.authority)) {
throw new Error(`Invalid uri. Scheme and authority or path must be set.`);
}
const canonicalUri = this._uriIdentityService.asCanonicalUri(inputUri);
let promise: Promise<URI>;
switch (canonicalUri.scheme) {
case Schemas.untitled:
promise = this._handleUntitledScheme(canonicalUri);
break;
case Schemas.file:
default:
promise = this._handleAsResourceInput(canonicalUri);
break;
}
let documentUri: URI | undefined;
try {
documentUri = await promise;
} catch (err) {
throw new Error(`cannot open ${canonicalUri.toString()}. Detail: ${toErrorMessage(err)}`);
}
if (!documentUri) {
throw new Error(`cannot open ${canonicalUri.toString()}`);
} else if (!extUri.isEqual(documentUri, canonicalUri)) {
throw new Error(`cannot open ${canonicalUri.toString()}. Detail: Actual document opened as ${documentUri.toString()}`);
} else if (!this._modelTrackers.has(canonicalUri)) {
throw new Error(`cannot open ${canonicalUri.toString()}. Detail: Files above 50MB cannot be synchronized with extensions.`);
} else {
return canonicalUri;
}
}
$tryCreateDocument(options?: { language?: string; content?: string }): Promise<URI> {
return this._doCreateUntitled(undefined, options ? options.language : undefined, options ? options.content : undefined);
}
private async _handleAsResourceInput(uri: URI): Promise<URI> {
const ref = await this._textModelResolverService.createModelReference(uri);
this._modelReferenceCollection.add(uri, ref, ref.object.textEditorModel.getValueLength());
return ref.object.textEditorModel.uri;
}
private async _handleUntitledScheme(uri: URI): Promise<URI> {
const asLocalUri = toLocalResource(uri, this._environmentService.remoteAuthority, this._pathService.defaultUriScheme);
const exists = await this._fileService.exists(asLocalUri);
if (exists) {
// don't create a new file ontop of an existing file
return Promise.reject(new Error('file already exists'));
}
return await this._doCreateUntitled(Boolean(uri.path) ? uri : undefined);
}
private async _doCreateUntitled(associatedResource?: URI, languageId?: string, initialValue?: string): Promise<URI> {
const model = await this._textFileService.untitled.resolve({
associatedResource,
languageId,
initialValue
});
const resource = model.resource;
if (!this._modelTrackers.has(resource)) {
throw new Error(`expected URI ${resource.toString()} to have come to LIFE`);
}
this._proxy.$acceptDirtyStateChanged(resource, true); // mark as dirty
return resource;
}
}
| src/vs/workbench/api/browser/mainThreadDocuments.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0001735019322950393,
0.00017096060037147254,
0.00016472252900712192,
0.00017175190441776067,
0.0000021835637653566664
] |
{
"id": 0,
"code_window": [
"\t},\n",
"\t\"view.workbench.scm.scanWorkspaceForRepositories\": {\n",
"\t\t\"message\": \"Scanning workspace for git repositories...\"\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepository\": {\n",
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 332
} | /*---------------------------------------------------------------------------------------------
* 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 { ToggleCellToolbarPositionAction } from 'vs/workbench/contrib/notebook/browser/contrib/layout/layoutActions';
suite('Notebook Layout Actions', () => {
test('Toggle Cell Toolbar Position', async function () {
const action = new ToggleCellToolbarPositionAction();
// "notebook.cellToolbarLocation": "right"
assert.deepStrictEqual(action.togglePosition('test-nb', 'right'), {
default: 'right',
'test-nb': 'left'
});
// "notebook.cellToolbarLocation": "left"
assert.deepStrictEqual(action.togglePosition('test-nb', 'left'), {
default: 'left',
'test-nb': 'right'
});
// "notebook.cellToolbarLocation": "hidden"
assert.deepStrictEqual(action.togglePosition('test-nb', 'hidden'), {
default: 'hidden',
'test-nb': 'right'
});
// invalid
assert.deepStrictEqual(action.togglePosition('test-nb', ''), {
default: 'right',
'test-nb': 'left'
});
// no user config, default value
assert.deepStrictEqual(action.togglePosition('test-nb', {
default: 'right'
}), {
default: 'right',
'test-nb': 'left'
});
// user config, default to left
assert.deepStrictEqual(action.togglePosition('test-nb', {
default: 'left'
}), {
default: 'left',
'test-nb': 'right'
});
// user config, default to hidden
assert.deepStrictEqual(action.togglePosition('test-nb', {
default: 'hidden'
}), {
default: 'hidden',
'test-nb': 'right'
});
});
});
| src/vs/workbench/contrib/notebook/test/browser/contrib/layoutActions.test.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.00017113822104874998,
0.0001695896207820624,
0.00016486473032273352,
0.00017031500465236604,
0.0000020157990547886584
] |
{
"id": 1,
"code_window": [
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepositories\": {\n",
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 340
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { workspace, WorkspaceFoldersChangeEvent, Uri, window, Event, EventEmitter, QuickPickItem, Disposable, SourceControl, SourceControlResourceGroup, TextEditor, Memento, commands, LogOutputChannel, l10n, ProgressLocation } from 'vscode';
import TelemetryReporter from '@vscode/extension-telemetry';
import { Operation, Repository, RepositoryState } from './repository';
import { memoize, sequentialize, debounce } from './decorators';
import { dispose, anyEvent, filterEvent, isDescendant, pathEquals, toDisposable, eventToPromise } from './util';
import { Git } from './git';
import * as path from 'path';
import * as fs from 'fs';
import { fromGitUri } from './uri';
import { APIState as State, CredentialsProvider, PushErrorHandler, PublishEvent, RemoteSourcePublisher, PostCommitCommandsProvider } from './api/git';
import { Askpass } from './askpass';
import { IPushErrorHandlerRegistry } from './pushError';
import { ApiRepository } from './api/api1';
import { IRemoteSourcePublisherRegistry } from './remotePublisher';
import { IPostCommitCommandsProviderRegistry } from './postCommitCommands';
class RepositoryPick implements QuickPickItem {
@memoize get label(): string {
return path.basename(this.repository.root);
}
@memoize get description(): string {
return [this.repository.headLabel, this.repository.syncLabel]
.filter(l => !!l)
.join(' ');
}
constructor(public readonly repository: Repository, public readonly index: number) { }
}
class UnsafeRepositorySet extends Set<string> {
constructor() {
super();
this.updateContextKey();
}
override add(value: string): this {
const result = super.add(value);
this.updateContextKey();
return result;
}
override delete(value: string): boolean {
const result = super.delete(value);
this.updateContextKey();
return result;
}
private updateContextKey(): void {
commands.executeCommand('setContext', 'git.unsafeRepositoryCount', this.size);
}
}
export interface ModelChangeEvent {
repository: Repository;
uri: Uri;
}
export interface OriginalResourceChangeEvent {
repository: Repository;
uri: Uri;
}
interface OpenRepository extends Disposable {
repository: Repository;
}
export class Model implements IRemoteSourcePublisherRegistry, IPostCommitCommandsProviderRegistry, IPushErrorHandlerRegistry {
private _onDidOpenRepository = new EventEmitter<Repository>();
readonly onDidOpenRepository: Event<Repository> = this._onDidOpenRepository.event;
private _onDidCloseRepository = new EventEmitter<Repository>();
readonly onDidCloseRepository: Event<Repository> = this._onDidCloseRepository.event;
private _onDidChangeRepository = new EventEmitter<ModelChangeEvent>();
readonly onDidChangeRepository: Event<ModelChangeEvent> = this._onDidChangeRepository.event;
private _onDidChangeOriginalResource = new EventEmitter<OriginalResourceChangeEvent>();
readonly onDidChangeOriginalResource: Event<OriginalResourceChangeEvent> = this._onDidChangeOriginalResource.event;
private openRepositories: OpenRepository[] = [];
get repositories(): Repository[] { return this.openRepositories.map(r => r.repository); }
private possibleGitRepositoryPaths = new Set<string>();
private _onDidChangeState = new EventEmitter<State>();
readonly onDidChangeState = this._onDidChangeState.event;
private _onDidPublish = new EventEmitter<PublishEvent>();
readonly onDidPublish = this._onDidPublish.event;
firePublishEvent(repository: Repository, branch?: string) {
this._onDidPublish.fire({ repository: new ApiRepository(repository), branch: branch });
}
private _state: State = 'uninitialized';
get state(): State { return this._state; }
setState(state: State): void {
this._state = state;
this._onDidChangeState.fire(state);
commands.executeCommand('setContext', 'git.state', state);
}
@memoize
get isInitialized(): Promise<void> {
if (this._state === 'initialized') {
return Promise.resolve();
}
return eventToPromise(filterEvent(this.onDidChangeState, s => s === 'initialized')) as Promise<any>;
}
private remoteSourcePublishers = new Set<RemoteSourcePublisher>();
private _onDidAddRemoteSourcePublisher = new EventEmitter<RemoteSourcePublisher>();
readonly onDidAddRemoteSourcePublisher = this._onDidAddRemoteSourcePublisher.event;
private _onDidRemoveRemoteSourcePublisher = new EventEmitter<RemoteSourcePublisher>();
readonly onDidRemoveRemoteSourcePublisher = this._onDidRemoveRemoteSourcePublisher.event;
private postCommitCommandsProviders = new Set<PostCommitCommandsProvider>();
private _onDidChangePostCommitCommandsProviders = new EventEmitter<void>();
readonly onDidChangePostCommitCommandsProviders = this._onDidChangePostCommitCommandsProviders.event;
private showRepoOnHomeDriveRootWarning = true;
private pushErrorHandlers = new Set<PushErrorHandler>();
private _unsafeRepositories = new UnsafeRepositorySet();
get unsafeRepositories(): Set<string> {
return this._unsafeRepositories;
}
private disposables: Disposable[] = [];
constructor(readonly git: Git, private readonly askpass: Askpass, private globalState: Memento, private logger: LogOutputChannel, private telemetryReporter: TelemetryReporter) {
workspace.onDidChangeWorkspaceFolders(this.onDidChangeWorkspaceFolders, this, this.disposables);
window.onDidChangeVisibleTextEditors(this.onDidChangeVisibleTextEditors, this, this.disposables);
workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this.disposables);
const fsWatcher = workspace.createFileSystemWatcher('**');
this.disposables.push(fsWatcher);
const onWorkspaceChange = anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate, fsWatcher.onDidDelete);
const onGitRepositoryChange = filterEvent(onWorkspaceChange, uri => /\/\.git/.test(uri.path));
const onPossibleGitRepositoryChange = filterEvent(onGitRepositoryChange, uri => !this.getRepository(uri));
onPossibleGitRepositoryChange(this.onPossibleGitRepositoryChange, this, this.disposables);
this.setState('uninitialized');
this.doInitialScan().finally(() => this.setState('initialized'));
}
private async doInitialScan(): Promise<void> {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
const initialScanFn = () => Promise.all([
this.onDidChangeWorkspaceFolders({ added: workspace.workspaceFolders || [], removed: [] }),
this.onDidChangeVisibleTextEditors(window.visibleTextEditors),
this.scanWorkspaceFolders()
]);
if (config.get<boolean>('showProgress', true)) {
await window.withProgress({ location: ProgressLocation.SourceControl }, initialScanFn);
} else {
await initialScanFn();
}
// Unsafe repositories notification
if (this._unsafeRepositories.size !== 0) {
this.showUnsafeRepositoryNotification();
}
/* __GDPR__
"git.repositoryInitialScan" : {
"owner": "lszomoru",
"autoRepositoryDetection": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Setting that controls the initial repository scan" },
"repositoryCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Number of repositories opened during initial repository scan" }
}
*/
this.telemetryReporter.sendTelemetryEvent('git.repositoryInitialScan', { autoRepositoryDetection: String(autoRepositoryDetection) }, { repositoryCount: this.openRepositories.length });
}
/**
* Scans each workspace folder, looking for git repositories. By
* default it scans one level deep but that can be changed using
* the git.repositoryScanMaxDepth setting.
*/
private async scanWorkspaceFolders(): Promise<void> {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
this.logger.trace(`[swsf] Scan workspace sub folders. autoRepositoryDetection=${autoRepositoryDetection}`);
if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'subFolders') {
return;
}
await Promise.all((workspace.workspaceFolders || []).map(async folder => {
const root = folder.uri.fsPath;
this.logger.trace(`[swsf] Workspace folder: ${root}`);
// Workspace folder children
const repositoryScanMaxDepth = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<number>('repositoryScanMaxDepth', 1);
const repositoryScanIgnoredFolders = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<string[]>('repositoryScanIgnoredFolders', []);
const subfolders = new Set(await this.traverseWorkspaceFolder(root, repositoryScanMaxDepth, repositoryScanIgnoredFolders));
// Repository scan folders
const scanPaths = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<string[]>('scanRepositories') || [];
this.logger.trace(`[swsf] Workspace scan settings: repositoryScanMaxDepth=${repositoryScanMaxDepth}; repositoryScanIgnoredFolders=[${repositoryScanIgnoredFolders.join(', ')}]; scanRepositories=[${scanPaths.join(', ')}]`);
for (const scanPath of scanPaths) {
if (scanPath === '.git') {
this.logger.trace('[swsf] \'.git\' not supported in \'git.scanRepositories\' setting.');
continue;
}
if (path.isAbsolute(scanPath)) {
const notSupportedMessage = l10n.t('Absolute paths not supported in "git.scanRepositories" setting.');
this.logger.warn(notSupportedMessage);
console.warn(notSupportedMessage);
continue;
}
subfolders.add(path.join(root, scanPath));
}
this.logger.trace(`[swsf] Workspace scan sub folders: [${[...subfolders].join(', ')}]`);
await Promise.all([...subfolders].map(f => this.openRepository(f)));
}));
}
private async traverseWorkspaceFolder(workspaceFolder: string, maxDepth: number, repositoryScanIgnoredFolders: string[]): Promise<string[]> {
const result: string[] = [];
const foldersToTravers = [{ path: workspaceFolder, depth: 0 }];
while (foldersToTravers.length > 0) {
const currentFolder = foldersToTravers.shift()!;
if (currentFolder.depth < maxDepth || maxDepth === -1) {
const children = await fs.promises.readdir(currentFolder.path, { withFileTypes: true });
const childrenFolders = children
.filter(dirent =>
dirent.isDirectory() && dirent.name !== '.git' &&
!repositoryScanIgnoredFolders.find(f => pathEquals(dirent.name, f)))
.map(dirent => path.join(currentFolder.path, dirent.name));
result.push(...childrenFolders);
foldersToTravers.push(...childrenFolders.map(folder => {
return { path: folder, depth: currentFolder.depth + 1 };
}));
}
}
return result;
}
private onPossibleGitRepositoryChange(uri: Uri): void {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
if (autoRepositoryDetection === false) {
return;
}
this.eventuallyScanPossibleGitRepository(uri.fsPath.replace(/\.git.*$/, ''));
}
private eventuallyScanPossibleGitRepository(path: string) {
this.possibleGitRepositoryPaths.add(path);
this.eventuallyScanPossibleGitRepositories();
}
@debounce(500)
private eventuallyScanPossibleGitRepositories(): void {
for (const path of this.possibleGitRepositoryPaths) {
this.openRepository(path);
}
this.possibleGitRepositoryPaths.clear();
}
private async onDidChangeWorkspaceFolders({ added, removed }: WorkspaceFoldersChangeEvent): Promise<void> {
const possibleRepositoryFolders = added
.filter(folder => !this.getOpenRepository(folder.uri));
const activeRepositoriesList = window.visibleTextEditors
.map(editor => this.getRepository(editor.document.uri))
.filter(repository => !!repository) as Repository[];
const activeRepositories = new Set<Repository>(activeRepositoriesList);
const openRepositoriesToDispose = removed
.map(folder => this.getOpenRepository(folder.uri))
.filter(r => !!r)
.filter(r => !activeRepositories.has(r!.repository))
.filter(r => !(workspace.workspaceFolders || []).some(f => isDescendant(f.uri.fsPath, r!.repository.root))) as OpenRepository[];
openRepositoriesToDispose.forEach(r => r.dispose());
this.logger.trace(`[swf] Scan workspace folders: [${possibleRepositoryFolders.map(p => p.uri.fsPath).join(', ')}]`);
await Promise.all(possibleRepositoryFolders.map(p => this.openRepository(p.uri.fsPath)));
}
private onDidChangeConfiguration(): void {
const possibleRepositoryFolders = (workspace.workspaceFolders || [])
.filter(folder => workspace.getConfiguration('git', folder.uri).get<boolean>('enabled') === true)
.filter(folder => !this.getOpenRepository(folder.uri));
const openRepositoriesToDispose = this.openRepositories
.map(repository => ({ repository, root: Uri.file(repository.repository.root) }))
.filter(({ root }) => workspace.getConfiguration('git', root).get<boolean>('enabled') !== true)
.map(({ repository }) => repository);
this.logger.trace(`[swf] Scan workspace folders: [${possibleRepositoryFolders.map(p => p.uri.fsPath).join(', ')}]`);
possibleRepositoryFolders.forEach(p => this.openRepository(p.uri.fsPath));
openRepositoriesToDispose.forEach(r => r.dispose());
}
private async onDidChangeVisibleTextEditors(editors: readonly TextEditor[]): Promise<void> {
if (!workspace.isTrusted) {
this.logger.trace('[svte] Workspace is not trusted.');
return;
}
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
this.logger.trace(`[svte] Scan visible text editors. autoRepositoryDetection=${autoRepositoryDetection}`);
if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors') {
return;
}
await Promise.all(editors.map(async editor => {
const uri = editor.document.uri;
if (uri.scheme !== 'file') {
return;
}
const repository = this.getRepository(uri);
if (repository) {
this.logger.trace(`[svte] Repository for editor resource ${uri.fsPath} already exists: ${repository.root}`);
return;
}
this.logger.trace(`[svte] Open repository for editor resource ${uri.fsPath}`);
await this.openRepository(path.dirname(uri.fsPath));
}));
}
@sequentialize
async openRepository(repoPath: string): Promise<void> {
this.logger.trace(`Opening repository: ${repoPath}`);
if (this.getRepositoryExact(repoPath)) {
this.logger.trace(`Repository for path ${repoPath} already exists`);
return;
}
const config = workspace.getConfiguration('git', Uri.file(repoPath));
const enabled = config.get<boolean>('enabled') === true;
if (!enabled) {
this.logger.trace('Git is not enabled');
return;
}
if (!workspace.isTrusted) {
// Check if the folder is a bare repo: if it has a file named HEAD && `rev-parse --show -cdup` is empty
try {
fs.accessSync(path.join(repoPath, 'HEAD'), fs.constants.F_OK);
const result = await this.git.exec(repoPath, ['-C', repoPath, 'rev-parse', '--show-cdup']);
if (result.stderr.trim() === '' && result.stdout.trim() === '') {
this.logger.trace(`Bare repository: ${repoPath}`);
return;
}
} catch {
// If this throw, we should be good to open the repo (e.g. HEAD doesn't exist)
}
}
try {
const rawRoot = await this.git.getRepositoryRoot(repoPath);
// This can happen whenever `path` has the wrong case sensitivity in
// case insensitive file systems
// https://github.com/microsoft/vscode/issues/33498
const repositoryRoot = Uri.file(rawRoot).fsPath;
this.logger.trace(`Repository root: ${repositoryRoot}`);
if (this.getRepositoryExact(repositoryRoot)) {
this.logger.trace(`Repository for path ${repositoryRoot} already exists`);
return;
}
if (this.shouldRepositoryBeIgnored(rawRoot)) {
this.logger.trace(`Repository for path ${repositoryRoot} is ignored`);
return;
}
// On Window, opening a git repository from the root of the HOMEDRIVE poses a security risk.
// We will only a open git repository from the root of the HOMEDRIVE if the user explicitly
// opens the HOMEDRIVE as a folder. Only show the warning once during repository discovery.
if (process.platform === 'win32' && process.env.HOMEDRIVE && pathEquals(`${process.env.HOMEDRIVE}\\`, repositoryRoot)) {
const isRepoInWorkspaceFolders = (workspace.workspaceFolders ?? []).find(f => pathEquals(f.uri.fsPath, repositoryRoot))!!;
if (!isRepoInWorkspaceFolders) {
if (this.showRepoOnHomeDriveRootWarning) {
window.showWarningMessage(l10n.t('Unable to automatically open the git repository at "{0}". To open that git repository, open it directly as a folder in VS Code.', repositoryRoot));
this.showRepoOnHomeDriveRootWarning = false;
}
this.logger.trace(`Repository for path ${repositoryRoot} is on the root of the HOMEDRIVE`);
return;
}
}
const dotGit = await this.git.getRepositoryDotGit(repositoryRoot);
const repository = new Repository(this.git.open(repositoryRoot, dotGit, this.logger), this, this, this, this.globalState, this.logger, this.telemetryReporter);
this.open(repository);
repository.status(); // do not await this, we want SCM to know about the repo asap
} catch (ex) {
// Handle unsafe repository
const match = /^fatal: detected dubious ownership in repository at \'([^']+)\'$/m.exec(ex.stderr);
if (match && match.length === 2) {
const unsafeRepositoryPath = path.normalize(match[1]);
this.logger.trace(`Unsafe repository: ${unsafeRepositoryPath}`);
// Show a notification if the unsafe repository is opened after the initial repository scan
if (this._state === 'initialized' && !this._unsafeRepositories.has(unsafeRepositoryPath)) {
this.showUnsafeRepositoryNotification();
}
this._unsafeRepositories.add(unsafeRepositoryPath);
return;
}
// noop
this.logger.trace(`Opening repository for path='${repoPath}' failed; ex=${ex}`);
}
}
private shouldRepositoryBeIgnored(repositoryRoot: string): boolean {
const config = workspace.getConfiguration('git');
const ignoredRepos = config.get<string[]>('ignoredRepositories') || [];
for (const ignoredRepo of ignoredRepos) {
if (path.isAbsolute(ignoredRepo)) {
if (pathEquals(ignoredRepo, repositoryRoot)) {
return true;
}
} else {
for (const folder of workspace.workspaceFolders || []) {
if (pathEquals(path.join(folder.uri.fsPath, ignoredRepo), repositoryRoot)) {
return true;
}
}
}
}
return false;
}
private open(repository: Repository): void {
this.logger.info(`Open repository: ${repository.root}`);
const onDidDisappearRepository = filterEvent(repository.onDidChangeState, state => state === RepositoryState.Disposed);
const disappearListener = onDidDisappearRepository(() => dispose());
const changeListener = repository.onDidChangeRepository(uri => this._onDidChangeRepository.fire({ repository, uri }));
const originalResourceChangeListener = repository.onDidChangeOriginalResource(uri => this._onDidChangeOriginalResource.fire({ repository, uri }));
const shouldDetectSubmodules = workspace
.getConfiguration('git', Uri.file(repository.root))
.get<boolean>('detectSubmodules') as boolean;
const submodulesLimit = workspace
.getConfiguration('git', Uri.file(repository.root))
.get<number>('detectSubmodulesLimit') as number;
const checkForSubmodules = () => {
if (!shouldDetectSubmodules) {
this.logger.trace('Automatic detection of git submodules is not enabled.');
return;
}
if (repository.submodules.length > submodulesLimit) {
window.showWarningMessage(l10n.t('The "{0}" repository has {1} submodules which won\'t be opened automatically. You can still open each one individually by opening a file within.', path.basename(repository.root), repository.submodules.length));
statusListener.dispose();
}
repository.submodules
.slice(0, submodulesLimit)
.map(r => path.join(repository.root, r.path))
.forEach(p => {
this.logger.trace(`Opening submodule: '${p}'`);
this.eventuallyScanPossibleGitRepository(p);
});
};
const updateMergeChanges = () => {
// set mergeChanges context
const mergeChanges: Uri[] = [];
for (const { repository } of this.openRepositories.values()) {
for (const state of repository.mergeGroup.resourceStates) {
mergeChanges.push(state.resourceUri);
}
}
commands.executeCommand('setContext', 'git.mergeChanges', mergeChanges);
};
const statusListener = repository.onDidRunGitStatus(() => {
checkForSubmodules();
updateMergeChanges();
});
checkForSubmodules();
const updateCommitInProgressContext = () => {
let commitInProgress = false;
for (const { repository } of this.openRepositories.values()) {
if (repository.operations.isRunning(Operation.Commit)) {
commitInProgress = true;
break;
}
}
commands.executeCommand('setContext', 'commitInProgress', commitInProgress);
};
const operationEvent = anyEvent(repository.onDidRunOperation as Event<any>, repository.onRunOperation as Event<any>);
const operationListener = operationEvent(() => updateCommitInProgressContext());
updateCommitInProgressContext();
const dispose = () => {
disappearListener.dispose();
changeListener.dispose();
originalResourceChangeListener.dispose();
statusListener.dispose();
operationListener.dispose();
repository.dispose();
this.openRepositories = this.openRepositories.filter(e => e !== openRepository);
this._onDidCloseRepository.fire(repository);
};
const openRepository = { repository, dispose };
this.openRepositories.push(openRepository);
updateMergeChanges();
this._onDidOpenRepository.fire(repository);
}
close(repository: Repository): void {
const openRepository = this.getOpenRepository(repository);
if (!openRepository) {
return;
}
this.logger.info(`Close repository: ${repository.root}`);
openRepository.dispose();
}
async pickRepository(): Promise<Repository | undefined> {
if (this.openRepositories.length === 0) {
throw new Error(l10n.t('There are no available repositories'));
}
const picks = this.openRepositories.map((e, index) => new RepositoryPick(e.repository, index));
const active = window.activeTextEditor;
const repository = active && this.getRepository(active.document.fileName);
const index = picks.findIndex(pick => pick.repository === repository);
// Move repository pick containing the active text editor to appear first
if (index > -1) {
picks.unshift(...picks.splice(index, 1));
}
const placeHolder = l10n.t('Choose a repository');
const pick = await window.showQuickPick(picks, { placeHolder });
return pick && pick.repository;
}
getRepository(sourceControl: SourceControl): Repository | undefined;
getRepository(resourceGroup: SourceControlResourceGroup): Repository | undefined;
getRepository(path: string): Repository | undefined;
getRepository(resource: Uri): Repository | undefined;
getRepository(hint: any): Repository | undefined {
const liveRepository = this.getOpenRepository(hint);
return liveRepository && liveRepository.repository;
}
private getRepositoryExact(repoPath: string): Repository | undefined {
const openRepository = this.openRepositories
.find(r => pathEquals(r.repository.root, repoPath));
return openRepository?.repository;
}
private getOpenRepository(repository: Repository): OpenRepository | undefined;
private getOpenRepository(sourceControl: SourceControl): OpenRepository | undefined;
private getOpenRepository(resourceGroup: SourceControlResourceGroup): OpenRepository | undefined;
private getOpenRepository(path: string): OpenRepository | undefined;
private getOpenRepository(resource: Uri): OpenRepository | undefined;
private getOpenRepository(hint: any): OpenRepository | undefined {
if (!hint) {
return undefined;
}
if (hint instanceof Repository) {
return this.openRepositories.filter(r => r.repository === hint)[0];
}
if (hint instanceof ApiRepository) {
return this.openRepositories.filter(r => r.repository === hint.repository)[0];
}
if (typeof hint === 'string') {
hint = Uri.file(hint);
}
if (hint instanceof Uri) {
let resourcePath: string;
if (hint.scheme === 'git') {
resourcePath = fromGitUri(hint).path;
} else {
resourcePath = hint.fsPath;
}
outer:
for (const liveRepository of this.openRepositories.sort((a, b) => b.repository.root.length - a.repository.root.length)) {
if (!isDescendant(liveRepository.repository.root, resourcePath)) {
continue;
}
for (const submodule of liveRepository.repository.submodules) {
const submoduleRoot = path.join(liveRepository.repository.root, submodule.path);
if (isDescendant(submoduleRoot, resourcePath)) {
continue outer;
}
}
return liveRepository;
}
return undefined;
}
for (const liveRepository of this.openRepositories) {
const repository = liveRepository.repository;
if (hint === repository.sourceControl) {
return liveRepository;
}
if (hint === repository.mergeGroup || hint === repository.indexGroup || hint === repository.workingTreeGroup) {
return liveRepository;
}
}
return undefined;
}
getRepositoryForSubmodule(submoduleUri: Uri): Repository | undefined {
for (const repository of this.repositories) {
for (const submodule of repository.submodules) {
const submodulePath = path.join(repository.root, submodule.path);
if (submodulePath === submoduleUri.fsPath) {
return repository;
}
}
}
return undefined;
}
registerRemoteSourcePublisher(publisher: RemoteSourcePublisher): Disposable {
this.remoteSourcePublishers.add(publisher);
this._onDidAddRemoteSourcePublisher.fire(publisher);
return toDisposable(() => {
this.remoteSourcePublishers.delete(publisher);
this._onDidRemoveRemoteSourcePublisher.fire(publisher);
});
}
getRemoteSourcePublishers(): RemoteSourcePublisher[] {
return [...this.remoteSourcePublishers.values()];
}
registerPostCommitCommandsProvider(provider: PostCommitCommandsProvider): Disposable {
this.postCommitCommandsProviders.add(provider);
this._onDidChangePostCommitCommandsProviders.fire();
return toDisposable(() => {
this.postCommitCommandsProviders.delete(provider);
this._onDidChangePostCommitCommandsProviders.fire();
});
}
getPostCommitCommandsProviders(): PostCommitCommandsProvider[] {
return [...this.postCommitCommandsProviders.values()];
}
registerCredentialsProvider(provider: CredentialsProvider): Disposable {
return this.askpass.registerCredentialsProvider(provider);
}
registerPushErrorHandler(handler: PushErrorHandler): Disposable {
this.pushErrorHandlers.add(handler);
return toDisposable(() => this.pushErrorHandlers.delete(handler));
}
getPushErrorHandlers(): PushErrorHandler[] {
return [...this.pushErrorHandlers];
}
private async showUnsafeRepositoryNotification(): Promise<void> {
const message = this._unsafeRepositories.size === 1 ?
l10n.t('The git repository in the current folder is potentially unsafe as the folder is owned by someone other than the current user.') :
l10n.t('The git repositories in the current folder are potentially unsafe as the folders are owned by someone other than the current user.');
const manageUnsafeRepositories = l10n.t('Manage Unsafe Repositories');
const learnMore = l10n.t('Learn More');
const choice = await window.showErrorMessage(message, manageUnsafeRepositories, learnMore);
if (choice === manageUnsafeRepositories) {
// Manage Unsafe Repositories
commands.executeCommand('git.manageUnsafeRepositories');
} else if (choice === learnMore) {
// Learn More
commands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-scm'));
}
}
dispose(): void {
const openRepositories = [...this.openRepositories];
openRepositories.forEach(r => r.dispose());
this.openRepositories = [];
this.possibleGitRepositoryPaths.clear();
this.disposables = dispose(this.disposables);
}
}
| extensions/git/src/model.ts | 1 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.00786107499152422,
0.0003745727881323546,
0.00016183240222744644,
0.0001686143223196268,
0.000964601116720587
] |
{
"id": 1,
"code_window": [
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepositories\": {\n",
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 340
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// https://github.com/microsoft/vscode/issues/153213
declare module 'vscode' {
export class TabInputTextMerge {
readonly base: Uri;
readonly input1: Uri;
readonly input2: Uri;
readonly result: Uri;
constructor(base: Uri, input1: Uri, input2: Uri, result: Uri);
}
export interface Tab {
readonly input: TabInputText | TabInputTextDiff | TabInputTextMerge | TabInputCustom | TabInputWebview | TabInputNotebook | TabInputNotebookDiff | TabInputTerminal | unknown;
}
}
| src/vscode-dts/vscode.proposed.tabInputTextMerge.d.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0001697957923170179,
0.00016808207146823406,
0.00016681062697898597,
0.0001676397951086983,
0.000001258175757357094
] |
{
"id": 1,
"code_window": [
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepositories\": {\n",
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 340
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { IPosition } from 'vs/editor/common/core/position';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const ITextResourceConfigurationService = createDecorator<ITextResourceConfigurationService>('textResourceConfigurationService');
export interface ITextResourceConfigurationChangeEvent {
/**
* All affected keys. Also includes language overrides and keys changed under language overrides.
*/
readonly affectedKeys: string[];
/**
* Returns `true` if the given section has changed for the given resource.
*
* Example: To check if the configuration section has changed for a given resource use `e.affectsConfiguration(resource, section)`.
*
* @param resource Resource for which the configuration has to be checked.
* @param section Section of the configuration
*/
affectsConfiguration(resource: URI, section: string): boolean;
}
export interface ITextResourceConfigurationService {
readonly _serviceBrand: undefined;
/**
* Event that fires when the configuration changes.
*/
onDidChangeConfiguration: Event<ITextResourceConfigurationChangeEvent>;
/**
* Fetches the value of the section for the given resource by applying language overrides.
* Value can be of native type or an object keyed off the section name.
*
* @param resource - Resource for which the configuration has to be fetched.
* @param position - Position in the resource for which configuration has to be fetched.
* @param section - Section of the configuraion.
*
*/
getValue<T>(resource: URI | undefined, section?: string): T;
getValue<T>(resource: URI | undefined, position?: IPosition, section?: string): T;
/**
* Update the configuration value for the given resource at the effective location.
*
* - If configurationTarget is not specified, target will be derived by checking where the configuration is defined.
* - If the language overrides for the give resource contains the configuration, then it is updated.
*
* @param resource Resource for which the configuration has to be updated
* @param key Configuration key
* @param value Configuration value
* @param configurationTarget Optional target into which the configuration has to be updated.
* If not specified, target will be derived by checking where the configuration is defined.
*/
updateValue(resource: URI, key: string, value: any, configurationTarget?: ConfigurationTarget): Promise<void>;
}
export const ITextResourcePropertiesService = createDecorator<ITextResourcePropertiesService>('textResourcePropertiesService');
export interface ITextResourcePropertiesService {
readonly _serviceBrand: undefined;
/**
* Returns the End of Line characters for the given resource
*/
getEOL(resource: URI, language?: string): string;
}
| src/vs/editor/common/services/textResourceConfiguration.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0001707187038846314,
0.00016805549967102706,
0.00016199436504393816,
0.0001686168252490461,
0.000002473094127708464
] |
{
"id": 1,
"code_window": [
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n",
"\t},\n",
"\t\"view.workbench.scm.unsafeRepositories\": {\n",
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).\",\n",
"\t\t\"comment\": [\n",
"\t\t\t\"{Locked='](command:git.manageUnsafeRepositories'}\",\n",
"\t\t\t\"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code\",\n",
"\t\t\t\"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links\"\n",
"\t\t]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"message\": \"The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).\",\n"
],
"file_path": "extensions/git/package.nls.json",
"type": "replace",
"edit_start_line_idx": 340
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { deepStrictEqual } from 'assert';
import { TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities';
import { TerminalCapabilityStore, TerminalCapabilityStoreMultiplexer } from 'vs/platform/terminal/common/capabilities/terminalCapabilityStore';
suite('TerminalCapabilityStore', () => {
let store: TerminalCapabilityStore;
let addEvents: TerminalCapability[];
let removeEvents: TerminalCapability[];
setup(() => {
store = new TerminalCapabilityStore();
store.onDidAddCapability(e => addEvents.push(e));
store.onDidRemoveCapability(e => removeEvents.push(e));
addEvents = [];
removeEvents = [];
});
teardown(() => store.dispose());
test('should fire events when capabilities are added', () => {
assertEvents(addEvents, []);
store.add(TerminalCapability.CwdDetection, null!);
assertEvents(addEvents, [TerminalCapability.CwdDetection]);
});
test('should fire events when capabilities are removed', async () => {
assertEvents(removeEvents, []);
store.add(TerminalCapability.CwdDetection, null!);
assertEvents(removeEvents, []);
store.remove(TerminalCapability.CwdDetection);
assertEvents(removeEvents, [TerminalCapability.CwdDetection]);
});
test('has should return whether a capability is present', () => {
deepStrictEqual(store.has(TerminalCapability.CwdDetection), false);
store.add(TerminalCapability.CwdDetection, null!);
deepStrictEqual(store.has(TerminalCapability.CwdDetection), true);
store.remove(TerminalCapability.CwdDetection);
deepStrictEqual(store.has(TerminalCapability.CwdDetection), false);
});
test('items should reflect current state', () => {
deepStrictEqual(Array.from(store.items), []);
store.add(TerminalCapability.CwdDetection, null!);
deepStrictEqual(Array.from(store.items), [TerminalCapability.CwdDetection]);
store.add(TerminalCapability.NaiveCwdDetection, null!);
deepStrictEqual(Array.from(store.items), [TerminalCapability.CwdDetection, TerminalCapability.NaiveCwdDetection]);
store.remove(TerminalCapability.CwdDetection);
deepStrictEqual(Array.from(store.items), [TerminalCapability.NaiveCwdDetection]);
});
});
suite('TerminalCapabilityStoreMultiplexer', () => {
let multiplexer: TerminalCapabilityStoreMultiplexer;
let store1: TerminalCapabilityStore;
let store2: TerminalCapabilityStore;
let addEvents: TerminalCapability[];
let removeEvents: TerminalCapability[];
setup(() => {
multiplexer = new TerminalCapabilityStoreMultiplexer();
multiplexer.onDidAddCapability(e => addEvents.push(e));
multiplexer.onDidRemoveCapability(e => removeEvents.push(e));
store1 = new TerminalCapabilityStore();
store2 = new TerminalCapabilityStore();
addEvents = [];
removeEvents = [];
});
teardown(() => multiplexer.dispose());
test('should fire events when capabilities are enabled', async () => {
assertEvents(addEvents, []);
multiplexer.add(store1);
multiplexer.add(store2);
store1.add(TerminalCapability.CwdDetection, null!);
assertEvents(addEvents, [TerminalCapability.CwdDetection]);
store2.add(TerminalCapability.NaiveCwdDetection, null!);
assertEvents(addEvents, [TerminalCapability.NaiveCwdDetection]);
});
test('should fire events when capabilities are disabled', async () => {
assertEvents(removeEvents, []);
multiplexer.add(store1);
multiplexer.add(store2);
store1.add(TerminalCapability.CwdDetection, null!);
store2.add(TerminalCapability.NaiveCwdDetection, null!);
assertEvents(removeEvents, []);
store1.remove(TerminalCapability.CwdDetection);
assertEvents(removeEvents, [TerminalCapability.CwdDetection]);
store2.remove(TerminalCapability.NaiveCwdDetection);
assertEvents(removeEvents, [TerminalCapability.NaiveCwdDetection]);
});
test('should fire events when stores are added', async () => {
assertEvents(addEvents, []);
store1.add(TerminalCapability.CwdDetection, null!);
assertEvents(addEvents, []);
store2.add(TerminalCapability.NaiveCwdDetection, null!);
multiplexer.add(store1);
multiplexer.add(store2);
assertEvents(addEvents, [TerminalCapability.CwdDetection, TerminalCapability.NaiveCwdDetection]);
});
test('items should return items from all stores', () => {
deepStrictEqual(Array.from(multiplexer.items).sort(), [].sort());
multiplexer.add(store1);
multiplexer.add(store2);
store1.add(TerminalCapability.CwdDetection, null!);
deepStrictEqual(Array.from(multiplexer.items).sort(), [TerminalCapability.CwdDetection].sort());
store1.add(TerminalCapability.CommandDetection, null!);
store2.add(TerminalCapability.NaiveCwdDetection, null!);
deepStrictEqual(Array.from(multiplexer.items).sort(), [TerminalCapability.CwdDetection, TerminalCapability.CommandDetection, TerminalCapability.NaiveCwdDetection].sort());
store2.remove(TerminalCapability.NaiveCwdDetection);
deepStrictEqual(Array.from(multiplexer.items).sort(), [TerminalCapability.CwdDetection, TerminalCapability.CommandDetection].sort());
});
test('has should return whether a capability is present', () => {
deepStrictEqual(multiplexer.has(TerminalCapability.CwdDetection), false);
multiplexer.add(store1);
store1.add(TerminalCapability.CwdDetection, null!);
deepStrictEqual(multiplexer.has(TerminalCapability.CwdDetection), true);
store1.remove(TerminalCapability.CwdDetection);
deepStrictEqual(multiplexer.has(TerminalCapability.CwdDetection), false);
});
});
function assertEvents(actual: TerminalCapability[], expected: TerminalCapability[]) {
deepStrictEqual(actual, expected);
actual.length = 0;
}
| src/vs/workbench/contrib/terminal/test/browser/capabilities/terminalCapabilityStore.test.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.00017267820658162236,
0.0001695737155387178,
0.0001636452943785116,
0.0001705630129436031,
0.000002416701136098709
] |
{
"id": 2,
"code_window": [
"\t\t\t// Manage Unsafe Repositories\n",
"\t\t\tcommands.executeCommand('git.manageUnsafeRepositories');\n",
"\t\t} else if (choice === learnMore) {\n",
"\t\t\t// Learn More\n",
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-scm'));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tdispose(): void {\n",
"\t\tconst openRepositories = [...this.openRepositories];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-git-unsafe-repository'));\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 742
} | {
"displayName": "Git",
"description": "Git SCM Integration",
"command.clone": "Clone",
"command.cloneRecursive": "Clone (Recursive)",
"command.init": "Initialize Repository",
"command.openRepository": "Open Repository",
"command.close": "Close Repository",
"command.refresh": "Refresh",
"command.openChange": "Open Changes",
"command.openAllChanges": "Open All Changes",
"command.openFile": "Open File",
"command.openHEADFile": "Open File (HEAD)",
"command.stage": "Stage Changes",
"command.stageAll": "Stage All Changes",
"command.stageAllTracked": "Stage All Tracked Changes",
"command.stageAllUntracked": "Stage All Untracked Changes",
"command.stageAllMerge": "Stage All Merge Changes",
"command.stageSelectedRanges": "Stage Selected Ranges",
"command.revertSelectedRanges": "Revert Selected Ranges",
"command.stageChange": "Stage Change",
"command.revertChange": "Revert Change",
"command.unstage": "Unstage Changes",
"command.unstageAll": "Unstage All Changes",
"command.unstageSelectedRanges": "Unstage Selected Ranges",
"command.rename": "Rename",
"command.clean": "Discard Changes",
"command.cleanAll": "Discard All Changes",
"command.cleanAllTracked": "Discard All Tracked Changes",
"command.cleanAllUntracked": "Discard All Untracked Changes",
"command.closeAllDiffEditors": "Close All Diff Editors",
"command.commit": "Commit",
"command.commitStaged": "Commit Staged",
"command.commitEmpty": "Commit Empty",
"command.commitStagedSigned": "Commit Staged (Signed Off)",
"command.commitStagedAmend": "Commit Staged (Amend)",
"command.commitAll": "Commit All",
"command.commitAllSigned": "Commit All (Signed Off)",
"command.commitAllAmend": "Commit All (Amend)",
"command.commitNoVerify": "Commit (No Verify)",
"command.commitStagedNoVerify": "Commit Staged (No Verify)",
"command.commitEmptyNoVerify": "Commit Empty (No Verify)",
"command.commitStagedSignedNoVerify": "Commit Staged (Signed Off, No Verify)",
"command.commitStagedAmendNoVerify": "Commit Staged (Amend, No Verify)",
"command.commitAllNoVerify": "Commit All (No Verify)",
"command.commitAllSignedNoVerify": "Commit All (Signed Off, No Verify)",
"command.commitAllAmendNoVerify": "Commit All (Amend, No Verify)",
"command.commitMessageAccept": "Accept Commit Message",
"command.commitMessageDiscard": "Discard Commit Message",
"command.restoreCommitTemplate": "Restore Commit Template",
"command.undoCommit": "Undo Last Commit",
"command.checkout": "Checkout to...",
"command.checkoutDetached": "Checkout to (Detached)...",
"command.branch": "Create Branch...",
"command.branchFrom": "Create Branch From...",
"command.deleteBranch": "Delete Branch...",
"command.renameBranch": "Rename Branch...",
"command.cherryPick": "Cherry Pick...",
"command.merge": "Merge Branch...",
"command.mergeAbort": "Abort Merge",
"command.rebase": "Rebase Branch...",
"command.createTag": "Create Tag",
"command.deleteTag": "Delete Tag",
"command.fetch": "Fetch",
"command.fetchPrune": "Fetch (Prune)",
"command.fetchAll": "Fetch From All Remotes",
"command.pull": "Pull",
"command.pullRebase": "Pull (Rebase)",
"command.pullFrom": "Pull from...",
"command.push": "Push",
"command.pushForce": "Push (Force)",
"command.pushTo": "Push to...",
"command.pushToForce": "Push to... (Force)",
"command.pushFollowTags": "Push (Follow Tags)",
"command.pushFollowTagsForce": "Push (Follow Tags, Force)",
"command.pushTags": "Push Tags",
"command.addRemote": "Add Remote...",
"command.removeRemote": "Remove Remote",
"command.sync": "Sync",
"command.syncRebase": "Sync (Rebase)",
"command.publish": "Publish Branch...",
"command.showOutput": "Show Git Output",
"command.ignore": "Add to .gitignore",
"command.revealInExplorer": "Reveal in Explorer View",
"command.revealFileInOS.linux": "Open Containing Folder",
"command.revealFileInOS.mac": "Reveal in Finder",
"command.revealFileInOS.windows": "Reveal in File Explorer",
"command.rebaseAbort": "Abort Rebase",
"command.stashIncludeUntracked": "Stash (Include Untracked)",
"command.stash": "Stash",
"command.stashPop": "Pop Stash...",
"command.stashPopLatest": "Pop Latest Stash",
"command.stashApply": "Apply Stash...",
"command.stashApplyLatest": "Apply Latest Stash",
"command.stashDrop": "Drop Stash...",
"command.stashDropAll": "Drop All Stashes...",
"command.timelineOpenDiff": "Open Changes",
"command.timelineCopyCommitId": "Copy Commit ID",
"command.timelineCopyCommitMessage": "Copy Commit Message",
"command.timelineSelectForCompare": "Select for Compare",
"command.timelineCompareWithSelected": "Compare with Selected",
"command.manageUnsafeRepositories": "Manage Unsafe Repositories",
"command.api.getRepositories": "Get Repositories",
"command.api.getRepositoryState": "Get Repository State",
"command.api.getRemoteSources": "Get Remote Sources",
"command.git.acceptMerge": "Complete Merge",
"command.git.openMergeEditor": "Resolve in Merge Editor",
"command.git.runGitMerge": "Compute Conflicts With Git",
"command.git.runGitMergeDiff3": "Compute Conflicts With Git (Diff3)",
"config.enabled": "Whether git is enabled.",
"config.path": "Path and filename of the git executable, e.g. `C:\\Program Files\\Git\\bin\\git.exe` (Windows). This can also be an array of string values containing multiple paths to look up.",
"config.autoRepositoryDetection": "Configures when repositories should be automatically detected.",
"config.autoRepositoryDetection.true": "Scan for both subfolders of the current opened folder and parent folders of open files.",
"config.autoRepositoryDetection.false": "Disable automatic repository scanning.",
"config.autoRepositoryDetection.subFolders": "Scan for subfolders of the currently opened folder.",
"config.autoRepositoryDetection.openEditors": "Scan for parent folders of open files.",
"config.autorefresh": "Whether auto refreshing is enabled.",
"config.autofetch": "When set to true, commits will automatically be fetched from the default remote of the current Git repository. Setting to `all` will fetch from all remotes.",
"config.autofetchPeriod": "Duration in seconds between each automatic git fetch, when `#git.autofetch#` is enabled.",
"config.confirmSync": "Confirm before synchronizing git repositories.",
"config.countBadge": "Controls the Git count badge.",
"config.countBadge.all": "Count all changes.",
"config.countBadge.tracked": "Count only tracked changes.",
"config.countBadge.off": "Turn off counter.",
"config.checkoutType": "Controls what type of git refs are listed when running `Checkout to...`.",
"config.checkoutType.local": "Local branches",
"config.checkoutType.tags": "Tags",
"config.checkoutType.remote": "Remote branches",
"config.branchPrefix": "Prefix used when creating a new branch.",
"config.branchProtection": "List of protected branches. By default, a prompt is shown before changes are committed to a protected branch. The prompt can be controlled using the `#git.branchProtectionPrompt#` setting.",
"config.branchProtectionPrompt": "Controls whether a prompt is being shown before changes are committed to a protected branch.",
"config.branchProtectionPrompt.alwaysCommit": "Always commit changes to the protected branch.",
"config.branchProtectionPrompt.alwaysCommitToNewBranch": "Always commit changes to a new branch.",
"config.branchProtectionPrompt.alwaysPrompt": "Always prompt before changes are committed to a protected branch.",
"config.branchRandomNameDictionary": "List of dictionaries used for the randomly generated branch name. Each value represents the dictionary used to generate the segment of the branch name. Supported dictionaries: `adjectives`, `animals`, `colors` and `numbers`.",
"config.branchRandomNameDictionary.adjectives": "A random adjective",
"config.branchRandomNameDictionary.animals": "A random animal name",
"config.branchRandomNameDictionary.colors": "A random color name",
"config.branchRandomNameDictionary.numbers": "A random number between 100 and 999",
"config.branchRandomNameEnable": "Controls whether a random name is generated when creating a new branch.",
"config.branchValidationRegex": "A regular expression to validate new branch names.",
"config.branchWhitespaceChar": "The character to replace whitespace in new branch names, and to separate segments of a randomly generated branch name.",
"config.ignoreLegacyWarning": "Ignores the legacy Git warning.",
"config.ignoreMissingGitWarning": "Ignores the warning when Git is missing.",
"config.ignoreWindowsGit27Warning": "Ignores the warning when Git 2.25 - 2.26 is installed on Windows.",
"config.ignoreLimitWarning": "Ignores the warning when there are too many changes in a repository.",
"config.ignoreRebaseWarning": "Ignores the warning when it looks like the branch might have been rebased when pulling.",
"config.defaultCloneDirectory": "The default location to clone a git repository.",
"config.useEditorAsCommitInput": "Controls whether a full text editor will be used to author commit messages, whenever no message is provided in the commit input box.",
"config.verboseCommit": "Enable verbose output when `#git.useEditorAsCommitInput#` is enabled.",
"config.enableSmartCommit": "Commit all changes when there are no staged changes.",
"config.smartCommitChanges": "Control which changes are automatically staged by Smart Commit.",
"config.smartCommitChanges.all": "Automatically stage all changes.",
"config.smartCommitChanges.tracked": "Automatically stage tracked changes only.",
"config.suggestSmartCommit": "Suggests to enable smart commit (commit all changes when there are no staged changes).",
"config.enableCommitSigning": "Enables commit signing with GPG or X.509.",
"config.discardAllScope": "Controls what changes are discarded by the `Discard all changes` command. `all` discards all changes. `tracked` discards only tracked files. `prompt` shows a prompt dialog every time the action is run.",
"config.decorations.enabled": "Controls whether Git contributes colors and badges to the Explorer and the Open Editors view.",
"config.enableStatusBarSync": "Controls whether the Git Sync command appears in the status bar.",
"config.followTagsWhenSync": "Follow push all tags when running the sync command.",
"config.promptToSaveFilesBeforeStash": "Controls whether Git should check for unsaved files before stashing changes.",
"config.promptToSaveFilesBeforeStash.always": "Check for any unsaved files.",
"config.promptToSaveFilesBeforeStash.staged": "Check only for unsaved staged files.",
"config.promptToSaveFilesBeforeStash.never": "Disable this check.",
"config.promptToSaveFilesBeforeCommit": "Controls whether Git should check for unsaved files before committing.",
"config.promptToSaveFilesBeforeCommit.always": "Check for any unsaved files.",
"config.promptToSaveFilesBeforeCommit.staged": "Check only for unsaved staged files.",
"config.promptToSaveFilesBeforeCommit.never": "Disable this check.",
"config.postCommitCommand": "Run a git command after a successful commit.",
"config.postCommitCommand.none": "Don't run any command after a commit.",
"config.postCommitCommand.push": "Run 'git push' after a successful commit.",
"config.postCommitCommand.sync": "Run 'git pull' and 'git push' after a successful commit.",
"config.rememberPostCommitCommand": "Remember the last git command that ran after a commit.",
"config.openAfterClone": "Controls whether to open a repository automatically after cloning.",
"config.openAfterClone.always": "Always open in current window.",
"config.openAfterClone.alwaysNewWindow": "Always open in a new window.",
"config.openAfterClone.whenNoFolderOpen": "Only open in current window when no folder is opened.",
"config.openAfterClone.prompt": "Always prompt for action.",
"config.showInlineOpenFileAction": "Controls whether to show an inline Open File action in the Git changes view.",
"config.showPushSuccessNotification": "Controls whether to show a notification when a push is successful.",
"config.inputValidation": "Controls when to show commit message input validation.",
"config.inputValidationLength": "Controls the commit message length threshold for showing a warning.",
"config.inputValidationSubjectLength": "Controls the commit message subject length threshold for showing a warning. Unset it to inherit the value of `config.inputValidationLength`.",
"config.detectSubmodules": "Controls whether to automatically detect git submodules.",
"config.detectSubmodulesLimit": "Controls the limit of git submodules detected.",
"config.alwaysShowStagedChangesResourceGroup": "Always show the Staged Changes resource group.",
"config.alwaysSignOff": "Controls the signoff flag for all commits.",
"config.ignoreSubmodules": "Ignore modifications to submodules in the file tree.",
"config.ignoredRepositories": "List of git repositories to ignore.",
"config.scanRepositories": "List of paths to search for git repositories in.",
"config.commandsToLog": {
"message": "List of git commands (ex: commit, push) that would have their `stdout` logged to the [git output](command:git.showOutput). If the git command has a client-side hook configured, the client-side hook's `stdout` will also be logged to the [git output](command:git.showOutput).",
"comment": [
"{Locked='](command:git.showOutput'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"config.showProgress": "Controls whether git actions should show progress.",
"config.rebaseWhenSync": "Force git to use rebase when running the sync command.",
"config.confirmEmptyCommits": "Always confirm the creation of empty commits for the 'Git: Commit Empty' command.",
"config.fetchOnPull": "When enabled, fetch all branches when pulling. Otherwise, fetch just the current one.",
"config.pullBeforeCheckout": "Controls whether a branch that does not have outgoing commits is fast-forwarded before it is checked out.",
"config.pullTags": "Fetch all tags when pulling.",
"config.pruneOnFetch": "Prune when fetching.",
"config.autoStash": "Stash any changes before pulling and restore them after successful pull.",
"config.allowForcePush": "Controls whether force push (with or without lease) is enabled.",
"config.useForcePushWithLease": "Controls whether force pushing uses the safer force-with-lease variant.",
"config.confirmForcePush": "Controls whether to ask for confirmation before force-pushing.",
"config.allowNoVerifyCommit": "Controls whether commits without running pre-commit and commit-msg hooks are allowed.",
"config.confirmNoVerifyCommit": "Controls whether to ask for confirmation before committing without verification.",
"config.closeDiffOnOperation": "Controls whether the diff editor should be automatically closed when changes are stashed, committed, discarded, staged, or unstaged.",
"config.openDiffOnClick": "Controls whether the diff editor should be opened when clicking a change. Otherwise the regular editor will be opened.",
"config.supportCancellation": "Controls whether a notification comes up when running the Sync action, which allows the user to cancel the operation.",
"config.branchSortOrder": "Controls the sort order for branches.",
"config.untrackedChanges": "Controls how untracked changes behave.",
"config.untrackedChanges.mixed": "All changes, tracked and untracked, appear together and behave equally.",
"config.untrackedChanges.separate": "Untracked changes appear separately in the Source Control view. They are also excluded from several actions.",
"config.untrackedChanges.hidden": "Untracked changes are hidden and excluded from several actions.",
"config.requireGitUserConfig": "Controls whether to require explicit Git user configuration or allow Git to guess if missing.",
"config.showCommitInput": "Controls whether to show the commit input in the Git source control panel.",
"config.terminalAuthentication": "Controls whether to enable VS Code to be the authentication handler for Git processes spawned in the Integrated Terminal. Note: Terminals need to be restarted to pick up a change in this setting.",
"config.terminalGitEditor": "Controls whether to enable VS Code to be the Git editor for Git processes spawned in the integrated terminal. Note: Terminals need to be restarted to pick up a change in this setting.",
"config.timeline.showAuthor": "Controls whether to show the commit author in the Timeline view.",
"config.timeline.showUncommitted": "Controls whether to show uncommitted changes in the Timeline view.",
"config.timeline.date": "Controls which date to use for items in the Timeline view.",
"config.timeline.date.committed": "Use the committed date",
"config.timeline.date.authored": "Use the authored date",
"config.useCommitInputAsStashMessage": "Controls whether to use the message from the commit input box as the default stash message.",
"config.showActionButton": "Controls whether an action button is shown in the Source Control view.",
"config.showActionButton.commit": "Show an action button to commit changes when the local branch has modified files ready to be committed.",
"config.showActionButton.publish": "Show an action button to publish the local branch when it does not have a tracking remote branch.",
"config.showActionButton.sync": "Show an action button to synchronize changes when the local branch is either ahead or behind the remote branch.",
"config.statusLimit": "Controls how to limit the number of changes that can be parsed from Git status command. Can be set to 0 for no limit.",
"config.experimental.installGuide": "Experimental improvements for the git setup flow.",
"config.repositoryScanIgnoredFolders": "List of folders that are ignored while scanning for Git repositories when `#git.autoRepositoryDetection#` is set to `true` or `subFolders`.",
"config.repositoryScanMaxDepth": "Controls the depth used when scanning workspace folders for Git repositories when `#git.autoRepositoryDetection#` is set to `true` or `subFolders`. Can be set to `-1` for no limit.",
"config.useIntegratedAskPass": "Controls whether GIT_ASKPASS should be overwritten to use the integrated version.",
"config.mergeEditor": "Open the merge editor for files that are currently under conflict.",
"config.optimisticUpdate": "Controls whether to optimistically update the state of the Source Control view after running git commands.",
"submenu.explorer": "Git",
"submenu.commit": "Commit",
"submenu.commit.amend": "Amend",
"submenu.commit.signoff": "Sign Off",
"submenu.changes": "Changes",
"submenu.pullpush": "Pull, Push",
"submenu.branch": "Branch",
"submenu.remotes": "Remote",
"submenu.stash": "Stash",
"submenu.tags": "Tags",
"colors.added": "Color for added resources.",
"colors.modified": "Color for modified resources.",
"colors.stageModified": "Color for modified resources which have been staged.",
"colors.stageDeleted": "Color for deleted resources which have been staged.",
"colors.deleted": "Color for deleted resources.",
"colors.renamed": "Color for renamed or copied resources.",
"colors.untracked": "Color for untracked resources.",
"colors.ignored": "Color for ignored resources.",
"colors.conflict": "Color for resources with conflicts.",
"colors.submodule": "Color for submodule resources.",
"view.workbench.scm.missing.windows": {
"message": "[Download Git for Windows](https://git-scm.com/download/win)\nAfter installing, please [reload](command:workbench.action.reloadWindow) (or [troubleshoot](command:git.showOutput)). Additional source control providers can be installed [from the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22).",
"comment": [
"{Locked='](command:workbench.action.reloadWindow'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.missing.mac": {
"message": "[Download Git for macOS](https://git-scm.com/download/mac)\nAfter installing, please [reload](command:workbench.action.reloadWindow) (or [troubleshoot](command:git.showOutput)). Additional source control providers can be installed [from the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22).",
"comment": [
"{Locked='](command:workbench.action.reloadWindow'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.missing.linux": {
"message": "Source control depends on Git being installed.\n[Download Git for Linux](https://git-scm.com/download/linux)\nAfter installing, please [reload](command:workbench.action.reloadWindow) (or [troubleshoot](command:git.showOutput)). Additional source control providers can be installed [from the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22).",
"comment": [
"{Locked='](command:workbench.action.reloadWindow'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.missing": "Install Git, a popular source control system, to track code changes and collaborate with others. Learn more in our [Git guides](https://aka.ms/vscode-scm).",
"view.workbench.scm.disabled": {
"message": "If you would like to use git features, please enable git in your [settings](command:workbench.action.openSettings?%5B%22git.enabled%22%5D).\nTo learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:workbench.action.openSettings?%5B%22git.enabled%22%5D'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.empty": {
"message": "In order to use git features, you can open a folder containing a git repository or clone from a URL.\n[Open Folder](command:vscode.openFolder)\n[Clone Repository](command:git.clone)\nTo learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:vscode.openFolder'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.folder": {
"message": "The folder currently open doesn't have a git repository. You can initialize a repository which will enable source control features powered by git.\n[Initialize Repository](command:git.init?%5Btrue%5D)\nTo learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.init?%5Btrue%5D'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.workspace": {
"message": "The workspace currently open doesn't have any folders containing git repositories. You can initialize a repository on a folder which will enable source control features powered by git.\n[Initialize Repository](command:git.init)\nTo learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.init'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.emptyWorkspace": {
"message": "The workspace currently open doesn't have any folders containing git repositories.\n[Add Folder to Workspace](command:workbench.action.addRootFolder)\nTo learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:workbench.action.addRootFolder'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.scanFolderForRepositories": {
"message": "Scanning folder for git repositories..."
},
"view.workbench.scm.scanWorkspaceForRepositories": {
"message": "Scanning workspace for git repositories..."
},
"view.workbench.scm.unsafeRepository": {
"message": "The detected git repository is potentially unsafe as the folder is owned by someone other than the current user.\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.manageUnsafeRepositories'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.unsafeRepositories": {
"message": "The detected git repositories are potentially unsafe as the folders are owned by someone other than the current user.\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.manageUnsafeRepositories'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.cloneRepository": {
"message": "You can clone a repository locally.\n[Clone Repository](command:git.clone 'Clone a repository once the git extension has activated')",
"comment": [
"{Locked='](command:git.clone'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.learnMore": "To learn more about how to use git and source control in VS Code [read our docs](https://aka.ms/vscode-scm)."
}
| extensions/git/package.nls.json | 1 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0005776031757704914,
0.00020180951105430722,
0.00016312261868733913,
0.00016982125816866755,
0.00008181605517165735
] |
{
"id": 2,
"code_window": [
"\t\t\t// Manage Unsafe Repositories\n",
"\t\t\tcommands.executeCommand('git.manageUnsafeRepositories');\n",
"\t\t} else if (choice === learnMore) {\n",
"\t\t\t// Learn More\n",
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-scm'));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tdispose(): void {\n",
"\t\tconst openRepositories = [...this.openRepositories];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-git-unsafe-repository'));\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 742
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* ---------- Find input ---------- */
.monaco-findInput {
position: relative;
}
.monaco-findInput .monaco-inputbox {
font-size: 13px;
width: 100%;
}
.monaco-findInput > .controls {
position: absolute;
top: 3px;
right: 2px;
}
.vs .monaco-findInput.disabled {
background-color: #E1E1E1;
}
/* Theming */
.vs-dark .monaco-findInput.disabled {
background-color: #333;
}
/* Highlighting */
.monaco-findInput.highlight-0 .controls,
.hc-light .monaco-findInput.highlight-0 .controls {
animation: monaco-findInput-highlight-0 100ms linear 0s;
}
.monaco-findInput.highlight-1 .controls,
.hc-light .monaco-findInput.highlight-1 .controls {
animation: monaco-findInput-highlight-1 100ms linear 0s;
}
.hc-black .monaco-findInput.highlight-0 .controls,
.vs-dark .monaco-findInput.highlight-0 .controls {
animation: monaco-findInput-highlight-dark-0 100ms linear 0s;
}
.hc-black .monaco-findInput.highlight-1 .controls,
.vs-dark .monaco-findInput.highlight-1 .controls {
animation: monaco-findInput-highlight-dark-1 100ms linear 0s;
}
@keyframes monaco-findInput-highlight-0 {
0% { background: rgba(253, 255, 0, 0.8); }
100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-1 {
0% { background: rgba(253, 255, 0, 0.8); }
/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
99% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-0 {
0% { background: rgba(255, 255, 255, 0.44); }
100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-1 {
0% { background: rgba(255, 255, 255, 0.44); }
/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
99% { background: transparent; }
}
| src/vs/base/browser/ui/findinput/findInput.css | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.00017829494026955217,
0.00017674345872364938,
0.00017314695287495852,
0.0001778732257662341,
0.0000018264745449414477
] |
{
"id": 2,
"code_window": [
"\t\t\t// Manage Unsafe Repositories\n",
"\t\t\tcommands.executeCommand('git.manageUnsafeRepositories');\n",
"\t\t} else if (choice === learnMore) {\n",
"\t\t\t// Learn More\n",
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-scm'));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tdispose(): void {\n",
"\t\tconst openRepositories = [...this.openRepositories];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-git-unsafe-repository'));\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 742
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, registerEditorAction, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { Range } from 'vs/editor/common/core/range';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { formatDocumentRangesWithSelectedProvider, FormattingMode } from 'vs/editor/contrib/format/browser/format';
import * as nls from 'vs/nls';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Progress } from 'vs/platform/progress/common/progress';
import { getOriginalResource } from 'vs/workbench/contrib/scm/browser/dirtydiffDecorator';
import { ISCMService } from 'vs/workbench/contrib/scm/common/scm';
registerEditorAction(class FormatModifiedAction extends EditorAction {
constructor() {
super({
id: 'editor.action.formatChanges',
label: nls.localize('formatChanges', "Format Modified Lines"),
alias: 'Format Modified Lines',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider),
});
}
async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
const instaService = accessor.get(IInstantiationService);
if (!editor.hasModel()) {
return;
}
const ranges = await instaService.invokeFunction(getModifiedRanges, editor.getModel());
if (isNonEmptyArray(ranges)) {
return instaService.invokeFunction(
formatDocumentRangesWithSelectedProvider, editor, ranges,
FormattingMode.Explicit, Progress.None, CancellationToken.None
);
}
}
});
export async function getModifiedRanges(accessor: ServicesAccessor, modified: ITextModel): Promise<Range[] | undefined | null> {
const scmService = accessor.get(ISCMService);
const workerService = accessor.get(IEditorWorkerService);
const modelService = accessor.get(ITextModelService);
const original = await getOriginalResource(scmService, modified.uri);
if (!original) {
return null; // let undefined signify no changes, null represents no source control (there's probably a better way, but I can't think of one rn)
}
const ranges: Range[] = [];
const ref = await modelService.createModelReference(original);
try {
if (!workerService.canComputeDirtyDiff(original, modified.uri)) {
return undefined;
}
const changes = await workerService.computeDirtyDiff(original, modified.uri, false);
if (!isNonEmptyArray(changes)) {
return undefined;
}
for (const change of changes) {
ranges.push(modified.validateRange(new Range(
change.modifiedStartLineNumber, 1,
change.modifiedEndLineNumber || change.modifiedStartLineNumber /*endLineNumber is 0 when things got deleted*/, Number.MAX_SAFE_INTEGER)
));
}
} finally {
ref.dispose();
}
return ranges;
}
| src/vs/workbench/contrib/format/browser/formatModified.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.00017708218365442008,
0.0001734633115120232,
0.00017007206042762846,
0.00017348174878861755,
0.0000020690413293777965
] |
{
"id": 2,
"code_window": [
"\t\t\t// Manage Unsafe Repositories\n",
"\t\t\tcommands.executeCommand('git.manageUnsafeRepositories');\n",
"\t\t} else if (choice === learnMore) {\n",
"\t\t\t// Learn More\n",
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-scm'));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tdispose(): void {\n",
"\t\tconst openRepositories = [...this.openRepositories];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tcommands.executeCommand('vscode.open', Uri.parse('https://aka.ms/vscode-git-unsafe-repository'));\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 742
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isMacintosh } from 'vs/base/common/platform';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IMainProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { IWebviewManagerService } from 'vs/platform/webview/common/webviewManagerService';
export class WindowIgnoreMenuShortcutsManager {
private readonly _isUsingNativeTitleBars: boolean;
private readonly _webviewMainService: IWebviewManagerService;
constructor(
configurationService: IConfigurationService,
mainProcessService: IMainProcessService,
private readonly _nativeHostService: INativeHostService
) {
this._isUsingNativeTitleBars = configurationService.getValue<string>('window.titleBarStyle') === 'native';
this._webviewMainService = ProxyChannel.toService<IWebviewManagerService>(mainProcessService.getChannel('webview'));
}
public didFocus(): void {
this.setIgnoreMenuShortcuts(true);
}
public didBlur(): void {
this.setIgnoreMenuShortcuts(false);
}
private get _shouldToggleMenuShortcutsEnablement() {
return isMacintosh || this._isUsingNativeTitleBars;
}
protected setIgnoreMenuShortcuts(value: boolean) {
if (this._shouldToggleMenuShortcutsEnablement) {
this._webviewMainService.setIgnoreMenuShortcuts({ windowId: this._nativeHostService.windowId }, value);
}
}
}
| src/vs/workbench/contrib/webview/electron-sandbox/windowIgnoreMenuShortcutsManager.ts | 0 | https://github.com/microsoft/vscode/commit/55d6b17e19e1e8d4f6040097383e61524930e3c4 | [
0.0001753769611241296,
0.00017381006909999996,
0.00017154290981125087,
0.0001746648777043447,
0.0000016472204151796177
] |
{
"id": 0,
"code_window": [
" Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }\n",
"\n",
"export function useFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 15
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.9974769949913025,
0.3978642225265503,
0.00016668312309775501,
0.2030618041753769,
0.43562987446784973
] |
{
"id": 0,
"code_window": [
" Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }\n",
"\n",
"export function useFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 15
} | <template>
<div ref="star" class="absolute bg-primary-300 dark:bg-white rounded-full opacity-100 star" :style="style" />
</template>
<script>
import { defineComponent, ref, computed, onMounted } from '@nuxtjs/composition-api'
export default defineComponent({
setup () {
const style = ref({})
const randomY = ref(null)
const randomX = ref(null)
const randomRadius = computed(() => Math.round(Math.random() * Math.round(4)))
const randomDuration = computed(() => Math.round(Math.random() * Math.round(10)))
onMounted(() => {
randomX.value = Math.random() * Math.floor(document.documentElement.clientWidth)
randomY.value = Math.random() * Math.floor(document.documentElement.clientHeight)
style.value = {
top: randomY.value + 'px',
left: randomX.value + 'px',
height: randomRadius.value + 'px',
width: randomRadius.value + 'px',
animationDuration: randomDuration.value + 's'
}
})
return {
style,
randomRadius,
randomDuration,
randomY,
randomX
}
}
})
</script>
<style lang="postcss" scoped>
/* Stars */
.star {
animation-name: fade;
animation-timing-function: linear;
animation-iteration-count: infinite;
animation-direction: alternate;
}
</style>
| docs/components/atoms/Star.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017772852152120322,
0.00017598900012671947,
0.00017437414498999715,
0.00017591995128896087,
0.0000011498518688313197
] |
{
"id": 0,
"code_window": [
" Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }\n",
"\n",
"export function useFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 15
} | contact_links:
- name: 📚 Documentation
url: https://v3.nuxtjs.org/
about: Check documentation for usage
- name: 💬 Discussions
url: https://github.com/nuxt/framework/discussions
about: Use discussions if you have an idea for improvement and asking questions
| .github/ISSUE_TEMPLATE/config.yml | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017777766333892941,
0.00017777766333892941,
0.00017777766333892941,
0.00017777766333892941,
0
] |
{
"id": 0,
"code_window": [
" Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }\n",
"\n",
"export function useFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 15
} | import destr from 'destr'
import defu from 'defu'
// Bundled runtime config (injected by nitro)
const _runtimeConfig = process.env.RUNTIME_CONFIG as any
// Allow override from process.env and deserialize
for (const type of ['private', 'public']) {
for (const key in _runtimeConfig[type]) {
_runtimeConfig[type][key] = destr(process.env[key] || _runtimeConfig[type][key])
}
}
// Load dynamic app configuration
const appConfig = _runtimeConfig.public.app
appConfig.baseURL = process.env.NUXT_APP_BASE_URL || appConfig.baseURL
appConfig.cdnURL = process.env.NUXT_APP_CDN_URL || appConfig.cdnURL
appConfig.buildAssetsDir = process.env.NUXT_APP_BUILD_ASSETS_DIR || appConfig.buildAssetsDir
// Named exports
export const privateConfig = deepFreeze(defu(_runtimeConfig.private, _runtimeConfig.public))
export const publicConfig = deepFreeze(_runtimeConfig.public)
// Default export (usable for server)
export default privateConfig
// Utils
function deepFreeze (object: Record<string, any>) {
const propNames = Object.getOwnPropertyNames(object)
for (const name of propNames) {
const value = object[name]
if (value && typeof value === 'object') {
deepFreeze(value)
}
}
return Object.freeze(object)
}
| packages/nitro/src/runtime/app/config.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017672221292741597,
0.00016925949603319168,
0.0001626011508051306,
0.00016885733930394053,
0.000006550845682795625
] |
{
"id": 1,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 16
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import { useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt3/src'
import { useRouter } from '#imports'
import { isVue3 } from '#app'
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toMatchTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toMatchTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognises named middleware', () => {
definePageMeta({ middleware: 'test-middleware' })
definePageMeta({ middleware: 'pascal-case' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
})
describe('layouts', () => {
it('recognises named layouts', () => {
definePageMeta({ layout: 'test-layout' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
| test/fixtures/basic/tests/types.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017823050438892096,
0.0001744848705129698,
0.000171216408489272,
0.0001734693651087582,
0.0000025458359687036136
] |
{
"id": 1,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 16
} | import { Plugin } from 'vite'
import { transform } from 'esbuild'
import { visualizer } from 'rollup-plugin-visualizer'
import { ViteBuildContext } from '../vite'
export function analyzePlugin (ctx: ViteBuildContext): Plugin[] {
return [
{
name: 'nuxt:analyze-minify',
async generateBundle (_opts, outputBundle) {
for (const [_bundleId, bundle] of Object.entries(outputBundle)) {
if (bundle.type !== 'chunk') { continue }
const originalEntries = Object.entries(bundle.modules)
const minifiedEntries = await Promise.all(originalEntries.map(async ([moduleId, module]) => {
const { code } = await transform(module.code || '', { minify: true })
return [moduleId, { ...module, code }]
}))
bundle.modules = Object.fromEntries(minifiedEntries)
}
return null
}
},
visualizer({
...ctx.nuxt.options.build.analyze as any,
// @ts-ignore
filename: ctx.nuxt.options.build.analyze.filename.replace('{name}', 'client'),
title: 'Client bundle stats',
gzipSize: true
})
]
}
| packages/vite/src/plugins/analyze.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.000181264549610205,
0.00017629991634748876,
0.00017211667727679014,
0.00017590921197552234,
0.0000037645290831278544
] |
{
"id": 1,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 16
} | export * from './app'
export * from './composables'
| packages/bridge/src/runtime/index.mjs | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017519945686217397,
0.00017519945686217397,
0.00017519945686217397,
0.00017519945686217397,
0
] |
{
"id": 1,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 16
} | {
"name": "nuxi",
"version": "3.0.0",
"repository": "nuxt/framework",
"license": "MIT",
"type": "module",
"exports": {
".": "./dist/index.mjs",
"./cli": "./bin/nuxi.mjs"
},
"bin": "./bin/nuxi.mjs",
"files": [
"bin",
"dist"
],
"scripts": {
"prepack": "unbuild"
},
"devDependencies": {
"@nuxt/design": "0.1.5",
"@nuxt/kit": "3.0.0",
"@nuxt/schema": "3.0.0",
"@types/clear": "^0",
"@types/mri": "^1.1.1",
"@types/rimraf": "^3",
"@types/semver": "^7",
"chokidar": "^3.5.3",
"clear": "^0.1.0",
"clipboardy": "^3.0.0",
"colorette": "^2.0.16",
"consola": "^2.15.3",
"deep-object-diff": "^1.1.7",
"destr": "^1.1.0",
"execa": "^6.1.0",
"flat": "^5.0.2",
"jiti": "^1.12.15",
"listhen": "^0.2.6",
"mlly": "^0.4.3",
"mri": "^1.2.0",
"p-debounce": "^4.0.0",
"pathe": "^0.2.0",
"pkg-types": "^0.3.2",
"rimraf": "^3.0.2",
"scule": "^0.2.1",
"semver": "^7.3.5",
"superb": "^4.0.0",
"tiged": "^2.12.0",
"unbuild": "latest"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
},
"engines": {
"node": "^14.16.0 || ^16.11.0 || ^17.0.0"
}
}
| packages/nuxi/package.json | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017833283345680684,
0.00017521785048302263,
0.00017264463531319052,
0.00017446087440475821,
0.0000021177270355110522
] |
{
"id": 2,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: UseFetchOptions<ResT, Transform, PickKeys> = {}\n",
") {\n",
" if (!opts.key) {\n",
" const keys: any = { u: url }\n",
" if (opts.baseURL) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: UseFetchOptions<_ResT, Transform, PickKeys> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 21
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.9980242252349854,
0.49513575434684753,
0.0002686047228053212,
0.48737555742263794,
0.4907905161380768
] |
{
"id": 2,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: UseFetchOptions<ResT, Transform, PickKeys> = {}\n",
") {\n",
" if (!opts.key) {\n",
" const keys: any = { u: url }\n",
" if (opts.baseURL) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: UseFetchOptions<_ResT, Transform, PickKeys> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 21
} | import type { Plugin } from 'vite'
import fse from 'fs-extra'
import { findExports } from 'mlly'
const PREFIX = 'defaultexport:'
const hasPrefix = (id: string = '') => id.startsWith(PREFIX)
const removePrefix = (id: string = '') => hasPrefix(id) ? id.substr(PREFIX.length) : id
const addDefaultExport = (code: string = '') => code + '\n\n' + 'export default () => {}'
export function defaultExportPlugin () {
return <Plugin>{
name: 'nuxt:default-export',
enforce: 'pre',
resolveId (id, importer) {
if (hasPrefix(id)) {
return id
}
if (importer && hasPrefix(importer)) {
return this.resolve(id, removePrefix(importer))
}
return null
},
async load (id) {
if (hasPrefix(id)) {
let code = await fse.readFile(removePrefix(id), 'utf8')
const exports = findExports(code)
if (!exports.find(i => i.names.includes('default'))) {
code = addDefaultExport(code)
}
return { map: null, code }
}
return null
}
}
}
| packages/bridge/src/vite/plugins/default-export.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017634063260629773,
0.00017292045231442899,
0.00017069089517462999,
0.00017232514801435173,
0.0000023730249267828185
] |
{
"id": 2,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: UseFetchOptions<ResT, Transform, PickKeys> = {}\n",
") {\n",
" if (!opts.key) {\n",
" const keys: any = { u: url }\n",
" if (opts.baseURL) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: UseFetchOptions<_ResT, Transform, PickKeys> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 21
} | import { resolve, join } from 'pathe'
import { existsSync, readdirSync } from 'fs'
import defu from 'defu'
export default {
/** Vue.js config */
vue: {
/**
* Properties that will be set directly on `Vue.config` for vue@2.
*
* @see [vue@2 Documentation](https://v2.vuejs.org/v2/api/#Global-Config)
* @type {import('vue/types/vue').VueConfiguration}
* @version 2
*/
config: {
silent: { $resolve: (val, get) => val ?? !get('dev') },
performance: { $resolve: (val, get) => val ?? get('dev') },
},
/**
* Options for the Vue compiler that will be passed at build time
* @see [documentation](https://vuejs.org/api/application.html#app-config-compileroptions)
* @type {import('@vue/compiler-core').CompilerOptions}
* @version 3
*/
compilerOptions: {}
},
/**
* Nuxt App configuration.
* @version 2
* @version 3
*/
app: {
/**
* The base path of your Nuxt application.
*
* This can be set at runtime by setting the BASE_PATH environment variable.
* @example
* ```bash
* BASE_PATH=/prefix/ node .output/server/index.mjs
* ```
*/
baseURL: '/',
/** The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set). This is set at build time and should not be customized at runtime. */
buildAssetsDir: '/_nuxt/',
/**
* The folder name for the built site assets, relative to `baseURL` (or `cdnURL` if set).
* @deprecated - use `buildAssetsDir` instead
* @version 2
*/
assetsPath: {
$resolve: (val, get) => val ?? get('buildAssetsDir')
},
/**
* An absolute URL to serve the public folder from (production-only).
*
* This can be set to a different value at runtime by setting the CDN_URL environment variable.
* @example
* ```bash
* CDN_URL=https://mycdn.org/ node .output/server/index.mjs
* ```
*/
cdnURL: {
$resolve: (val, get) => get('dev') ? null : val || null
}
},
/**
* The path to a templated HTML file for rendering Nuxt responses.
* Uses `<srcDir>/app.html` if it exists or the Nuxt default template if not.
*
* @example
* ```html
* <!DOCTYPE html>
* <html {{ HTML_ATTRS }}>
* <head {{ HEAD_ATTRS }}>
* {{ HEAD }}
* </head>
* <body {{ BODY_ATTRS }}>
* {{ APP }}
* </body>
* </html>
* ```
* @version 2
*/
appTemplatePath: {
$resolve: (val, get) => {
if (val) {
return resolve(get('srcDir'), val)
}
if (existsSync(join(get('srcDir'), 'app.html'))) {
return join(get('srcDir'), 'app.html')
}
return resolve(get('buildDir'), 'views/app.template.html')
}
},
/**
* Enable or disable vuex store.
*
* By default it is enabled if there is a `store/` directory
* @version 2
*/
store: {
$resolve: (val, get) => val !== false &&
existsSync(join(get('srcDir'), get('dir.store'))) &&
readdirSync(join(get('srcDir'), get('dir.store')))
.find(filename => filename !== 'README.md' && filename[0] !== '.')
},
/**
* Options to pass directly to `vue-meta`.
*
* @see [documentation](https://vue-meta.nuxtjs.org/api/#plugin-options).
* @type {import('vue-meta').VueMetaOptions}
* @version 2
*/
vueMeta: null,
/**
* Set default configuration for `<head>` on every page.
*
* @see [documentation](https://vue-meta.nuxtjs.org/api/#metainfo-properties) for specifics.
* @type {import('vue-meta').MetaInfo}
* @version 2
*/
head: {
/** Each item in the array maps to a newly-created `<meta>` element, where object properties map to attributes. */
meta: [],
/** Each item in the array maps to a newly-created `<link>` element, where object properties map to attributes. */
link: [],
/** Each item in the array maps to a newly-created `<style>` element, where object properties map to attributes. */
style: [],
/** Each item in the array maps to a newly-created `<script>` element, where object properties map to attributes. */
script: []
},
/**
* Set default configuration for `<head>` on every page.
*
* @example
* ```js
* meta: {
* meta: [
* // <meta name="viewport" content="width=device-width, initial-scale=1">
* { name: 'viewport', content: 'width=device-width, initial-scale=1' }
* ],
* script: [
* // <script src="https://myawesome-lib.js"></script>
* { src: 'https://awesome-lib.js' }
* ],
* link: [
* // <link rel="stylesheet" href="https://myawesome-lib.css">
* { rel: 'stylesheet', href: 'https://awesome-lib.css' }
* ],
* // please note that this is an area that is likely to change
* style: [
* // <style type="text/css">:root { color: red }</style>
* { children: ':root { color: red }', type: 'text/css' }
* ]
* }
* ```
* @type {typeof import('../src/types/meta').MetaObject}
* @version 3
*/
meta: {
meta: [],
link: [],
style: [],
script: []
},
/**
* Configuration for the Nuxt `fetch()` hook.
* @version 2
*/
fetch: {
/** Whether to enable `fetch()` on the server. */
server: true,
/** Whether to enable `fetch()` on the client. */
client: true
},
/**
* An array of nuxt app plugins.
*
* Each plugin can be a string (which can be an absolute or relative path to a file).
* If it ends with `.client` or `.server` then it will be automatically loaded only
* in the appropriate context.
*
* It can also be an object with `src` and `mode` keys.
*
* @example
* ```js
* plugins: [
* '~/plugins/foo.client.js', // only in client side
* '~/plugins/bar.server.js', // only in server side
* '~/plugins/baz.js', // both client & server
* { src: '~/plugins/both-sides.js' },
* { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side
* { src: '~/plugins/server-only.js', mode: 'server' } // only on server side
* ]
* ```
* @type {(typeof import('../src/types/nuxt').NuxtPlugin | string)[]}
* @version 2
*/
plugins: [],
/**
* You may want to extend plugins or change their order. For this, you can pass
* a function using `extendPlugins`. It accepts an array of plugin objects and
* should return an array of plugin objects.
* @type {(plugins: Array<{ src: string, mode?: 'client' | 'server' }>) => Array<{ src: string, mode?: 'client' | 'server' }>}
* @version 2
*/
extendPlugins: null,
/**
* You can define the CSS files/modules/libraries you want to set globally
* (included in every page).
*
* Nuxt will automatically guess the file type by its extension and use the
* appropriate pre-processor. You will still need to install the required
* loader if you need to use them.
*
* @example
* ```js
* css: [
* // Load a Node.js module directly (here it's a Sass file)
* 'bulma',
* // CSS file in the project
* '@/assets/css/main.css',
* // SCSS file in the project
* '@/assets/css/main.scss'
* ]
* ```
* @type {string[]}
* @version 2
* @version 3
*/
css: {
$resolve: val => (val ?? []).map(c => c.src || c)
},
/**
* An object where each key name maps to a path to a layout .vue file.
*
* Normally there is no need to configure this directly.
* @type {Record<string, string>}
* @version 2
*/
layouts: {},
/**
* Set a custom error page layout.
*
* Normally there is no need to configure this directly.
* @type {string}
* @version 2
*/
ErrorPage: null,
/**
* Configure the Nuxt loading progress bar component that's shown between
* routes. Set to `false` to disable. You can also customize it or create
* your own component.
* @version 2
*/
loading: {
/** CSS color of the progress bar */
color: 'black',
/**
* CSS color of the progress bar when an error appended while rendering
* the route (if data or fetch sent back an error for example).
*/
failedColor: 'red',
/** Height of the progress bar (used in the style property of the progress bar). */
height: '2px',
/**
* In ms, wait for the specified time before displaying the progress bar.
* Useful for preventing the bar from flashing.
*/
throttle: 200,
/**
* In ms, the maximum duration of the progress bar, Nuxt assumes that the
* route will be rendered before 5 seconds.
*/
duration: 5000,
/** Keep animating progress bar when loading takes longer than duration. */
continuous: false,
/** Set the direction of the progress bar from right to left. */
rtl: false,
/** Set to false to remove default progress bar styles (and add your own). */
css: true
},
/**
* Show a loading spinner while the page is loading (only when `ssr: false`).
*
* Set to `false` to disable. Alternatively, you can pass a string name or an object for more
* configuration. The name can refer to an indicator from [SpinKit](https://tobiasahlin.com/spinkit/)
* or a path to an HTML template of the indicator source code (in this case, all the
* other options will be passed to the template.)
* @version 2
*/
loadingIndicator: {
$resolve: (val, get) => {
val = typeof val === 'string' ? { name: val } : val
return defu(val, {
name: 'default',
color: get('loading.color') || '#D3D3D3',
color2: '#F5F5F5',
background: (get('manifest') && get('manifest.theme_color')) || 'white',
dev: get('dev'),
loading: get('messages.loading')
})
}
},
/**
* Used to set the default properties of the page transitions.
*
* You can either pass a string (the transition name) or an object with properties to bind
* to the `<Transition>` component that will wrap your pages.
*
* @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html)
* @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions)
* @version 2
*/
pageTransition: {
$resolve: (val, get) => {
val = typeof val === 'string' ? { name: val } : val
return defu(val, {
name: 'page',
mode: 'out-in',
appear: get('render.ssr') === false || Boolean(val),
appearClass: 'appear',
appearActiveClass: 'appear-active',
appearToClass: 'appear-to'
})
}
},
/**
* Used to set the default properties of the layout transitions.
*
* You can either pass a string (the transition name) or an object with properties to bind
* to the `<Transition>` component that will wrap your layouts.
*
* @see [vue@2 documentation](https://v2.vuejs.org/v2/guide/transitions.html)
* @see [vue@3 documentation](https://vuejs.org/guide/built-ins/transition-group.html#enter-leave-transitions)
* @version 2
*/
layoutTransition: {
$resolve: val => {
val = typeof val === 'string' ? { name: val } : val
return defu(val, {
name: 'layout',
mode: 'out-in'
})
}
},
/**
* You can disable specific Nuxt features that you do not want.
* @version 2
*/
features: {
/** Set to false to disable Nuxt vuex integration */
store: true,
/** Set to false to disable layouts */
layouts: true,
/** Set to false to disable Nuxt integration with `vue-meta` and the `head` property */
meta: true,
/** Set to false to disable middleware */
middleware: true,
/** Set to false to disable transitions */
transitions: true,
/** Set to false to disable support for deprecated features and aliases */
deprecations: true,
/** Set to false to disable the Nuxt `validate()` hook */
validate: true,
/** Set to false to disable the Nuxt `asyncData()` hook */
useAsyncData: true,
/** Set to false to disable the Nuxt `fetch()` hook */
fetch: true,
/** Set to false to disable `$nuxt.isOnline` */
clientOnline: true,
/** Set to false to disable prefetching behavior in `<NuxtLink>` */
clientPrefetch: true,
/** Set to false to disable extra component aliases like `<NLink>` and `<NChild>` */
componentAliases: true,
/** Set to false to disable the `<ClientOnly>` component (see [docs](https://github.com/egoist/vue-client-only)) */
componentClientOnly: true
}
}
| packages/schema/src/config/_app.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0001790127862477675,
0.0001724511239444837,
0.00016294338274747133,
0.00017381621000822634,
0.000004215780791128054
] |
{
"id": 2,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: UseFetchOptions<ResT, Transform, PickKeys> = {}\n",
") {\n",
" if (!opts.key) {\n",
" const keys: any = { u: url }\n",
" if (opts.baseURL) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: UseFetchOptions<_ResT, Transform, PickKeys> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 21
} | sw.js
| docs/static/.gitignore | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017836650658864528,
0.00017836650658864528,
0.00017836650658864528,
0.00017836650658864528,
0
] |
{
"id": 3,
"code_window": [
" }\n",
" opts.key = generateKey(keys)\n",
" }\n",
"\n",
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)\n",
"}\n",
"\n",
"export function useLazyFetch<\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<_ResT>, opts)\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.9979425072669983,
0.2005191445350647,
0.0014957984676584601,
0.038483235985040665,
0.359502911567688
] |
{
"id": 3,
"code_window": [
" }\n",
" opts.key = generateKey(keys)\n",
" }\n",
"\n",
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)\n",
"}\n",
"\n",
"export function useLazyFetch<\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<_ResT>, opts)\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 37
} | <template>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M7.02751 0.333496C3.34571 0.333496 0.333332 3.40836 0.333332 7.16653C0.333332 10.1845 2.23002 12.7468 4.90769 13.6579C5.2424 13.7149 5.35397 13.4871 5.35397 13.3163C5.35397 13.1454 5.35397 12.7468 5.35397 12.1774C3.51307 12.576 3.12257 11.2664 3.12257 11.2664C2.84365 10.4692 2.39737 10.2414 2.39737 10.2414C1.72795 9.8428 2.39737 9.8428 2.39737 9.8428C3.06679 9.89974 3.4015 10.5261 3.4015 10.5261C4.01513 11.5511 4.96347 11.2664 5.35397 11.0955C5.40975 10.64 5.57711 10.3553 5.80024 10.1845C4.29405 10.0136 2.73208 9.44421 2.73208 6.82488C2.73208 6.08463 3.011 5.45827 3.4015 5.00274C3.4015 4.77497 3.12257 4.09166 3.51307 3.18059C3.51307 3.18059 4.07091 3.00977 5.35397 3.8639C5.91181 3.69307 6.46966 3.63613 7.02751 3.63613C7.58536 3.63613 8.14321 3.69307 8.70105 3.8639C9.98411 2.95283 10.542 3.18059 10.542 3.18059C10.9324 4.14861 10.6535 4.83191 10.5977 5.00274C11.044 5.45827 11.2672 6.08463 11.2672 6.82488C11.2672 9.44421 9.70518 10.0136 8.19899 10.1845C8.42213 10.4122 8.64527 10.8108 8.64527 11.4372C8.64527 12.3482 8.64527 13.0885 8.64527 13.3163C8.64527 13.4871 8.75684 13.7149 9.09155 13.6579C11.7692 12.7468 13.6659 10.1845 13.6659 7.16653C13.7217 3.40836 10.7093 0.333496 7.02751 0.333496Z"
fill="currentColor"
/>
</svg>
</template>
| docs/components/atoms/icons/IconGitHub.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.000756441499106586,
0.0004667702014558017,
0.00017709890380501747,
0.0004667702014558017,
0.00028967129765078425
] |
{
"id": 3,
"code_window": [
" }\n",
" opts.key = generateKey(keys)\n",
" }\n",
"\n",
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)\n",
"}\n",
"\n",
"export function useLazyFetch<\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<_ResT>, opts)\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 37
} |
<template>
<svg width="1em" height="1em" viewBox="0 0 24 24"><path d="M2.6 10.59L8.38 4.8l1.69 1.7c-.24.85.15 1.78.93 2.23v5.54c-.6.34-1 .99-1 1.73a2 2 0 0 0 2 2a2 2 0 0 0 2-2c0-.74-.4-1.39-1-1.73V9.41l2.07 2.09c-.07.15-.07.32-.07.5a2 2 0 0 0 2 2a2 2 0 0 0 2-2a2 2 0 0 0-2-2c-.18 0-.35 0-.5.07L13.93 7.5a1.98 1.98 0 0 0-1.15-2.34c-.43-.16-.88-.2-1.28-.09L9.8 3.38l.79-.78c.78-.79 2.04-.79 2.82 0l7.99 7.99c.79.78.79 2.04 0 2.82l-7.99 7.99c-.78.79-2.04.79-2.82 0L2.6 13.41c-.79-.78-.79-2.04 0-2.82z" fill="currentColor" /></svg>
</template>
| docs/components/atoms/icons/IconGit.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.000163991455337964,
0.000163991455337964,
0.000163991455337964,
0.000163991455337964,
0
] |
{
"id": 3,
"code_window": [
" }\n",
" opts.key = generateKey(keys)\n",
" }\n",
"\n",
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)\n",
"}\n",
"\n",
"export function useLazyFetch<\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<_ResT>, opts)\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 37
} | <template>
<svg
width="160"
height="160"
viewBox="0 0 160 160"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="text-black dark:text-white"
>
<path d="M80.0761 12L159.152 148.965H1L80.0761 12Z" fill="currentColor" />
</svg>
</template>
| docs/components/atoms/logo/LogoVercel.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0001758592261467129,
0.0001751459640217945,
0.0001744327018968761,
0.0001751459640217945,
7.132621249184012e-7
] |
{
"id": 4,
"code_window": [
"}\n",
"\n",
"export function useLazyFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 41
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.99894779920578,
0.6616466641426086,
0.00017007399583235383,
0.9852777719497681,
0.467073917388916
] |
{
"id": 4,
"code_window": [
"}\n",
"\n",
"export function useLazyFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 41
} | {
"name": "example-use-cookie",
"private": true,
"scripts": {
"build": "nuxi build",
"dev": "nuxi dev",
"start": "nuxi preview"
},
"devDependencies": {
"@nuxt/ui": "npm:@nuxt/ui-edge@latest",
"nuxt3": "latest"
}
}
| examples/use-cookie/package.json | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017359742196276784,
0.00017235917039215565,
0.00017112093337345868,
0.00017235917039215565,
0.000001238244294654578
] |
{
"id": 4,
"code_window": [
"}\n",
"\n",
"export function useLazyFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 41
} | #!/usr/bin/env node
require('../packages/nuxi/bin/nuxi')
| scripts/nu | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017025021952576935,
0.00017025021952576935,
0.00017025021952576935,
0.00017025021952576935,
0
] |
{
"id": 4,
"code_window": [
"}\n",
"\n",
"export function useLazyFetch<\n",
" ReqT extends string = string,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" ResT = void,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "add",
"edit_start_line_idx": 41
} | {
"name": "example-module-extend-pages",
"private": true,
"scripts": {
"build": "nuxi build",
"dev": "nuxi dev",
"start": "nuxi preview"
},
"devDependencies": {
"@nuxt/ui": "npm:@nuxt/ui-edge@latest",
"nuxt3": "latest"
}
}
| examples/module-extend-pages/package.json | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017359742196276784,
0.00017165427561849356,
0.00016971112927421927,
0.00017165427561849356,
0.0000019431463442742825
] |
{
"id": 5,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.9979084730148315,
0.35500362515449524,
0.0001715545222396031,
0.06717932969331741,
0.45668190717697144
] |
{
"id": 5,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import type { } from '@nuxt/nitro'
export * from './dist/index'
export * from './dist/app/types/index'
| packages/nuxt3/types.d.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017280076281167567,
0.00017280076281167567,
0.00017280076281167567,
0.00017280076281167567,
0
] |
{
"id": 5,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 42
} | <template>
<div>
<Head>
<Title>Basic fixture</Title>
</Head>
<h1>Hello Vue 3</h1>
<div>Config: {{ $config.testConfig }}</div>
</div>
</template>
<script setup>
const $config = useRuntimeConfig()
</script>
| test/fixtures/basic/pages/index.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017557773389853537,
0.00017532346828375012,
0.00017506920266896486,
0.00017532346828375012,
2.54265614785254e-7
] |
{
"id": 5,
"code_window": [
" ReqT extends string = string,\n",
" ResT = FetchResult<ReqT>,\n",
" Transform extends (res: ResT) => any = (res: ResT) => ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" _ResT = ResT extends void ? FetchResult<ReqT> : ResT,\n",
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 42
} | export * from './core/nuxt'
export * from './core/builder'
| packages/nuxt3/src/index.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017468487203586847,
0.00017468487203586847,
0.00017468487203586847,
0.00017468487203586847,
0
] |
{
"id": 6,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}\n",
") {\n",
" return useFetch(url, { ...opts, lazy: true })\n",
"}\n",
"\n",
"function generateKey (keys) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 47
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.999128520488739,
0.3380368649959564,
0.00207176199182868,
0.013531085103750229,
0.4667247533798218
] |
{
"id": 6,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}\n",
") {\n",
" return useFetch(url, { ...opts, lazy: true })\n",
"}\n",
"\n",
"function generateKey (keys) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 47
} | import mri from 'mri'
import { red } from 'colorette'
import consola from 'consola'
import { checkEngines } from './utils/engines'
import { commands, Command, NuxtCommand } from './commands'
import { showHelp } from './utils/help'
import { showBanner } from './utils/banner'
async function _main () {
const _argv = process.argv.slice(2)
const args = mri(_argv, {
boolean: [
'no-clear'
]
})
// @ts-ignore
const command = args._.shift() || 'usage'
showBanner(command === 'dev' && args.clear !== false)
if (!(command in commands)) {
console.log('\n' + red('Invalid command ' + command))
await commands.usage().then(r => r.invoke())
process.exit(1)
}
// Check Node.js version in background
setTimeout(() => { checkEngines() }, 1000)
try {
// @ts-ignore default.default is hotfix for #621
const cmd = await commands[command as Command]() as NuxtCommand
if (args.h || args.help) {
showHelp(cmd.meta)
} else {
await cmd.invoke(args)
}
} catch (err) {
onFatalError(err)
}
}
function onFatalError (err: unknown) {
consola.error(err)
process.exit(1)
}
// Wrap all console logs with consola for better DX
consola.wrapConsole()
process.on('unhandledRejection', err => consola.error('[unhandledRejection]', err))
process.on('uncaughtException', err => consola.error('[uncaughtException]', err))
export function main () {
_main().catch(onFatalError)
}
| packages/nuxi/src/index.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017784720694180578,
0.00017571110220160335,
0.00016987952403724194,
0.00017710047541186213,
0.000002839884245986468
] |
{
"id": 6,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}\n",
") {\n",
" return useFetch(url, { ...opts, lazy: true })\n",
"}\n",
"\n",
"function generateKey (keys) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 47
} | export * from './composables'
export type { MetaObject } from '@nuxt/schema'
| packages/nuxt3/src/meta/runtime/index.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00016467510431539267,
0.00016467510431539267,
0.00016467510431539267,
0.00016467510431539267,
0
] |
{
"id": 6,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" url: ReqT,\n",
" opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}\n",
") {\n",
" return useFetch(url, { ...opts, lazy: true })\n",
"}\n",
"\n",
"function generateKey (keys) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" opts: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'> = {}\n"
],
"file_path": "packages/nuxt3/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 47
} | import { getCurrentInstance, onBeforeUnmount, isRef, watch, reactive, toRef, isReactive, Ref, set } from '@vue/composition-api'
import type { CombinedVueInstance } from 'vue/types/vue'
import type { MetaInfo } from 'vue-meta'
import type VueRouter from 'vue-router'
import type { Location, Route } from 'vue-router'
import type { RuntimeConfig } from '@nuxt/schema'
import defu from 'defu'
import { useNuxtApp } from './app'
export { useLazyAsyncData } from './asyncData'
export { useLazyFetch } from './fetch'
export { useCookie } from './cookie'
export { useRequestHeaders } from './ssr'
export * from '@vue/composition-api'
const mock = () => () => { throw new Error('not implemented') }
export const useAsyncData = mock()
export const useFetch = mock()
export const useHydration = mock()
// Runtime config helper
export const useRuntimeConfig = () => {
const nuxtApp = useNuxtApp()
if (!nuxtApp.$config) {
nuxtApp.$config = reactive(nuxtApp.nuxt2Context.app.$config)
}
return nuxtApp.$config as RuntimeConfig
}
// Auto-import equivalents for `vue-router`
export const useRouter = () => {
return useNuxtApp()?.nuxt2Context.app.router as VueRouter
}
// This provides an equivalent interface to `vue-router` (unlike legacy implementation)
export const useRoute = () => {
const nuxtApp = useNuxtApp()
if (!nuxtApp._route) {
Object.defineProperty(nuxtApp, '__route', {
get: () => nuxtApp.nuxt2Context.app.context.route
})
nuxtApp._route = reactive(nuxtApp.__route)
const router = useRouter()
router.afterEach(route => Object.assign(nuxtApp._route, route))
}
return nuxtApp._route as Route
}
// payload.state is used for vuex by nuxt 2
export const useState = <T>(key: string, init?: (() => T)): Ref<T> => {
const nuxtApp = useNuxtApp()
if (!nuxtApp.payload.useState) {
nuxtApp.payload.useState = {}
}
if (!isReactive(nuxtApp.payload.useState)) {
nuxtApp.payload.useState = reactive(nuxtApp.payload.useState)
}
// see @vuejs/composition-api reactivity tracking on a reactive object with set
if (!(key in nuxtApp.payload.useState)) {
set(nuxtApp.payload.useState, key, undefined)
}
const state = toRef(nuxtApp.payload.useState, key)
if (state.value === undefined && init) {
state.value = init()
}
return state
}
type Reffed<T extends Record<string, any>> = {
[P in keyof T]: T[P] extends Array<infer A> ? Ref<Array<Reffed<A>>> | Array<Reffed<A>> : T[P] extends Record<string, any> ? Reffed<T[P]> | Ref<Reffed<T[P]>> : T[P] | Ref<T[P]>
}
function unwrap (value: any): Record<string, any> {
if (!value || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number') { return value }
if (Array.isArray(value)) { return value.map(i => unwrap(i)) }
if (isRef(value)) { return unwrap(value.value) }
if (typeof value === 'object') {
return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, unwrap(value)]))
}
return value
}
type AugmentedComponent = CombinedVueInstance<Vue, object, object, object, Record<never, any>> & {
_vueMeta?: boolean
$metaInfo?: MetaInfo
}
/** internal */
function metaInfoFromOptions (metaOptions: Reffed<MetaInfo> | (() => Reffed<MetaInfo>)) {
return metaOptions instanceof Function ? metaOptions : () => metaOptions
}
export const useNuxt2Meta = (metaOptions: Reffed<MetaInfo> | (() => Reffed<MetaInfo>)) => {
let vm: AugmentedComponent | null = null
try {
vm = getCurrentInstance()!.proxy as AugmentedComponent
const meta = vm.$meta()
const $root = vm.$root
if (!vm._vueMeta) {
vm._vueMeta = true
let parent = vm.$parent as AugmentedComponent
while (parent && parent !== $root) {
if (parent._vueMeta === undefined) {
parent._vueMeta = false
}
parent = parent.$parent
}
}
// @ts-ignore
vm.$options.head = vm.$options.head || {}
const unwatch = watch(metaInfoFromOptions(metaOptions), (metaInfo: MetaInfo) => {
vm.$metaInfo = {
...vm.$metaInfo || {},
...unwrap(metaInfo)
}
if (process.client) {
meta.refresh()
}
}, { immediate: true, deep: true })
onBeforeUnmount(unwatch)
} catch {
const app = (useNuxtApp().nuxt2Context as any).app
if (typeof app.head === 'function') {
const originalHead = app.head
app.head = function () {
const head = originalHead.call(this) || {}
return defu(unwrap(metaInfoFromOptions(metaOptions)()), head)
}
} else {
app.head = defu(unwrap(metaInfoFromOptions(metaOptions)()), app.head)
}
}
}
export interface AddRouteMiddlewareOptions {
global?: boolean
}
/** internal */
function convertToLegacyMiddleware (middleware) {
return async (ctx: any) => {
const result = await middleware(ctx.route, ctx.from)
if (result instanceof Error) {
return ctx.error(result)
}
if (result) {
return ctx.redirect(result)
}
return result
}
}
export const addRouteMiddleware = (name: string, middleware: any, options: AddRouteMiddlewareOptions = {}) => {
const nuxtApp = useNuxtApp()
if (options.global) {
nuxtApp._middleware.global.push(middleware)
} else {
nuxtApp._middleware.named[name] = convertToLegacyMiddleware(middleware)
}
}
const isProcessingMiddleware = () => {
try {
if (useNuxtApp()._processingMiddleware) {
return true
}
} catch {
// Within an async middleware
return true
}
return false
}
export const navigateTo = (to: Route) => {
if (isProcessingMiddleware()) {
return to
}
const router: VueRouter = process.server ? useRouter() : (window as any).$nuxt.router
return router.push(to)
}
/** This will abort navigation within a Nuxt route middleware handler. */
export const abortNavigation = (err?: Error | string) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
}
if (err) {
throw err instanceof Error ? err : new Error(err)
}
return false
}
type RouteMiddlewareReturn = void | Error | string | Location | boolean
export interface RouteMiddleware {
(to: Route, from: Route): RouteMiddlewareReturn | Promise<RouteMiddlewareReturn>
}
export const defineNuxtRouteMiddleware = (middleware: RouteMiddleware) => middleware
| packages/bridge/src/runtime/composables.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0014405215624719858,
0.00024013010261114687,
0.00016496930038556457,
0.00017495706561021507,
0.00026961619732901454
] |
{
"id": 7,
"code_window": [
"import { useRouter } from '#imports'\n",
"import { isVue3 } from '#app'\n",
"\n",
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface TestResponse { message: string }\n",
"\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 9
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0027258277405053377,
0.0005964317242614925,
0.00016782771854195744,
0.000170693572727032,
0.0009522964246571064
] |
{
"id": 7,
"code_window": [
"import { useRouter } from '#imports'\n",
"import { isVue3 } from '#app'\n",
"\n",
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface TestResponse { message: string }\n",
"\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 9
} | import type { Nuxt, NuxtModule } from '@nuxt/schema'
import { useNuxt } from '../context'
import { resolveModule, requireModule, importModule } from '../internal/cjs'
import { resolveAlias } from '../resolve'
import { useModuleContainer } from './container'
/** Installs a module on a Nuxt instance. */
export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) {
const nuxt = useNuxt()
const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions)
// Call module
await nuxtModule.call(useModuleContainer(), inlineOptions, nuxt)
nuxt.options._installedModules = nuxt.options._installedModules || []
nuxt.options._installedModules.push({
meta: await nuxtModule.getMeta?.(),
entryPath: typeof moduleToInstall === 'string' ? resolveAlias(moduleToInstall) : undefined
})
}
// --- Internal ---
async function normalizeModule (nuxtModule: string | NuxtModule, inlineOptions?: any) {
const nuxt = useNuxt()
// Detect if `installModule` used with older signuture (nuxt, nuxtModule)
// TODO: Remove in RC
// @ts-ignore
if (nuxtModule?._version || nuxtModule?.version || nuxtModule?.constructor?.version || '') {
[nuxtModule, inlineOptions] = [inlineOptions, {}]
console.warn(new Error('`installModule` is being called with old signature!'))
}
// Import if input is string
if (typeof nuxtModule === 'string') {
const _src = resolveModule(resolveAlias(nuxtModule), { paths: nuxt.options.modulesDir })
// TODO: also check with type: 'module' in closest `package.json`
const isESM = _src.endsWith('.mjs')
nuxtModule = isESM ? await importModule(_src) : requireModule(_src)
}
// Throw error if input is not a function
if (typeof nuxtModule !== 'function') {
throw new TypeError('Nuxt module should be a function: ' + nuxtModule)
}
return { nuxtModule, inlineOptions } as { nuxtModule: NuxtModule<any>, inlineOptions: undefined | Record<string, any> }
}
| packages/kit/src/module/install.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017495806969236583,
0.0001740826410241425,
0.0001727737399050966,
0.0001741323940223083,
8.213699516090855e-7
] |
{
"id": 7,
"code_window": [
"import { useRouter } from '#imports'\n",
"import { isVue3 } from '#app'\n",
"\n",
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface TestResponse { message: string }\n",
"\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 9
} | ---
icon: IconDirectory
title: server
head.title: Server directory
---
# Server directory
The server directory is used to create any backend logic for your Nuxt application. It supports HMR and powerful features.
The `server/` directory contains API endpoints and server middleware for your project.
## API Routes
Nuxt will automatically read in any files in the `~/server/api` directory to create API endpoints.
Each file should export a default function that handles API requests. It can return a promise or JSON data directly (or use `res.end()`).
### Examples
#### Hello world
```js [server/api/hello.ts]
export default (req, res) => 'Hello World'
```
See the result on <http://localhost:3000/api/hello>.
#### Async function
```js [server/api/async.ts]
export default async (req, res) => {
await someAsyncFunction()
return {
someData: true
}
}
```
**Example:** Using Node.js style
```ts [server/api/node.ts]
import type { IncomingMessage, ServerResponse } from 'http'
export default async (req: IncomingMessage, res: ServerResponse) => {
res.statusCode = 200
res.end('Works!')
}
```
#### Accessing req data
```js
import { useBody, useCookies, useQuery } from 'h3'
export default async (req, res) => {
const query = await useQuery(req)
const body = await useBody(req) // only for POST request
const cookies = useCookies(req)
return { query, body, cookies }
}
```
Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions).
## Server Middleware
Nuxt will automatically read in any files in the `~/server/middleware` to create server middleware for your project.
These files will be run on every request, unlike [API routes](#api-routes) that are mapped to their own routes. This is typically so you can add a common header to all responses, log responses or modify the incoming request object for later use in the request chain.
Each file should export a default function that will handle a request.
```js
export default async (req, res) => {
req.someValue = true
}
```
There is nothing different about the `req`/`res` objects, so typing them is straightforward.
```ts
import type { IncomingMessage, ServerResponse } from 'http'
export default async (req: IncomingMessage, res: ServerResponse) => {
req.someValue = true
}
```
More information about custom middleware can be found in the documentation for [nuxt.config.js](/docs/directory-structure/nuxt.config#servermiddleware)
| docs/content/3.docs/2.directory-structure/13.server.md | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0001816753065213561,
0.00016944858361966908,
0.0001607947633601725,
0.00017017356003634632,
0.0000056504768508602865
] |
{
"id": 7,
"code_window": [
"import { useRouter } from '#imports'\n",
"import { isVue3 } from '#app'\n",
"\n",
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"interface TestResponse { message: string }\n",
"\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 9
} | import satisfies from 'semver/functions/satisfies.js' // npm/node-semver#381
import type { Nuxt, NuxtCompatibility, NuxtCompatibilityIssues } from '@nuxt/schema'
import { useNuxt } from './context'
/**
* Check version constraints and return incompatibility issues as an array
*/
export async function checkNuxtCompatibility (constraints: NuxtCompatibility, nuxt: Nuxt = useNuxt()): Promise<NuxtCompatibilityIssues> {
const issues: NuxtCompatibilityIssues = []
// Nuxt version check
if (constraints.nuxt) {
const nuxtVersion = getNuxtVersion(nuxt)
const nuxtSemanticVersion = nuxtVersion.split('-').shift()
if (!satisfies(nuxtSemanticVersion, constraints.nuxt)) {
issues.push({
name: 'nuxt',
message: `Nuxt version \`${constraints.nuxt}\` is required but currently using \`${nuxtVersion}\``
})
}
}
// Bridge compatibility check
if (isNuxt2(nuxt)) {
const bridgeRequirement = constraints?.bridge
const hasBridge = !!(nuxt.options as any).bridge
if (bridgeRequirement === true && !hasBridge) {
issues.push({
name: 'bridge',
message: 'Nuxt bridge is required'
})
} else if (bridgeRequirement === false && hasBridge) {
issues.push({
name: 'bridge',
message: 'Nuxt bridge is not supported'
})
}
}
// Allow extending compatibility checks
await nuxt.callHook('kit:compatibility', constraints, issues)
// Issues formatter
issues.toString = () =>
issues.map(issue => ` - [${issue.name}] ${issue.message}`).join('\n')
return issues
}
/**
* Check version constraints and throw a detailed error if has any, otherwise returns true
*/
export async function assertNuxtCompatibility (constraints: NuxtCompatibility, nuxt: Nuxt = useNuxt()): Promise<true> {
const issues = await checkNuxtCompatibility(constraints, nuxt)
if (issues.length) {
throw new Error('Nuxt compatibility issues found:\n' + issues.toString())
}
return true
}
/**
* Check version constraints and return true if passed, otherwise returns false
*/
export async function hasNuxtCompatibility (constraints: NuxtCompatibility, nuxt: Nuxt = useNuxt()): Promise<boolean> {
const issues = await checkNuxtCompatibility(constraints, nuxt)
return !issues.length
}
/**
* Check if current nuxt instance is version 2 legacy
*/
export function isNuxt2 (nuxt: Nuxt = useNuxt()) {
return getNuxtVersion(nuxt).startsWith('2.')
}
/**
* Check if current nuxt instance is version 3
*/
export function isNuxt3 (nuxt: Nuxt = useNuxt()) {
return getNuxtVersion(nuxt).startsWith('3.')
}
/**
* Get nuxt version
*/
export function getNuxtVersion (nuxt: Nuxt | any = useNuxt() /* TODO: LegacyNuxt */) {
const version = (nuxt?._version || nuxt?.version || nuxt?.constructor?.version || '').replace(/^v/g, '')
if (!version) {
throw new Error('Cannot determine nuxt version! Is currect instance passed?')
}
return version
}
| packages/kit/src/compatibility.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017642656166572124,
0.0001729819632600993,
0.00016330360085703433,
0.0001742192544043064,
0.000003883812041749479
] |
{
"id": 8,
"code_window": [
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf($fetch<TestResponse>('/test')).toMatchTypeOf<Promise<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 14
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0016801367746666074,
0.0004785190976690501,
0.0001656666718190536,
0.0001692682271823287,
0.0005525395972654223
] |
{
"id": 8,
"code_window": [
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf($fetch<TestResponse>('/test')).toMatchTypeOf<Promise<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 14
} | import { defineBuildConfig } from 'unbuild'
export default defineBuildConfig({
declaration: true,
entries: [
'src/module',
{ input: 'src/runtime/', outDir: 'dist/runtime', format: 'esm', declaration: true }
],
externals: [
'webpack',
'vite',
'vue-meta'
]
})
| packages/bridge/build.config.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017825124086812139,
0.00017580739222466946,
0.0001733635290293023,
0.00017580739222466946,
0.0000024438559194095433
] |
{
"id": 8,
"code_window": [
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf($fetch<TestResponse>('/test')).toMatchTypeOf<Promise<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 14
} | import { promises as fsp } from 'fs'
import { join, resolve } from 'pathe'
import { createApp, lazyHandle } from 'h3'
import type { PluginVisualizerOptions } from 'rollup-plugin-visualizer'
import { createServer } from '../utils/server'
import { writeTypes } from '../utils/prepare'
import { loadKit } from '../utils/kit'
import { clearDir } from '../utils/fs'
import { defineNuxtCommand } from './index'
export default defineNuxtCommand({
meta: {
name: 'analyze',
usage: 'npx nuxi analyze [rootDir]',
description: 'Build nuxt and analyze production bundle (experimental)'
},
async invoke (args) {
process.env.NODE_ENV = process.env.NODE_ENV || 'production'
const rootDir = resolve(args._[0] || '.')
const statsDir = join(rootDir, '.nuxt/stats')
const { loadNuxt, buildNuxt } = await loadKit(rootDir)
const analyzeOptions: PluginVisualizerOptions = {
template: 'treemap',
projectRoot: rootDir,
filename: join(statsDir, '{name}.html')
}
const nuxt = await loadNuxt({
rootDir,
config: {
build: {
// @ts-ignore
analyze: analyzeOptions
}
}
})
await clearDir(nuxt.options.buildDir)
await writeTypes(nuxt)
await buildNuxt(nuxt)
const app = createApp()
const server = createServer(app)
const serveFile = (filePath: string) => lazyHandle(async () => {
const contents = await fsp.readFile(filePath, 'utf-8')
return (_req, res) => { res.end(contents) }
})
console.warn('Do not deploy analyze results! Use `nuxi build` before deploying.')
console.info('Starting stats server...')
app.use('/client', serveFile(join(statsDir, 'client.html')))
app.use('/nitro', serveFile(join(statsDir, 'nitro.html')))
app.use(() => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Nuxt Bundle Stats (experimental)</title>
</head>
<h1>Nuxt Bundle Stats (experimental)</h1>
<ul>
<li>
<a href="/nitro">Nitro server bundle stats</a>
</li>
<li>
<a href="/client">Client bundle stats</a>
</li>
</ul>
</html>`)
await server.listen()
}
})
| packages/nuxi/src/commands/analyze.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017783870862331241,
0.00017647907952778041,
0.00017475200002081692,
0.00017642497550696135,
0.0000011697226227624924
] |
{
"id": 8,
"code_window": [
"describe('API routes', () => {\n",
" it('generates types for routes', () => {\n",
" expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()\n",
" expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()\n",
" expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf($fetch<TestResponse>('/test')).toMatchTypeOf<Promise<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 14
} | {
"extends": "./.nuxt/tsconfig.json"
}
| examples/use-meta/tsconfig.json | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017396561452187598,
0.00017396561452187598,
0.00017396561452187598,
0.00017396561452187598,
0
] |
{
"id": 9,
"code_window": [
" expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 21
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import { useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt3/src'
import { useRouter } from '#imports'
import { isVue3 } from '#app'
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toMatchTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toMatchTypeOf<Promise<{ foo:string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toMatchTypeOf<Promise<unknown>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toMatchTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toMatchTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognises named middleware', () => {
definePageMeta({ middleware: 'test-middleware' })
definePageMeta({ middleware: 'pascal-case' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
})
describe('layouts', () => {
it('recognises named layouts', () => {
definePageMeta({ layout: 'test-layout' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
| test/fixtures/basic/tests/types.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.9915221929550171,
0.27907514572143555,
0.00016430228424724191,
0.00017278561426792294,
0.44106245040893555
] |
{
"id": 9,
"code_window": [
" expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 21
} | # Custom build preset (advanced)
Get full control of Nuxt Nitro output to deploy on any kind of hosting platform.
::list{type=info}
- Allows full customization
- This is an advanced usage pattern
::
::alert{icon=IconPresets}
Back to [presets list](/docs/deployment/presets).
::
## Setup
You can create your own custom-built preset. See [the provided presets](https://github.com/nuxt/framework/blob/main/packages/nitro/src/presets) for examples.
### Inline preset definition
You can define everything that a custom preset would configure directly in the Nitro options:
```ts [nuxt.config.js|ts]
export default {
nitro: {
// preset options
}
}
```
### Reusable preset
You can also define a preset in a separate file (or publish as a separate npm package).
```ts [my-preset/index.ts]
import type { NitroPreset } from '@nuxt/nitro'
const myPreset: NitroPreset = {
// Your custom configuration
}
export default myPreset
```
Then in your `nuxt.config` you can specify that Nitro should use your custom preset:
```ts [nuxt.config.js|ts]
import { resolve } from 'path'
export default {
nitro: {
preset: resolve(__dirname, 'my-preset')
}
}
```
| docs/content/3.docs/3.deployment/99.presets/custom.md | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017428604769520462,
0.00016954018792603165,
0.00016628911544103175,
0.0001688461343292147,
0.0000029195985007390846
] |
{
"id": 9,
"code_window": [
" expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 21
} | import type { IncomingMessage, ServerResponse } from 'http'
import type { App } from 'vue'
import type { Component } from '@vue/runtime-core'
import mockContext from 'unenv/runtime/mock/proxy'
import { NuxtApp, useRuntimeConfig } from '../nuxt'
type Route = any
type Store = any
export type LegacyApp = App<Element> & {
$root: LegacyApp
constructor: LegacyApp
}
export interface LegacyContext {
// -> $config
$config: Record<string, any>
env: Record<string, any>
// -> app
app: Component
// -> unsupported
isClient: boolean
isServer: boolean
isStatic: boolean
// TODO: needs app implementation
isDev: boolean
isHMR: boolean
// -> unsupported
store: Store
// vue-router integration
route: Route
params: Route['params']
query: Route['query']
base: string /** TODO: */
payload: any /** TODO: */
from: Route /** TODO: */
// -> nuxt.payload.data
nuxtState: Record<string, any>
// TODO: needs app implementation
beforeNuxtRender (fn: (params: { Components: any, nuxtState: Record<string, any> }) => void): void
beforeSerialize (fn: (nuxtState: Record<string, any>) => void): void
// TODO: needs app implementation
enablePreview?: (previewData?: Record<string, any>) => void
$preview?: Record<string, any>
// -> ssrContext.{req,res}
req: IncomingMessage
res: ServerResponse
/** TODO: */
next?: (err?: any) => any
error (params: any): void
redirect (status: number, path: string, query?: Route['query']): void
redirect (path: string, query?: Route['query']): void
redirect (location: Location): void
redirect (status: number, location: Location): void
ssrContext?: {
// -> ssrContext.{req,res,url,runtimeConfig}
req: LegacyContext['req']
res: LegacyContext['res']
url: string
runtimeConfig: {
public: Record<string, any>
private: Record<string, any>
}
// -> unsupported
target: string
spa?: boolean
modern: boolean
fetchCounters: Record<string, number>
// TODO:
next: LegacyContext['next']
redirected: boolean
beforeRenderFns: Array<() => any>
beforeSerializeFns: Array<() => any>
// -> nuxt.payload
nuxt: {
serverRendered: boolean
// TODO:
layout: string
data: Array<Record<string, any>>
fetch: Array<Record<string, any>>
error: any
state: Array<Record<string, any>>
routePath: string
config: Record<string, any>
}
}
}
function mock (warning: string) {
console.warn(warning)
return mockContext
}
const unsupported = new Set<keyof LegacyContext | keyof LegacyContext['ssrContext']>([
'store',
'spa',
'fetchCounters'
])
const todo = new Set<keyof LegacyContext | keyof LegacyContext['ssrContext']>([
'isHMR',
// Routing handlers - needs implementation or deprecation
'base',
'payload',
'from',
'next',
'error',
'redirect',
'redirected',
// needs app implementation
'enablePreview',
'$preview',
'beforeNuxtRender',
'beforeSerialize'
])
const serverProperties = new Set<keyof LegacyContext['ssrContext'] | keyof LegacyContext>([
'req',
'res',
'ssrContext'
])
const routerKeys: Array<keyof LegacyContext | keyof LegacyContext['ssrContext']> = ['route', 'params', 'query']
const staticFlags = {
isClient: process.client,
isServer: process.server,
isDev: process.dev,
isStatic: undefined,
target: 'server',
modern: false
}
export const legacyPlugin = (nuxtApp: NuxtApp) => {
nuxtApp._legacyContext = new Proxy(nuxtApp, {
get (nuxt, p: keyof LegacyContext | keyof LegacyContext['ssrContext']) {
// Unsupported keys
if (unsupported.has(p)) {
return mock(`Accessing ${p} is not supported in Nuxt 3.`)
}
if (todo.has(p)) {
return mock(`Accessing ${p} is not yet supported in Nuxt 3.`)
}
// vue-router implementation
if (routerKeys.includes(p)) {
if (!('$router' in nuxtApp)) {
return mock('vue-router is not being used in this project.')
}
switch (p) {
case 'route':
return nuxt.$router.currentRoute.value
case 'params':
case 'query':
return nuxt.$router.currentRoute.value[p]
}
}
if (p === '$config' || p === 'env') {
return useRuntimeConfig()
}
if (p in staticFlags) {
return staticFlags[p]
}
if (process.client && serverProperties.has(p)) {
return undefined
}
if (p === 'ssrContext') {
return nuxt._legacyContext
}
if (nuxt.ssrContext && p in nuxt.ssrContext) {
return nuxt.ssrContext[p]
}
if (p === 'nuxt') {
return nuxt.payload
}
if (p === 'nuxtState') {
return nuxt.payload.data
}
if (p in nuxtApp.vueApp) {
return nuxtApp.vueApp[p]
}
if (p in nuxtApp) {
return nuxtApp[p]
}
return mock(`Accessing ${p} is not supported in Nuxt3.`)
}
}) as unknown as LegacyContext
if (process.client) {
nuxtApp.hook('app:created', () => {
const legacyApp = { ...nuxtApp.vueApp } as LegacyApp
legacyApp.$root = legacyApp
// @ts-ignore
// TODO: https://github.com/nuxt/framework/issues/244
legacyApp.constructor = legacyApp
window[`$${nuxtApp.globalName}`] = legacyApp
})
}
}
| packages/nuxt3/src/app/compat/legacy-app.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0001745448389556259,
0.0001701059372862801,
0.0001630795595701784,
0.0001704044989310205,
0.0000022138244730740553
] |
{
"id": 9,
"code_window": [
" expectTypeOf(useFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toMatchTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 21
} | <template>
<div>
Other layout
<slot />
</div>
</template>
| examples/with-layouts/layouts/other.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0001693899102974683,
0.0001693899102974683,
0.0001693899102974683,
0.0001693899102974683,
0
] |
{
"id": 10,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 25
} | import type { FetchOptions, FetchRequest } from 'ohmyfetch'
import type { TypedInternalResponse } from '@nuxt/nitro'
import { murmurHashV3 } from 'murmurhash-es'
import type { AsyncDataOptions, _Transform, KeyOfRes } from './asyncData'
import { useAsyncData } from './asyncData'
export type FetchResult<ReqT extends FetchRequest> = TypedInternalResponse<ReqT, unknown>
export type UseFetchOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> = AsyncDataOptions<DataT, Transform, PickKeys> & FetchOptions & { key?: string }
export function useFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: UseFetchOptions<ResT, Transform, PickKeys> = {}
) {
if (!opts.key) {
const keys: any = { u: url }
if (opts.baseURL) {
keys.b = opts.baseURL
}
if (opts.method && opts.method.toLowerCase() !== 'get') {
keys.m = opts.method.toLowerCase()
}
if (opts.params) {
keys.p = opts.params
}
opts.key = generateKey(keys)
}
return useAsyncData(opts.key, () => $fetch(url, opts) as Promise<ResT>, opts)
}
export function useLazyFetch<
ReqT extends string = string,
ResT = FetchResult<ReqT>,
Transform extends (res: ResT) => any = (res: ResT) => ResT,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
url: ReqT,
opts: Omit<UseFetchOptions<ResT, Transform, PickKeys>, 'lazy'> = {}
) {
return useFetch(url, { ...opts, lazy: true })
}
function generateKey (keys) {
return '$f' + murmurHashV3(JSON.stringify(keys))
}
| packages/nuxt3/src/app/composables/fetch.ts | 1 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0023825783282518387,
0.0008943516877479851,
0.00017169526836369187,
0.00017566743190400302,
0.00101845886092633
] |
{
"id": 10,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 25
} | import { existsSync, promises as fsp } from 'fs'
import { resolve } from 'pathe'
import consola from 'consola'
import { joinURL } from 'ufo'
import { genString } from 'knitwork'
import { extendPreset, prettyPath } from '../utils'
import { NitroPreset, NitroContext, NitroInput } from '../context'
import { worker } from './worker'
export const browser: NitroPreset = extendPreset(worker, (input: NitroInput) => {
// TODO: Join base at runtime
const baseURL = input._nuxt.baseURL
const script = `<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register(${genString(joinURL(baseURL, 'sw.js'))});
});
}
</script>`
// TEMP FIX
const html = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="prefetch" href="${joinURL(baseURL, 'sw.js')}">
<link rel="prefetch" href="${joinURL(baseURL, '_server/index.mjs')}">
<script>
async function register () {
const registration = await navigator.serviceWorker.register(${genString(joinURL(baseURL, 'sw.js'))})
await navigator.serviceWorker.ready
registration.active.addEventListener('statechange', (event) => {
if (event.target.state === 'activated') {
window.location.reload()
}
})
}
if (location.hostname !== 'localhost' && location.protocol === 'http:') {
location.replace(location.href.replace('http://', 'https://'))
} else {
register()
}
</script>
</head>
<body>
Loading...
</body>
</html>`
return <NitroInput> {
entry: '{{ _internal.runtimeDir }}/entries/service-worker',
output: {
serverDir: '{{ output.dir }}/public/_server'
},
nuxtHooks: {
'generate:page' (page) {
page.html = page.html.replace('</body>', script + '</body>')
}
},
hooks: {
'nitro:document' (tmpl) {
tmpl.contents = tmpl.contents.replace('</body>', script + '</body>')
},
async 'nitro:compiled' ({ output }: NitroContext) {
await fsp.writeFile(resolve(output.publicDir, 'sw.js'), `self.importScripts(${genString(joinURL(baseURL, '_server/index.mjs'))});`, 'utf8')
// Temp fix
if (!existsSync(resolve(output.publicDir, 'index.html'))) {
await fsp.writeFile(resolve(output.publicDir, 'index.html'), html, 'utf8')
}
if (!existsSync(resolve(output.publicDir, '200.html'))) {
await fsp.writeFile(resolve(output.publicDir, '200.html'), html, 'utf8')
}
if (!existsSync(resolve(output.publicDir, '404.html'))) {
await fsp.writeFile(resolve(output.publicDir, '404.html'), html, 'utf8')
}
consola.info('Ready to deploy to static hosting:', prettyPath(output.publicDir as string))
}
}
}
})
| packages/nitro/src/presets/browser.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.0001797383010853082,
0.00017601210856810212,
0.00017296626174356788,
0.00017556853708811104,
0.0000019481433355394984
] |
{
"id": 10,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 25
} | <template>
<AppPage class="min-h-screen-sm relative z-0 h-full">
<div class="relative flex flex-col items-center justify-center px-2 sm:px-4 mt-20 lg:mt-32 md:px-0 z-10">
<h1 class="font-serif text-center text-display-6 md:text-display-5 2xl:text-display-4 mb-6">
{{ error.message }}
</h1>
<NuxtLink
to="/"
size="md"
class="text-gray-800 bg-primary hover:bg-primary-400 focus:bg-primary-400 font-medium rounded-md px-4 py-2.5"
>
Go Home
</NuxtLink>
</div>
</AppPage>
</template>
<script>
import { defineComponent } from '@nuxtjs/composition-api'
export default defineComponent({
props: {
error: {
type: Object,
required: true
}
},
head () {
return {
title: this.error.message
}
}
})
</script>
| docs/components/templates/Error.vue | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017840035434346646,
0.00017441196541767567,
0.0001715692487778142,
0.000173839129274711,
0.000002627157982715289
] |
{
"id": 10,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey').data).toMatchTypeOf<Ref<{ foo:string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toMatchTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/api/other').data).toMatchTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toMatchTypeOf<Ref<TestResponse>>()\n"
],
"file_path": "test/fixtures/basic/tests/types.ts",
"type": "add",
"edit_start_line_idx": 25
} | import type { InlineConfig, SSROptions } from 'vite'
import type { VueViteOptions } from 'vite-plugin-vue2'
export interface Nuxt {
options: any;
resolver: any;
hook: Function;
callHook: Function;
}
export interface ViteOptions extends Omit<InlineConfig, 'build'> {
/**
* Options for vite-plugin-vue2
*
* @see https://github.com/underfin/vite-plugin-vue2
*/
vue?: VueViteOptions
ssr?: boolean | SSROptions
build?: boolean | InlineConfig['build']
experimentWarning?: boolean
}
export interface ViteBuildContext {
nuxt: Nuxt;
builder: {
plugins: { name: string; mode?: 'client' | 'server'; src: string; }[];
};
config: ViteOptions;
}
| packages/bridge/src/vite/types.ts | 0 | https://github.com/nuxt/nuxt/commit/77aeaa3288f90bdeb1d34c373e9a3a05a8b31970 | [
0.00017941553960554302,
0.00017815225874073803,
0.00017639595898799598,
0.00017839876818470657,
0.0000011045974588341778
] |
{
"id": 0,
"code_window": [
"\theight: 100%;\n",
"\tvisibility: hidden;\n",
"\topacity: 0;\n",
"\tz-index: 10;\n",
"}\n",
"\n",
".monaco-workbench .part > .title {\n",
"\tdisplay: none; /* Parts have to opt in to show title area */\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 12;\n"
],
"file_path": "src/vs/workbench/browser/media/part.css",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.027962900698184967,
0.003821255173534155,
0.00016482669161632657,
0.002417632844299078,
0.0045896186493337154
] |
{
"id": 0,
"code_window": [
"\theight: 100%;\n",
"\tvisibility: hidden;\n",
"\topacity: 0;\n",
"\tz-index: 10;\n",
"}\n",
"\n",
".monaco-workbench .part > .title {\n",
"\tdisplay: none; /* Parts have to opt in to show title area */\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 12;\n"
],
"file_path": "src/vs/workbench/browser/media/part.css",
"type": "replace",
"edit_start_line_idx": 21
} | {
"displayName": "HTML Language Basics",
"description": "Provides syntax highlighting, bracket matching & snippets in HTML files."
}
| extensions/html/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0001698955602478236,
0.0001698955602478236,
0.0001698955602478236,
0.0001698955602478236,
0
] |
{
"id": 0,
"code_window": [
"\theight: 100%;\n",
"\tvisibility: hidden;\n",
"\topacity: 0;\n",
"\tz-index: 10;\n",
"}\n",
"\n",
".monaco-workbench .part > .title {\n",
"\tdisplay: none; /* Parts have to opt in to show title area */\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 12;\n"
],
"file_path": "src/vs/workbench/browser/media/part.css",
"type": "replace",
"edit_start_line_idx": 21
} | {
"name": "sql",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ./build/update-grammar.js"
},
"contributes": {
"languages": [
{
"id": "sql",
"extensions": [
".sql",
".dsql"
],
"aliases": [
"SQL"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "sql",
"scopeName": "source.sql",
"path": "./syntaxes/sql.tmLanguage.json"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/sql/package.json | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017765244410838932,
0.00017466145800426602,
0.00017245936032850295,
0.0001737416605465114,
0.0000018770266478895792
] |
{
"id": 0,
"code_window": [
"\theight: 100%;\n",
"\tvisibility: hidden;\n",
"\topacity: 0;\n",
"\tz-index: 10;\n",
"}\n",
"\n",
".monaco-workbench .part > .title {\n",
"\tdisplay: none; /* Parts have to opt in to show title area */\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 12;\n"
],
"file_path": "src/vs/workbench/browser/media/part.css",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* 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';
import { ICommandQuickPick, CommandsHistory } from 'vs/platform/quickinput/browser/commandsQuickAccess';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IMenuService, MenuId, MenuItemAction, SubmenuItemAction, Action2 } from 'vs/platform/actions/common/actions';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { CancellationToken } from 'vs/base/common/cancellation';
import { timeout } from 'vs/base/common/async';
import { DisposableStore, toDisposable, dispose } from 'vs/base/common/lifecycle';
import { AbstractEditorCommandsQuickAccessProvider } from 'vs/editor/contrib/quickAccess/commandsQuickAccess';
import { IEditor } from 'vs/editor/common/editorCommon';
import { Language } from 'vs/base/common/platform';
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 { DefaultQuickAccessFilterValue } from 'vs/platform/quickinput/common/quickAccess';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchQuickAccessConfiguration } from 'vs/workbench/browser/quickaccess';
import { Codicon } from 'vs/base/common/codicons';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { TriggerAction } from 'vs/platform/quickinput/browser/pickerQuickAccess';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { stripIcons } from 'vs/base/common/iconLabels';
import { isFirefox } from 'vs/base/browser/browser';
export class CommandsQuickAccessProvider extends AbstractEditorCommandsQuickAccessProvider {
// If extensions are not yet registered, we wait for a little moment to give them
// a chance to register so that the complete set of commands shows up as result
// We do not want to delay functionality beyond that time though to keep the commands
// functional.
private readonly extensionRegistrationRace = Promise.race([
timeout(800),
this.extensionService.whenInstalledExtensionsRegistered()
]);
protected get activeTextEditorControl(): IEditor | undefined { return this.editorService.activeTextEditorControl; }
get defaultFilterValue(): DefaultQuickAccessFilterValue | undefined {
if (this.configuration.preserveInput) {
return DefaultQuickAccessFilterValue.LAST;
}
return undefined;
}
constructor(
@IEditorService private readonly editorService: IEditorService,
@IMenuService private readonly menuService: IMenuService,
@IExtensionService private readonly extensionService: IExtensionService,
@IInstantiationService instantiationService: IInstantiationService,
@IKeybindingService keybindingService: IKeybindingService,
@ICommandService commandService: ICommandService,
@ITelemetryService telemetryService: ITelemetryService,
@IDialogService dialogService: IDialogService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
) {
super({
showAlias: !Language.isDefaultVariant(),
noResultsPick: {
label: localize('noCommandResults', "No matching commands"),
commandId: ''
}
}, instantiationService, keybindingService, commandService, telemetryService, dialogService);
}
private get configuration() {
const commandPaletteConfig = this.configurationService.getValue<IWorkbenchQuickAccessConfiguration>().workbench.commandPalette;
return {
preserveInput: commandPaletteConfig.preserveInput
};
}
protected async getCommandPicks(disposables: DisposableStore, token: CancellationToken): Promise<Array<ICommandQuickPick>> {
// wait for extensions registration or 800ms once
await this.extensionRegistrationRace;
if (token.isCancellationRequested) {
return [];
}
return [
...this.getCodeEditorCommandPicks(),
...this.getGlobalCommandPicks(disposables)
].map(c => ({
...c,
buttons: [{
iconClass: Codicon.gear.classNames,
tooltip: localize('configure keybinding', "Configure Keybinding"),
}],
trigger: (): TriggerAction => {
this.preferencesService.openGlobalKeybindingSettings(false, { query: `@command:${c.commandId}` });
return TriggerAction.CLOSE_PICKER;
},
}));
}
private getGlobalCommandPicks(disposables: DisposableStore): ICommandQuickPick[] {
const globalCommandPicks: ICommandQuickPick[] = [];
const scopedContextKeyService = this.editorService.activeEditorPane?.scopedContextKeyService || this.editorGroupService.activeGroup.scopedContextKeyService;
const globalCommandsMenu = this.menuService.createMenu(MenuId.CommandPalette, scopedContextKeyService);
const globalCommandsMenuActions = globalCommandsMenu.getActions()
.reduce((r, [, actions]) => [...r, ...actions], <Array<MenuItemAction | SubmenuItemAction | string>>[])
.filter(action => action instanceof MenuItemAction && action.enabled) as MenuItemAction[];
for (const action of globalCommandsMenuActions) {
// Label
let label = (typeof action.item.title === 'string' ? action.item.title : action.item.title.value) || action.item.id;
// Category
const category = typeof action.item.category === 'string' ? action.item.category : action.item.category?.value;
if (category) {
label = localize('commandWithCategory', "{0}: {1}", category, label);
}
// Alias
const aliasLabel = typeof action.item.title !== 'string' ? action.item.title.original : undefined;
const aliasCategory = (category && action.item.category && typeof action.item.category !== 'string') ? action.item.category.original : undefined;
const commandAlias = (aliasLabel && category) ?
aliasCategory ? `${aliasCategory}: ${aliasLabel}` : `${category}: ${aliasLabel}` :
aliasLabel;
globalCommandPicks.push({
commandId: action.item.id,
commandAlias,
label: stripIcons(label)
});
}
// Cleanup
globalCommandsMenu.dispose();
disposables.add(toDisposable(() => dispose(globalCommandsMenuActions)));
return globalCommandPicks;
}
}
//#region Actions
export class ShowAllCommandsAction extends Action2 {
static readonly ID = 'workbench.action.showCommands';
constructor() {
super({
id: ShowAllCommandsAction.ID,
title: { value: localize('showTriggerActions', "Show All Commands"), original: 'Show All Commands' },
f1: true,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: !isFirefox ? (KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyP) : undefined,
secondary: [KeyCode.F1]
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
accessor.get(IQuickInputService).quickAccess.show(CommandsQuickAccessProvider.PREFIX);
}
}
export class ClearCommandHistoryAction extends Action2 {
constructor() {
super({
id: 'workbench.action.clearCommandHistory',
title: { value: localize('clearCommandHistory', "Clear Command History"), original: 'Clear Command History' },
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const configurationService = accessor.get(IConfigurationService);
const storageService = accessor.get(IStorageService);
const commandHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(configurationService);
if (commandHistoryLength > 0) {
CommandsHistory.clearHistory(configurationService, storageService);
}
}
}
//#endregion
| src/vs/workbench/contrib/quickaccess/browser/commandsQuickAccess.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00025328551419079304,
0.00017607439076527953,
0.00016549490101169795,
0.00017304728680755943,
0.000018016897229244933
] |
{
"id": 1,
"code_window": [
"\tcontent: '';\n",
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--title-border-bottom-color);\n",
"\twidth: 100%;\n",
"\theight: 1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/editorgroupview.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.9206188321113586,
0.02105063945055008,
0.00016403570771217346,
0.00016892699932213873,
0.1356254667043686
] |
{
"id": 1,
"code_window": [
"\tcontent: '';\n",
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--title-border-bottom-color);\n",
"\twidth: 100%;\n",
"\theight: 1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/editorgroupview.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import assert = require('assert');
import { splitLines } from 'vs/base/common/strings';
import { Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { BeforeEditPositionMapper, TextEditInfo } from 'vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper';
import { Length, lengthOfString, lengthToObj, lengthToPosition, toLength } from 'vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length';
suite('Bracket Pair Colorizer - BeforeEditPositionMapper', () => {
test('Single-Line 1', () => {
assert.deepStrictEqual(
compute(
[
'0123456789',
],
[
new TextEdit(toLength(0, 4), toLength(0, 7), 'xy')
]
),
[
'0 1 2 3 x y 7 8 9 ', // The line
'0 0 0 0 0 0 0 0 0 0 ', // the old line numbers
'0 1 2 3 4 5 7 8 9 10 ', // the old columns
'0 0 0 0 0 0 0 0 0 0 ', // line count until next change
'4 3 2 1 0 0 3 2 1 0 ', // column count until next change
]
);
});
test('Single-Line 2', () => {
assert.deepStrictEqual(
compute(
[
'0123456789',
],
[
new TextEdit(toLength(0, 2), toLength(0, 4), 'xxxx'),
new TextEdit(toLength(0, 6), toLength(0, 6), 'yy')
]
),
[
'0 1 x x x x 4 5 y y 6 7 8 9 ',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ',
'0 1 2 3 4 5 4 5 6 7 6 7 8 9 10 ',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ',
'2 1 0 0 0 0 2 1 0 0 4 3 2 1 0 ',
]
);
});
test('Multi-Line Replace 1', () => {
assert.deepStrictEqual(
compute(
[
'₀₁₂₃₄₅₆₇₈₉',
'0123456789',
'⁰¹²³⁴⁵⁶⁷⁸⁹',
],
[
new TextEdit(toLength(0, 3), toLength(1, 3), 'xy'),
]
),
[
'₀ ₁ ₂ x y 3 4 5 6 7 8 9 ',
'0 0 0 0 0 1 1 1 1 1 1 1 1 ',
'0 1 2 3 4 3 4 5 6 7 8 9 10 ',
'0 0 0 0 0 1 1 1 1 1 1 1 1 ',
'3 2 1 0 0 10 10 10 10 10 10 10 10 ',
// ------------------
'⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ',
'2 2 2 2 2 2 2 2 2 2 2 ',
'0 1 2 3 4 5 6 7 8 9 10 ',
'0 0 0 0 0 0 0 0 0 0 0 ',
'10 9 8 7 6 5 4 3 2 1 0 ',
]
);
});
test('Multi-Line Replace 2', () => {
assert.deepStrictEqual(
compute(
[
'₀₁₂₃₄₅₆₇₈₉',
'012345678',
'⁰¹²³⁴⁵⁶⁷⁸⁹',
],
[
new TextEdit(toLength(0, 3), toLength(1, 0), 'ab'),
new TextEdit(toLength(1, 5), toLength(1, 7), 'c'),
]
),
[
'₀ ₁ ₂ a b 0 1 2 3 4 c 7 8 ',
'0 0 0 0 0 1 1 1 1 1 1 1 1 1 ',
'0 1 2 3 4 0 1 2 3 4 5 7 8 9 ',
'0 0 0 0 0 0 0 0 0 0 0 1 1 1 ',
'3 2 1 0 0 5 4 3 2 1 0 10 10 10 ',
// ------------------
'⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ',
'2 2 2 2 2 2 2 2 2 2 2 ',
'0 1 2 3 4 5 6 7 8 9 10 ',
'0 0 0 0 0 0 0 0 0 0 0 ',
'10 9 8 7 6 5 4 3 2 1 0 ',
]
);
});
test('Multi-Line Replace 3', () => {
assert.deepStrictEqual(
compute(
[
'₀₁₂₃₄₅₆₇₈₉',
'012345678',
'⁰¹²³⁴⁵⁶⁷⁸⁹',
],
[
new TextEdit(toLength(0, 3), toLength(1, 0), 'ab'),
new TextEdit(toLength(1, 5), toLength(1, 7), 'c'),
new TextEdit(toLength(1, 8), toLength(2, 4), 'd'),
]
),
[
'₀ ₁ ₂ a b 0 1 2 3 4 c 7 d ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ',
'0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 ',
'0 1 2 3 4 0 1 2 3 4 5 7 8 4 5 6 7 8 9 10 ',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ',
'3 2 1 0 0 5 4 3 2 1 0 1 0 6 5 4 3 2 1 0 ',
]
);
});
test('Multi-Line Insert 1', () => {
assert.deepStrictEqual(
compute(
[
'012345678',
],
[
new TextEdit(toLength(0, 3), toLength(0, 5), 'a\nb'),
]
),
[
'0 1 2 a ',
'0 0 0 0 0 ',
'0 1 2 3 4 ',
'0 0 0 0 0 ',
'3 2 1 0 0 ',
// ------------------
'b 5 6 7 8 ',
'1 0 0 0 0 0 ',
'0 5 6 7 8 9 ',
'0 0 0 0 0 0 ',
'0 4 3 2 1 0 ',
]
);
});
test('Multi-Line Insert 2', () => {
assert.deepStrictEqual(
compute(
[
'012345678',
],
[
new TextEdit(toLength(0, 3), toLength(0, 5), 'a\nb'),
new TextEdit(toLength(0, 7), toLength(0, 8), 'x\ny'),
]
),
[
'0 1 2 a ',
'0 0 0 0 0 ',
'0 1 2 3 4 ',
'0 0 0 0 0 ',
'3 2 1 0 0 ',
// ------------------
'b 5 6 x ',
'1 0 0 0 0 ',
'0 5 6 7 8 ',
'0 0 0 0 0 ',
'0 2 1 0 0 ',
// ------------------
'y 8 ',
'1 0 0 ',
'0 8 9 ',
'0 0 0 ',
'0 1 0 ',
]
);
});
test('Multi-Line Replace/Insert 1', () => {
assert.deepStrictEqual(
compute(
[
'₀₁₂₃₄₅₆₇₈₉',
'012345678',
'⁰¹²³⁴⁵⁶⁷⁸⁹',
],
[
new TextEdit(toLength(0, 3), toLength(1, 1), 'aaa\nbbb'),
]
),
[
'₀ ₁ ₂ a a a ',
'0 0 0 0 0 0 0 ',
'0 1 2 3 4 5 6 ',
'0 0 0 0 0 0 0 ',
'3 2 1 0 0 0 0 ',
// ------------------
'b b b 1 2 3 4 5 6 7 8 ',
'1 1 1 1 1 1 1 1 1 1 1 1 ',
'0 1 2 1 2 3 4 5 6 7 8 9 ',
'0 0 0 1 1 1 1 1 1 1 1 1 ',
'0 0 0 10 10 10 10 10 10 10 10 10 ',
// ------------------
'⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ',
'2 2 2 2 2 2 2 2 2 2 2 ',
'0 1 2 3 4 5 6 7 8 9 10 ',
'0 0 0 0 0 0 0 0 0 0 0 ',
'10 9 8 7 6 5 4 3 2 1 0 ',
]
);
});
test('Multi-Line Replace/Insert 2', () => {
assert.deepStrictEqual(
compute(
[
'₀₁₂₃₄₅₆₇₈₉',
'012345678',
'⁰¹²³⁴⁵⁶⁷⁸⁹',
],
[
new TextEdit(toLength(0, 3), toLength(1, 1), 'aaa\nbbb'),
new TextEdit(toLength(1, 5), toLength(1, 5), 'x\ny'),
new TextEdit(toLength(1, 7), toLength(2, 4), 'k\nl'),
]
),
[
'₀ ₁ ₂ a a a ',
'0 0 0 0 0 0 0 ',
'0 1 2 3 4 5 6 ',
'0 0 0 0 0 0 0 ',
'3 2 1 0 0 0 0 ',
// ------------------
'b b b 1 2 3 4 x ',
'1 1 1 1 1 1 1 1 1 ',
'0 1 2 1 2 3 4 5 6 ',
'0 0 0 0 0 0 0 0 0 ',
'0 0 0 4 3 2 1 0 0 ',
// ------------------
'y 5 6 k ',
'2 1 1 1 1 ',
'0 5 6 7 8 ',
'0 0 0 0 0 ',
'0 2 1 0 0 ',
// ------------------
'l ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ',
'2 2 2 2 2 2 2 2 ',
'0 4 5 6 7 8 9 10 ',
'0 0 0 0 0 0 0 0 ',
'0 6 5 4 3 2 1 0 ',
]
);
});
});
/** @pure */
function compute(inputArr: string[], edits: TextEdit[]): string[] {
const newLines = splitLines(applyLineColumnEdits(inputArr.join('\n'), edits.map(e => ({
text: e.newText,
range: Range.fromPositions(lengthToPosition(e.startOffset), lengthToPosition(e.endOffset))
}))));
const mapper = new BeforeEditPositionMapper(edits, lengthOfString(newLines.join('\n')));
const result = new Array<string>();
let lineIdx = 0;
for (const line of newLines) {
let lineLine = '';
let colLine = '';
let lineStr = '';
let colDist = '';
let lineDist = '';
for (let colIdx = 0; colIdx <= line.length; colIdx++) {
const before = mapper.getOffsetBeforeChange(toLength(lineIdx, colIdx));
const beforeObj = lengthToObj(before);
if (colIdx < line.length) {
lineStr += rightPad(line[colIdx], 3);
}
lineLine += rightPad('' + beforeObj.lineCount, 3);
colLine += rightPad('' + beforeObj.columnCount, 3);
const dist = lengthToObj(mapper.getDistanceToNextChange(toLength(lineIdx, colIdx)));
lineDist += rightPad('' + dist.lineCount, 3);
colDist += rightPad('' + dist.columnCount, 3);
}
result.push(lineStr);
result.push(lineLine);
result.push(colLine);
result.push(lineDist);
result.push(colDist);
lineIdx++;
}
return result;
}
export class TextEdit extends TextEditInfo {
constructor(
startOffset: Length,
endOffset: Length,
public readonly newText: string
) {
super(
startOffset,
endOffset,
lengthOfString(newText)
);
}
}
class PositionOffsetTransformer {
private readonly lineStartOffsetByLineIdx: number[];
constructor(text: string) {
this.lineStartOffsetByLineIdx = [];
this.lineStartOffsetByLineIdx.push(0);
for (let i = 0; i < text.length; i++) {
if (text.charAt(i) === '\n') {
this.lineStartOffsetByLineIdx.push(i + 1);
}
}
}
getOffset(position: Position): number {
return this.lineStartOffsetByLineIdx[position.lineNumber - 1] + position.column - 1;
}
}
function applyLineColumnEdits(text: string, edits: { range: IRange, text: string }[]): string {
const transformer = new PositionOffsetTransformer(text);
const offsetEdits = edits.map(e => {
const range = Range.lift(e.range);
return ({
startOffset: transformer.getOffset(range.getStartPosition()),
endOffset: transformer.getOffset(range.getEndPosition()),
text: e.text
});
});
offsetEdits.sort((a, b) => b.startOffset - a.startOffset);
for (const edit of offsetEdits) {
text = text.substring(0, edit.startOffset) + edit.text + text.substring(edit.endOffset);
}
return text;
}
function rightPad(str: string, len: number): string {
while (str.length < len) {
str += ' ';
}
return str;
}
| src/vs/editor/test/common/model/bracketPairColorizer/beforeEditPositionMapper.test.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00037176249315962195,
0.00017664955521468073,
0.0001651687198318541,
0.00017164909513667226,
0.000030497143598040566
] |
{
"id": 1,
"code_window": [
"\tcontent: '';\n",
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--title-border-bottom-color);\n",
"\twidth: 100%;\n",
"\theight: 1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/editorgroupview.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as strings from 'vs/base/common/strings';
enum Severity {
Ignore = 0,
Info = 1,
Warning = 2,
Error = 3
}
namespace Severity {
const _error = 'error';
const _warning = 'warning';
const _warn = 'warn';
const _info = 'info';
const _ignore = 'ignore';
/**
* Parses 'error', 'warning', 'warn', 'info' in call casings
* and falls back to ignore.
*/
export function fromValue(value: string): Severity {
if (!value) {
return Severity.Ignore;
}
if (strings.equalsIgnoreCase(_error, value)) {
return Severity.Error;
}
if (strings.equalsIgnoreCase(_warning, value) || strings.equalsIgnoreCase(_warn, value)) {
return Severity.Warning;
}
if (strings.equalsIgnoreCase(_info, value)) {
return Severity.Info;
}
return Severity.Ignore;
}
export function toString(severity: Severity): string {
switch (severity) {
case Severity.Error: return _error;
case Severity.Warning: return _warning;
case Severity.Info: return _info;
default: return _ignore;
}
}
}
export default Severity;
| src/vs/base/common/severity.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017389364074915648,
0.0001711365330265835,
0.00016636413056403399,
0.00017149667837657034,
0.0000025755437036423245
] |
{
"id": 1,
"code_window": [
"\tcontent: '';\n",
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--title-border-bottom-color);\n",
"\twidth: 100%;\n",
"\theight: 1px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/editorgroupview.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { onUnexpectedExternalError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { ITextModel } from 'vs/editor/common/model';
import { DocumentSemanticTokensProviderRegistry, DocumentSemanticTokensProvider, SemanticTokens, SemanticTokensEdits, SemanticTokensLegend, DocumentRangeSemanticTokensProviderRegistry, DocumentRangeSemanticTokensProvider } from 'vs/editor/common/languages';
import { IModelService } from 'vs/editor/common/services/model';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { assertType } from 'vs/base/common/types';
import { VSBuffer } from 'vs/base/common/buffer';
import { encodeSemanticTokensDto } from 'vs/editor/common/services/semanticTokensDto';
import { Range } from 'vs/editor/common/core/range';
export function isSemanticTokens(v: SemanticTokens | SemanticTokensEdits): v is SemanticTokens {
return v && !!((<SemanticTokens>v).data);
}
export function isSemanticTokensEdits(v: SemanticTokens | SemanticTokensEdits): v is SemanticTokensEdits {
return v && Array.isArray((<SemanticTokensEdits>v).edits);
}
export class DocumentSemanticTokensResult {
constructor(
public readonly provider: DocumentSemanticTokensProvider,
public readonly tokens: SemanticTokens | SemanticTokensEdits | null,
public readonly error: any
) { }
}
export function hasDocumentSemanticTokensProvider(model: ITextModel): boolean {
return DocumentSemanticTokensProviderRegistry.has(model);
}
function getDocumentSemanticTokensProviders(model: ITextModel): DocumentSemanticTokensProvider[] {
const groups = DocumentSemanticTokensProviderRegistry.orderedGroups(model);
return (groups.length > 0 ? groups[0] : []);
}
export async function getDocumentSemanticTokens(model: ITextModel, lastProvider: DocumentSemanticTokensProvider | null, lastResultId: string | null, token: CancellationToken): Promise<DocumentSemanticTokensResult | null> {
const providers = getDocumentSemanticTokensProviders(model);
// Get tokens from all providers at the same time.
const results = await Promise.all(providers.map(async (provider) => {
let result: SemanticTokens | SemanticTokensEdits | null | undefined;
let error: any = null;
try {
result = await provider.provideDocumentSemanticTokens(model, (provider === lastProvider ? lastResultId : null), token);
} catch (err) {
error = err;
result = null;
}
if (!result || (!isSemanticTokens(result) && !isSemanticTokensEdits(result))) {
result = null;
}
return new DocumentSemanticTokensResult(provider, result, error);
}));
// Try to return the first result with actual tokens or
// the first result which threw an error (!!)
for (const result of results) {
if (result.error) {
throw result.error;
}
if (result.tokens) {
return result;
}
}
// Return the first result, even if it doesn't have tokens
if (results.length > 0) {
return results[0];
}
return null;
}
function _getDocumentSemanticTokensProviderHighestGroup(model: ITextModel): DocumentSemanticTokensProvider[] | null {
const result = DocumentSemanticTokensProviderRegistry.orderedGroups(model);
return (result.length > 0 ? result[0] : null);
}
class DocumentRangeSemanticTokensResult {
constructor(
public readonly provider: DocumentRangeSemanticTokensProvider,
public readonly tokens: SemanticTokens | null,
) { }
}
export function hasDocumentRangeSemanticTokensProvider(model: ITextModel): boolean {
return DocumentRangeSemanticTokensProviderRegistry.has(model);
}
function getDocumentRangeSemanticTokensProviders(model: ITextModel): DocumentRangeSemanticTokensProvider[] {
const groups = DocumentRangeSemanticTokensProviderRegistry.orderedGroups(model);
return (groups.length > 0 ? groups[0] : []);
}
export async function getDocumentRangeSemanticTokens(model: ITextModel, range: Range, token: CancellationToken): Promise<DocumentRangeSemanticTokensResult | null> {
const providers = getDocumentRangeSemanticTokensProviders(model);
// Get tokens from all providers at the same time.
const results = await Promise.all(providers.map(async (provider) => {
let result: SemanticTokens | null | undefined;
try {
result = await provider.provideDocumentRangeSemanticTokens(model, range, token);
} catch (err) {
onUnexpectedExternalError(err);
result = null;
}
if (!result || !isSemanticTokens(result)) {
result = null;
}
return new DocumentRangeSemanticTokensResult(provider, result);
}));
// Try to return the first result with actual tokens
for (const result of results) {
if (result.tokens) {
return result;
}
}
// Return the first result, even if it doesn't have tokens
if (results.length > 0) {
return results[0];
}
return null;
}
CommandsRegistry.registerCommand('_provideDocumentSemanticTokensLegend', async (accessor, ...args): Promise<SemanticTokensLegend | undefined> => {
const [uri] = args;
assertType(uri instanceof URI);
const model = accessor.get(IModelService).getModel(uri);
if (!model) {
return undefined;
}
const providers = _getDocumentSemanticTokensProviderHighestGroup(model);
if (!providers) {
// there is no provider => fall back to a document range semantic tokens provider
return accessor.get(ICommandService).executeCommand('_provideDocumentRangeSemanticTokensLegend', uri);
}
return providers[0].getLegend();
});
CommandsRegistry.registerCommand('_provideDocumentSemanticTokens', async (accessor, ...args): Promise<VSBuffer | undefined> => {
const [uri] = args;
assertType(uri instanceof URI);
const model = accessor.get(IModelService).getModel(uri);
if (!model) {
return undefined;
}
if (!hasDocumentSemanticTokensProvider(model)) {
// there is no provider => fall back to a document range semantic tokens provider
return accessor.get(ICommandService).executeCommand('_provideDocumentRangeSemanticTokens', uri, model.getFullModelRange());
}
const r = await getDocumentSemanticTokens(model, null, null, CancellationToken.None);
if (!r) {
return undefined;
}
const { provider, tokens } = r;
if (!tokens || !isSemanticTokens(tokens)) {
return undefined;
}
const buff = encodeSemanticTokensDto({
id: 0,
type: 'full',
data: tokens.data
});
if (tokens.resultId) {
provider.releaseDocumentSemanticTokens(tokens.resultId);
}
return buff;
});
CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokensLegend', async (accessor, ...args): Promise<SemanticTokensLegend | undefined> => {
const [uri, range] = args;
assertType(uri instanceof URI);
const model = accessor.get(IModelService).getModel(uri);
if (!model) {
return undefined;
}
const providers = getDocumentRangeSemanticTokensProviders(model);
if (providers.length === 0) {
// no providers
return undefined;
}
if (providers.length === 1) {
// straight forward case, just a single provider
return providers[0].getLegend();
}
if (!range || !Range.isIRange(range)) {
// if no range is provided, we cannot support multiple providers
// as we cannot fall back to the one which would give results
// => return the first legend for backwards compatibility and print a warning
console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`);
return providers[0].getLegend();
}
const result = await getDocumentRangeSemanticTokens(model, Range.lift(range), CancellationToken.None);
if (!result) {
return undefined;
}
return result.provider.getLegend();
});
CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokens', async (accessor, ...args): Promise<VSBuffer | undefined> => {
const [uri, range] = args;
assertType(uri instanceof URI);
assertType(Range.isIRange(range));
const model = accessor.get(IModelService).getModel(uri);
if (!model) {
return undefined;
}
const result = await getDocumentRangeSemanticTokens(model, Range.lift(range), CancellationToken.None);
if (!result || !result.tokens) {
// there is no provider or it didn't return tokens
return undefined;
}
return encodeSemanticTokensDto({
id: 0,
type: 'full',
data: result.tokens.data
});
});
| src/vs/editor/common/services/getSemanticTokens.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0002961507416330278,
0.00017962936544790864,
0.00016722311556804925,
0.00017304797074757516,
0.000025163491955026984
] |
{
"id": 2,
"code_window": [
"\tis still broken. putting sticky-tabs above tabs bottom border would not render this\n",
"\tborder at all for sticky tabs.\n",
"\n",
"\tOn top of that there is 2 borders with a z-index for a general border below tabs\n",
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tOn top of that there is 3 borders with a z-index for a general border below or above tabs\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.9930370450019836,
0.031619276851415634,
0.00016877194866538048,
0.0003589020052459091,
0.15682853758335114
] |
{
"id": 2,
"code_window": [
"\tis still broken. putting sticky-tabs above tabs bottom border would not render this\n",
"\tborder at all for sticky tabs.\n",
"\n",
"\tOn top of that there is 2 borders with a z-index for a general border below tabs\n",
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tOn top of that there is 3 borders with a z-index for a general border below or above tabs\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 18
} | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style>
.container {
border-top: 1px solid #ccc;
padding-top: 5px;
clear: both;
margin-top: 30px;
}
.container .title {
margin-bottom: 10px;
}
.container button {
float: left;
}
.container textarea {
float: left;
width: 200px;
height: 100px;
margin-left: 50px;
}
.container .output {
float: left;
background: lightblue;
margin: 0;
margin-left: 50px;
}
.container .check {
float: left;
background: grey;
margin: 0;
margin-left: 50px;
}
.container .check.good {
background: lightgreen;
}
</style>
</head>
<body>
<h3>Detailed setup steps at https://github.com/microsoft/vscode/wiki/IME-Test</h3>
<script src="../../../../loader.js"></script>
<script>
require.config({
baseUrl: '../../../../../../out'
});
require(['vs/editor/test/browser/controller/imeTester'], function(imeTester) {
// console.log('loaded', imeTester);
// imeTester.createTest();
});
</script>
</body>
</html>
| src/vs/editor/test/browser/controller/imeTester.html | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017063213454093784,
0.0001679152628639713,
0.00016568593855481595,
0.00016787738422863185,
0.0000016021143665057025
] |
{
"id": 2,
"code_window": [
"\tis still broken. putting sticky-tabs above tabs bottom border would not render this\n",
"\tborder at all for sticky tabs.\n",
"\n",
"\tOn top of that there is 2 borders with a z-index for a general border below tabs\n",
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tOn top of that there is 3 borders with a z-index for a general border below or above tabs\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onDidChangeFullscreen, isFullscreen } from 'vs/base/browser/browser';
import { getTotalHeight, getTotalWidth } from 'vs/base/browser/dom';
import { Color } from 'vs/base/common/color';
import { Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ILifecycleService, LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { editorBackground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { getThemeTypeSelector, IThemeService } from 'vs/platform/theme/common/themeService';
import { DEFAULT_EDITOR_MIN_DIMENSIONS } from 'vs/workbench/browser/parts/editor/editor';
import * as themes from 'vs/workbench/common/theme';
import { IWorkbenchLayoutService, Parts, Position } from 'vs/workbench/services/layout/browser/layoutService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import * as perf from 'vs/base/common/performance';
import { assertIsDefined } from 'vs/base/common/types';
import { RunOnceScheduler } from 'vs/base/common/async';
import { ISplashStorageService } from 'vs/workbench/contrib/splash/browser/splash';
export class PartsSplash {
private static readonly _splashElementId = 'monaco-parts-splash';
private readonly _disposables = new DisposableStore();
private _didChangeTitleBarStyle?: boolean;
constructor(
@IThemeService private readonly _themeService: IThemeService,
@IWorkbenchLayoutService private readonly _layoutService: IWorkbenchLayoutService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@ILifecycleService lifecycleService: ILifecycleService,
@IEditorGroupsService editorGroupsService: IEditorGroupsService,
@IConfigurationService configService: IConfigurationService,
@ISplashStorageService private readonly _partSplashService: ISplashStorageService
) {
lifecycleService.when(LifecyclePhase.Restored).then(_ => {
this._removePartsSplash();
perf.mark('code/didRemovePartsSplash');
});
const savePartsSplashSoon = new RunOnceScheduler(() => this._savePartsSplash(), 800);
Event.any(onDidChangeFullscreen, editorGroupsService.onDidLayout)(() => {
savePartsSplashSoon.schedule();
}, undefined, this._disposables);
configService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('window.titleBarStyle')) {
this._didChangeTitleBarStyle = true;
this._savePartsSplash();
}
}, this, this._disposables);
_themeService.onDidColorThemeChange(_ => {
this._savePartsSplash();
}, this, this._disposables);
}
dispose(): void {
this._disposables.dispose();
}
private _savePartsSplash() {
const theme = this._themeService.getColorTheme();
this._partSplashService.saveWindowSplash({
baseTheme: getThemeTypeSelector(theme.type),
colorInfo: {
foreground: theme.getColor(foreground)?.toString(),
background: Color.Format.CSS.formatHex(theme.getColor(editorBackground) || themes.WORKBENCH_BACKGROUND(theme)),
editorBackground: theme.getColor(editorBackground)?.toString(),
titleBarBackground: theme.getColor(themes.TITLE_BAR_ACTIVE_BACKGROUND)?.toString(),
activityBarBackground: theme.getColor(themes.ACTIVITY_BAR_BACKGROUND)?.toString(),
sideBarBackground: theme.getColor(themes.SIDE_BAR_BACKGROUND)?.toString(),
statusBarBackground: theme.getColor(themes.STATUS_BAR_BACKGROUND)?.toString(),
statusBarNoFolderBackground: theme.getColor(themes.STATUS_BAR_NO_FOLDER_BACKGROUND)?.toString(),
windowBorder: theme.getColor(themes.WINDOW_ACTIVE_BORDER)?.toString() ?? theme.getColor(themes.WINDOW_INACTIVE_BORDER)?.toString()
},
layoutInfo: !this._shouldSaveLayoutInfo() ? undefined : {
sideBarSide: this._layoutService.getSideBarPosition() === Position.RIGHT ? 'right' : 'left',
editorPartMinWidth: DEFAULT_EDITOR_MIN_DIMENSIONS.width,
titleBarHeight: this._layoutService.isVisible(Parts.TITLEBAR_PART) ? getTotalHeight(assertIsDefined(this._layoutService.getContainer(Parts.TITLEBAR_PART))) : 0,
activityBarWidth: this._layoutService.isVisible(Parts.ACTIVITYBAR_PART) ? getTotalWidth(assertIsDefined(this._layoutService.getContainer(Parts.ACTIVITYBAR_PART))) : 0,
sideBarWidth: this._layoutService.isVisible(Parts.SIDEBAR_PART) ? getTotalWidth(assertIsDefined(this._layoutService.getContainer(Parts.SIDEBAR_PART))) : 0,
statusBarHeight: this._layoutService.isVisible(Parts.STATUSBAR_PART) ? getTotalHeight(assertIsDefined(this._layoutService.getContainer(Parts.STATUSBAR_PART))) : 0,
windowBorder: this._layoutService.hasWindowBorder(),
windowBorderRadius: this._layoutService.getWindowBorderRadius()
}
});
}
private _shouldSaveLayoutInfo(): boolean {
return !isFullscreen() && !this._environmentService.isExtensionDevelopment && !this._didChangeTitleBarStyle;
}
private _removePartsSplash(): void {
const element = document.getElementById(PartsSplash._splashElementId);
if (element) {
element.style.display = 'none';
}
// remove initial colors
const defaultStyles = document.head.getElementsByClassName('initialShellColors');
if (defaultStyles.length) {
document.head.removeChild(defaultStyles[0]);
}
}
}
| src/vs/workbench/contrib/splash/browser/partsSplash.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00022637027723249048,
0.000178425558260642,
0.00016334705287590623,
0.00016883453645277768,
0.00001959885958058294
] |
{
"id": 2,
"code_window": [
"\tis still broken. putting sticky-tabs above tabs bottom border would not render this\n",
"\tborder at all for sticky tabs.\n",
"\n",
"\tOn top of that there is 2 borders with a z-index for a general border below tabs\n",
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tOn top of that there is 3 borders with a z-index for a general border below or above tabs\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IRemoteAuthorityResolverService, RemoteAuthorityResolverError } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { AbstractRemoteAgentService } from 'vs/workbench/services/remote/common/abstractRemoteAgentService';
import { IProductService } from 'vs/platform/product/common/productService';
import { IWebSocketFactory, BrowserSocketFactory } from 'vs/platform/remote/browser/browserSocketFactory';
import { ISignService } from 'vs/platform/sign/common/sign';
import { ILogService } from 'vs/platform/log/common/log';
import { Severity } from 'vs/platform/notification/common/notification';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions } from 'vs/workbench/common/contributions';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { getRemoteName } from 'vs/platform/remote/common/remoteHosts';
export class RemoteAgentService extends AbstractRemoteAgentService implements IRemoteAgentService {
constructor(
webSocketFactory: IWebSocketFactory | null | undefined,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@IProductService productService: IProductService,
@IRemoteAuthorityResolverService remoteAuthorityResolverService: IRemoteAuthorityResolverService,
@ISignService signService: ISignService,
@ILogService logService: ILogService
) {
super(new BrowserSocketFactory(webSocketFactory), environmentService, productService, remoteAuthorityResolverService, signService, logService);
}
}
class RemoteConnectionFailureNotificationContribution implements IWorkbenchContribution {
constructor(
@IRemoteAgentService remoteAgentService: IRemoteAgentService,
@IDialogService private readonly _dialogService: IDialogService,
@IHostService private readonly _hostService: IHostService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
) {
// Let's cover the case where connecting to fetch the remote extension info fails
remoteAgentService.getRawEnvironment()
.then(undefined, (err) => {
type RemoteConnectionFailureClassification = {
web: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
remoteName: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
message: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
};
type RemoteConnectionFailureEvent = {
web: boolean;
remoteName: string | undefined;
message: string;
};
this._telemetryService.publicLog2<RemoteConnectionFailureEvent, RemoteConnectionFailureClassification>('remoteConnectionFailure', {
web: true,
remoteName: getRemoteName(this._environmentService.remoteAuthority),
message: err ? err.message : ''
});
if (!RemoteAuthorityResolverError.isHandled(err)) {
this._presentConnectionError(err);
}
});
}
private async _presentConnectionError(err: any): Promise<void> {
const res = await this._dialogService.show(
Severity.Error,
nls.localize('connectionError', "An unexpected error occurred that requires a reload of this page."),
[
nls.localize('reload', "Reload")
],
{
detail: nls.localize('connectionErrorDetail', "The workbench failed to connect to the server (Error: {0})", err ? err.message : '')
}
);
if (res.choice === 0) {
this._hostService.reload();
}
}
}
const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(Extensions.Workbench);
workbenchRegistry.registerWorkbenchContribution(RemoteConnectionFailureNotificationContribution, LifecyclePhase.Ready);
| src/vs/workbench/services/remote/browser/remoteAgentService.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017331972776446491,
0.00016847120423335582,
0.00016450231487397105,
0.0001680689019849524,
0.000002558037067501573
] |
{
"id": 3,
"code_window": [
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n",
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t- editor group border\n",
"\n",
"\tFinally, we show a drop overlay that should always be on top of everything.\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.9868412017822266,
0.022486090660095215,
0.00016420047904830426,
0.00019771330698858947,
0.14539502561092377
] |
{
"id": 3,
"code_window": [
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n",
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t- editor group border\n",
"\n",
"\tFinally, we show a drop overlay that should always be on top of everything.\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { incrementFileName } from 'vs/workbench/contrib/files/browser/fileActions';
suite('Files - Increment file name simple', () => {
test('Increment file name without any version', function () {
const name = 'test.js';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy.js');
});
test('Increment file name with suffix version', function () {
const name = 'test copy.js';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy 2.js');
});
test('Increment file name with suffix version with leading zeros', function () {
const name = 'test copy 005.js';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy 6.js');
});
test('Increment file name with suffix version, too big number', function () {
const name = 'test copy 9007199254740992.js';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy 9007199254740992 copy.js');
});
test('Increment file name with just version in name', function () {
const name = 'copy.js';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'copy copy.js');
});
test('Increment file name with just version in name, v2', function () {
const name = 'copy 2.js';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'copy 2 copy.js');
});
test('Increment file name without any extension or version', function () {
const name = 'test';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy');
});
test('Increment file name without any extension or version, trailing dot', function () {
const name = 'test.';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy.');
});
test('Increment file name without any extension or version, leading dot', function () {
const name = '.test';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, '.test copy');
});
test('Increment file name without any extension or version, leading dot v2', function () {
const name = '..test';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, '. copy.test');
});
test('Increment file name without any extension but with suffix version', function () {
const name = 'test copy 5';
const result = incrementFileName(name, false, 'simple');
assert.strictEqual(result, 'test copy 6');
});
test('Increment folder name without any version', function () {
const name = 'test';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test copy');
});
test('Increment folder name with suffix version', function () {
const name = 'test copy';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test copy 2');
});
test('Increment folder name with suffix version, leading zeros', function () {
const name = 'test copy 005';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test copy 6');
});
test('Increment folder name with suffix version, too big number', function () {
const name = 'test copy 9007199254740992';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test copy 9007199254740992 copy');
});
test('Increment folder name with just version in name', function () {
const name = 'copy';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'copy copy');
});
test('Increment folder name with just version in name, v2', function () {
const name = 'copy 2';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'copy 2 copy');
});
test('Increment folder name "with extension" but without any version', function () {
const name = 'test.js';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test.js copy');
});
test('Increment folder name "with extension" and with suffix version', function () {
const name = 'test.js copy 5';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test.js copy 6');
});
test('Increment file/folder name with suffix version, special case 1', function () {
const name = 'test copy 0';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test copy');
});
test('Increment file/folder name with suffix version, special case 2', function () {
const name = 'test copy 1';
const result = incrementFileName(name, true, 'simple');
assert.strictEqual(result, 'test copy 2');
});
});
suite('Files - Increment file name smart', () => {
test('Increment file name without any version', function () {
const name = 'test.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test.1.js');
});
test('Increment folder name without any version', function () {
const name = 'test';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, 'test.1');
});
test('Increment file name with suffix version', function () {
const name = 'test.1.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test.2.js');
});
test('Increment file name with suffix version with trailing zeros', function () {
const name = 'test.001.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test.002.js');
});
test('Increment file name with suffix version with trailing zeros, changing length', function () {
const name = 'test.009.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test.010.js');
});
test('Increment file name with suffix version with `-` as separator', function () {
const name = 'test-1.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test-2.js');
});
test('Increment file name with suffix version with `-` as separator, trailing zeros', function () {
const name = 'test-001.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test-002.js');
});
test('Increment file name with suffix version with `-` as separator, trailing zeros, changnig length', function () {
const name = 'test-099.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test-100.js');
});
test('Increment file name with suffix version with `_` as separator', function () {
const name = 'test_1.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test_2.js');
});
test('Increment folder name with suffix version', function () {
const name = 'test.1';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, 'test.2');
});
test('Increment folder name with suffix version, trailing zeros', function () {
const name = 'test.001';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, 'test.002');
});
test('Increment folder name with suffix version with `-` as separator', function () {
const name = 'test-1';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, 'test-2');
});
test('Increment folder name with suffix version with `_` as separator', function () {
const name = 'test_1';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, 'test_2');
});
test('Increment file name with suffix version, too big number', function () {
const name = 'test.9007199254740992.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'test.9007199254740992.1.js');
});
test('Increment folder name with suffix version, too big number', function () {
const name = 'test.9007199254740992';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, 'test.9007199254740992.1');
});
test('Increment file name with prefix version', function () {
const name = '1.test.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '2.test.js');
});
test('Increment file name with just version in name', function () {
const name = '1.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '2.js');
});
test('Increment file name with just version in name, too big number', function () {
const name = '9007199254740992.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '9007199254740992.1.js');
});
test('Increment file name with prefix version, trailing zeros', function () {
const name = '001.test.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '002.test.js');
});
test('Increment file name with prefix version with `-` as separator', function () {
const name = '1-test.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '2-test.js');
});
test('Increment file name with prefix version with `_` as separator', function () {
const name = '1_test.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '2_test.js');
});
test('Increment file name with prefix version, too big number', function () {
const name = '9007199254740992.test.js';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '9007199254740992.test.1.js');
});
test('Increment file name with just version and no extension', function () {
const name = '001004';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '001005');
});
test('Increment file name with just version and no extension, too big number', function () {
const name = '9007199254740992';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, '9007199254740992.1');
});
test('Increment file name with no extension and no version', function () {
const name = 'file';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'file1');
});
test('Increment file name with no extension', function () {
const name = 'file1';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'file2');
});
test('Increment file name with no extension, too big number', function () {
const name = 'file9007199254740992';
const result = incrementFileName(name, false, 'smart');
assert.strictEqual(result, 'file9007199254740992.1');
});
test('Increment folder name with prefix version', function () {
const name = '1.test';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, '2.test');
});
test('Increment folder name with prefix version, too big number', function () {
const name = '9007199254740992.test';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, '9007199254740992.test.1');
});
test('Increment folder name with prefix version, trailing zeros', function () {
const name = '001.test';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, '002.test');
});
test('Increment folder name with prefix version with `-` as separator', function () {
const name = '1-test';
const result = incrementFileName(name, true, 'smart');
assert.strictEqual(result, '2-test');
});
});
| src/vs/workbench/contrib/files/test/browser/fileActions.test.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0001754130789777264,
0.0001735352852847427,
0.0001699589192867279,
0.0001734382676659152,
0.000001266966137336567
] |
{
"id": 3,
"code_window": [
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n",
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t- editor group border\n",
"\n",
"\tFinally, we show a drop overlay that should always be on top of everything.\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "add",
"edit_start_line_idx": 22
} | [
{
"c": "<?",
"t": "text.xml meta.tag.preprocessor.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "xml",
"t": "text.xml meta.tag.preprocessor.xml entity.name.tag.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": " version",
"t": "text.xml meta.tag.preprocessor.xml entity.other.attribute-name.xml",
"r": {
"dark_plus": "entity.other.attribute-name: #9CDCFE",
"light_plus": "entity.other.attribute-name: #FF0000",
"dark_vs": "entity.other.attribute-name: #9CDCFE",
"light_vs": "entity.other.attribute-name: #FF0000",
"hc_black": "entity.other.attribute-name: #9CDCFE"
}
},
{
"c": "=",
"t": "text.xml meta.tag.preprocessor.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.begin.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "1.0",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.end.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": " encoding",
"t": "text.xml meta.tag.preprocessor.xml entity.other.attribute-name.xml",
"r": {
"dark_plus": "entity.other.attribute-name: #9CDCFE",
"light_plus": "entity.other.attribute-name: #FF0000",
"dark_vs": "entity.other.attribute-name: #9CDCFE",
"light_vs": "entity.other.attribute-name: #FF0000",
"hc_black": "entity.other.attribute-name: #9CDCFE"
}
},
{
"c": "=",
"t": "text.xml meta.tag.preprocessor.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.begin.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "utf-8",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.end.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": " standalone",
"t": "text.xml meta.tag.preprocessor.xml entity.other.attribute-name.xml",
"r": {
"dark_plus": "entity.other.attribute-name: #9CDCFE",
"light_plus": "entity.other.attribute-name: #FF0000",
"dark_vs": "entity.other.attribute-name: #9CDCFE",
"light_vs": "entity.other.attribute-name: #FF0000",
"hc_black": "entity.other.attribute-name: #9CDCFE"
}
},
{
"c": "=",
"t": "text.xml meta.tag.preprocessor.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.begin.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "no",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.end.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": " ",
"t": "text.xml meta.tag.preprocessor.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "?>",
"t": "text.xml meta.tag.preprocessor.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "<",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "WorkFine",
"t": "text.xml meta.tag.xml entity.name.tag.localname.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": " ",
"t": "text.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "<",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "NoColorWithNonLatinCharacters_АБВ",
"t": "text.xml meta.tag.xml entity.name.tag.localname.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": " ",
"t": "text.xml meta.tag.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "NextTagnotWork",
"t": "text.xml meta.tag.xml entity.other.attribute-name.localname.xml",
"r": {
"dark_plus": "entity.other.attribute-name: #9CDCFE",
"light_plus": "entity.other.attribute-name: #FF0000",
"dark_vs": "entity.other.attribute-name: #9CDCFE",
"light_vs": "entity.other.attribute-name: #FF0000",
"hc_black": "entity.other.attribute-name: #9CDCFE"
}
},
{
"c": "=",
"t": "text.xml meta.tag.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.begin.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "something",
"t": "text.xml meta.tag.xml string.quoted.double.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.end.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": " ",
"t": "text.xml meta.tag.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "Поле",
"t": "text.xml meta.tag.xml entity.other.attribute-name.localname.xml",
"r": {
"dark_plus": "entity.other.attribute-name: #9CDCFE",
"light_plus": "entity.other.attribute-name: #FF0000",
"dark_vs": "entity.other.attribute-name: #9CDCFE",
"light_vs": "entity.other.attribute-name: #FF0000",
"hc_black": "entity.other.attribute-name: #9CDCFE"
}
},
{
"c": "=",
"t": "text.xml meta.tag.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.begin.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "tagnotwork",
"t": "text.xml meta.tag.xml string.quoted.double.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": "\"",
"t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.end.xml",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string.quoted.double.xml: #0000FF",
"dark_vs": "string: #CE9178",
"light_vs": "string.quoted.double.xml: #0000FF",
"hc_black": "string: #CE9178"
}
},
{
"c": ">",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": " ",
"t": "text.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "<",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "WorkFine",
"t": "text.xml meta.tag.xml entity.name.tag.localname.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": "/>",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": " ",
"t": "text.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "<",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "Error_АБВГД",
"t": "text.xml meta.tag.xml entity.name.tag.localname.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": "/>",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": " ",
"t": "text.xml",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "</",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "NoColorWithNonLatinCharacters_АБВ",
"t": "text.xml meta.tag.xml entity.name.tag.localname.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "</",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "WorkFine",
"t": "text.xml meta.tag.xml entity.name.tag.localname.xml",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.xml meta.tag.xml punctuation.definition.tag.xml",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
}
] | extensions/vscode-colorize-tests/test/colorize-results/test-7115_xml.json | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017599458806216717,
0.00017278958694078028,
0.00016938861517701298,
0.0001728645438561216,
0.0000015728701328043826
] |
{
"id": 3,
"code_window": [
"\t- tabs bottom border\n",
"\t- editor title bottom border (when breadcrumbs are disabled, this border will appear\n",
"\tsame as tabs bottom border)\n",
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t- editor group border\n",
"\n",
"\tFinally, we show a drop overlay that should always be on top of everything.\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const path = require('path');
const Mocha = require('mocha');
const minimist = require('minimist');
const [, , ...args] = process.argv;
const opts = minimist(args, {
boolean: 'web',
string: ['f', 'g']
});
const suite = opts['web'] ? 'Browser Smoke Tests' : 'Desktop Smoke Tests';
const options = {
color: true,
timeout: 60000,
slow: 30000,
grep: opts['f'] || opts['g']
};
if (process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
options.reporter = 'mocha-multi-reporters';
options.reporterOptions = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
testsuitesTitle: `${suite} ${process.platform}`,
mochaFile: path.join(process.env.BUILD_ARTIFACTSTAGINGDIRECTORY, `test-results/${process.platform}-${process.arch}-${suite.toLowerCase().replace(/[^\w]/g, '-')}-results.xml`)
}
};
}
const mocha = new Mocha(options);
mocha.addFile('out/main.js');
mocha.run(failures => {
// Indicate location of log files for further diagnosis
if (failures) {
const repoPath = path.join(__dirname, '..', '..', '..');
const logPath = path.join(repoPath, '.build', 'logs', opts.web ? 'smoke-tests-browser' : opts.remote ? 'smoke-tests-remote' : 'smoke-tests');
const logFile = path.join(logPath, 'smoke-test-runner.log');
if (process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
console.log(`
###################################################################
# #
# Logs are attached as build artefact and can be downloaded #
# from the build Summary page (Summary -> Related -> N published) #
# #
# Show playwright traces on: https://trace.playwright.dev/ #
# #
###################################################################
`);
} else {
console.log(`
#############################################
#
# Log files of client & server are stored into
# '${logPath}'.
#
# Logs of the smoke test runner are stored into
# '${logFile}'.
#
#############################################
`);
}
}
process.exit(failures ? -1 : 0);
});
| test/smoke/test/index.js | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017441506497561932,
0.00017163969459943473,
0.0001669694611337036,
0.00017224636394530535,
0.000002719363692449406
] |
{
"id": 4,
"code_window": [
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n",
"\t\t\t7 \tscrollbar\n",
"\t\t\t6\tactive-tab border-bottom\n",
"\t\t\t5\ttabs, title border bottom\n",
"\t\t\t4\tsticky-tab\n",
"\t\t\t2 \tactive/dirty-tab border top\n",
"\t\t\t0 tab\n",
"\n",
"\t##########################################################################################\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t12 drag and drop overlay\n",
"\t\t\t11 \tscrollbar\n",
"\t\t\t10\tactive-tab border-bottom\n",
"\t\t\t9\ttabs, title border bottom\n",
"\t\t\t8\tsticky-tab\n",
"\t\t\t6 \tactive/dirty-tab border top\n",
"\t\t\t5 editor group border\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.9907242655754089,
0.0227066483348608,
0.00016462610801681876,
0.00017083855345845222,
0.145951047539711
] |
{
"id": 4,
"code_window": [
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n",
"\t\t\t7 \tscrollbar\n",
"\t\t\t6\tactive-tab border-bottom\n",
"\t\t\t5\ttabs, title border bottom\n",
"\t\t\t4\tsticky-tab\n",
"\t\t\t2 \tactive/dirty-tab border top\n",
"\t\t\t0 tab\n",
"\n",
"\t##########################################################################################\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t12 drag and drop overlay\n",
"\t\t\t11 \tscrollbar\n",
"\t\t\t10\tactive-tab border-bottom\n",
"\t\t\t9\ttabs, title border bottom\n",
"\t\t\t8\tsticky-tab\n",
"\t\t\t6 \tactive/dirty-tab border top\n",
"\t\t\t5 editor group border\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 26
} | #!/usr/bin/env sh
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
case "$1" in
--inspect*) INSPECT="$1"; shift;;
esac
ROOT="$(dirname "$0")"
"$ROOT/node" ${INSPECT:-} "$ROOT/out/vs/server/main.js" --compatibility=1.63 "$@"
| resources/server/bin/server-old.sh | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00016915894229896367,
0.00016909372061491013,
0.00016902849893085659,
0.00016909372061491013,
6.522168405354023e-8
] |
{
"id": 4,
"code_window": [
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n",
"\t\t\t7 \tscrollbar\n",
"\t\t\t6\tactive-tab border-bottom\n",
"\t\t\t5\ttabs, title border bottom\n",
"\t\t\t4\tsticky-tab\n",
"\t\t\t2 \tactive/dirty-tab border top\n",
"\t\t\t0 tab\n",
"\n",
"\t##########################################################################################\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t12 drag and drop overlay\n",
"\t\t\t11 \tscrollbar\n",
"\t\t\t10\tactive-tab border-bottom\n",
"\t\t\t9\ttabs, title border bottom\n",
"\t\t\t8\tsticky-tab\n",
"\t\t\t6 \tactive/dirty-tab border top\n",
"\t\t\t5 editor group border\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 26
} | "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 });
const path = require("path");
const cp = require("child_process");
const fs = require("fs");
const File = require("vinyl");
const es = require("event-stream");
const filter = require("gulp-filter");
const watcherPath = path.join(__dirname, 'watcher.exe');
function toChangeType(type) {
switch (type) {
case '0': return 'change';
case '1': return 'add';
default: return 'unlink';
}
}
function watch(root) {
const result = es.through();
let child = cp.spawn(watcherPath, [root]);
child.stdout.on('data', function (data) {
const lines = data.toString('utf8').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.length === 0) {
continue;
}
const changeType = line[0];
const changePath = line.substr(2);
// filter as early as possible
if (/^\.git/.test(changePath) || /(^|\\)out($|\\)/.test(changePath)) {
continue;
}
const changePathFull = path.join(root, changePath);
const file = new File({
path: changePathFull,
base: root
});
file.event = toChangeType(changeType);
result.emit('data', file);
}
});
child.stderr.on('data', function (data) {
result.emit('error', data);
});
child.on('exit', function (code) {
result.emit('error', 'Watcher died with code ' + code);
child = null;
});
process.once('SIGTERM', function () { process.exit(0); });
process.once('SIGTERM', function () { process.exit(0); });
process.once('exit', function () { if (child) {
child.kill();
} });
return result;
}
const cache = Object.create(null);
module.exports = function (pattern, options) {
options = options || {};
const cwd = path.normalize(options.cwd || process.cwd());
let watcher = cache[cwd];
if (!watcher) {
watcher = cache[cwd] = watch(cwd);
}
const rebase = !options.base ? es.through() : es.mapSync(function (f) {
f.base = options.base;
return f;
});
return watcher
.pipe(filter(['**', '!.git{,/**}'])) // ignore all things git
.pipe(filter(pattern))
.pipe(es.map(function (file, cb) {
fs.stat(file.path, function (err, stat) {
if (err && err.code === 'ENOENT') {
return cb(undefined, file);
}
if (err) {
return cb();
}
if (!stat.isFile()) {
return cb();
}
fs.readFile(file.path, function (err, contents) {
if (err && err.code === 'ENOENT') {
return cb(undefined, file);
}
if (err) {
return cb();
}
file.contents = contents;
file.stat = stat;
cb(undefined, file);
});
});
}))
.pipe(rebase);
};
| build/lib/watch/watch-win32.js | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017344190564472228,
0.00017156163812614977,
0.00016836289432831109,
0.00017256266437470913,
0.0000016122312445077114
] |
{
"id": 4,
"code_window": [
"\n",
"\tThe following tabls shows the current stacking order:\n",
"\n",
"\t[z-index] \t[kind]\n",
"\t\t\t7 \tscrollbar\n",
"\t\t\t6\tactive-tab border-bottom\n",
"\t\t\t5\ttabs, title border bottom\n",
"\t\t\t4\tsticky-tab\n",
"\t\t\t2 \tactive/dirty-tab border top\n",
"\t\t\t0 tab\n",
"\n",
"\t##########################################################################################\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t12 drag and drop overlay\n",
"\t\t\t11 \tscrollbar\n",
"\t\t\t10\tactive-tab border-bottom\n",
"\t\t\t9\ttabs, title border bottom\n",
"\t\t\t8\tsticky-tab\n",
"\t\t\t6 \tactive/dirty-tab border top\n",
"\t\t\t5 editor group border\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 26
} | {
"name": "csharp",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "0.10.x"
},
"scripts": {
"update-grammar": "node ../node_modules/vscode-grammar-updater/bin dotnet/csharp-tmLanguage grammars/csharp.tmLanguage ./syntaxes/csharp.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "csharp",
"extensions": [
".cs",
".csx",
".cake"
],
"aliases": [
"C#",
"csharp"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "csharp",
"scopeName": "source.cs",
"path": "./syntaxes/csharp.tmLanguage.json"
}
],
"snippets": [
{
"language": "csharp",
"path": "./snippets/csharp.code-snippets"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/csharp/package.json | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017570402997080237,
0.000173756227013655,
0.0001712098892312497,
0.00017326982924714684,
0.0000016632344568279223
] |
{
"id": 5,
"code_window": [
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--tabs-border-bottom-color);\n",
"\twidth: 100%;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 48
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.866355299949646,
0.02298935316503048,
0.00016414333367720246,
0.00017666358326096088,
0.128363236784935
] |
{
"id": 5,
"code_window": [
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--tabs-border-bottom-color);\n",
"\twidth: 100%;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 48
} | /*---------------------------------------------------------------------------------------------
* 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 { Emitter } from 'vs/base/common/event';
import { DisposableStore, dispose, IDisposable, markAsSingleton, MultiDisposeError, ReferenceCollection, toDisposable } from 'vs/base/common/lifecycle';
import { ensureNoDisposablesAreLeakedInTestSuite, throwIfDisposablesAreLeaked } from 'vs/base/test/common/utils';
class Disposable implements IDisposable {
isDisposed = false;
dispose() { this.isDisposed = true; }
}
suite('Lifecycle', () => {
test('dispose single disposable', () => {
const disposable = new Disposable();
assert(!disposable.isDisposed);
dispose(disposable);
assert(disposable.isDisposed);
});
test('dispose disposable array', () => {
const disposable = new Disposable();
const disposable2 = new Disposable();
assert(!disposable.isDisposed);
assert(!disposable2.isDisposed);
dispose([disposable, disposable2]);
assert(disposable.isDisposed);
assert(disposable2.isDisposed);
});
test('dispose disposables', () => {
const disposable = new Disposable();
const disposable2 = new Disposable();
assert(!disposable.isDisposed);
assert(!disposable2.isDisposed);
dispose(disposable);
dispose(disposable2);
assert(disposable.isDisposed);
assert(disposable2.isDisposed);
});
test('dispose array should dispose all if a child throws on dispose', () => {
const disposedValues = new Set<number>();
let thrownError: any;
try {
dispose([
toDisposable(() => { disposedValues.add(1); }),
toDisposable(() => { throw new Error('I am error'); }),
toDisposable(() => { disposedValues.add(3); }),
]);
} catch (e) {
thrownError = e;
}
assert.ok(disposedValues.has(1));
assert.ok(disposedValues.has(3));
assert.strictEqual(thrownError.message, 'I am error');
});
test('dispose array should rethrow composite error if multiple entries throw on dispose', () => {
const disposedValues = new Set<number>();
let thrownError: any;
try {
dispose([
toDisposable(() => { disposedValues.add(1); }),
toDisposable(() => { throw new Error('I am error 1'); }),
toDisposable(() => { throw new Error('I am error 2'); }),
toDisposable(() => { disposedValues.add(4); }),
]);
} catch (e) {
thrownError = e;
}
assert.ok(disposedValues.has(1));
assert.ok(disposedValues.has(4));
assert.ok(thrownError instanceof MultiDisposeError);
assert.strictEqual((thrownError as MultiDisposeError).errors.length, 2);
assert.strictEqual((thrownError as MultiDisposeError).errors[0].message, 'I am error 1');
assert.strictEqual((thrownError as MultiDisposeError).errors[1].message, 'I am error 2');
});
test('Action bar has broken accessibility #100273', function () {
let array = [{ dispose() { } }, { dispose() { } }];
let array2 = dispose(array);
assert.strictEqual(array.length, 2);
assert.strictEqual(array2.length, 0);
assert.ok(array !== array2);
let set = new Set<IDisposable>([{ dispose() { } }, { dispose() { } }]);
let setValues = set.values();
let setValues2 = dispose(setValues);
assert.ok(setValues === setValues2);
});
});
suite('DisposableStore', () => {
test('dispose should call all child disposes even if a child throws on dispose', () => {
const disposedValues = new Set<number>();
const store = new DisposableStore();
store.add(toDisposable(() => { disposedValues.add(1); }));
store.add(toDisposable(() => { throw new Error('I am error'); }));
store.add(toDisposable(() => { disposedValues.add(3); }));
let thrownError: any;
try {
store.dispose();
} catch (e) {
thrownError = e;
}
assert.ok(disposedValues.has(1));
assert.ok(disposedValues.has(3));
assert.strictEqual(thrownError.message, 'I am error');
});
test('dispose should throw composite error if multiple children throw on dispose', () => {
const disposedValues = new Set<number>();
const store = new DisposableStore();
store.add(toDisposable(() => { disposedValues.add(1); }));
store.add(toDisposable(() => { throw new Error('I am error 1'); }));
store.add(toDisposable(() => { throw new Error('I am error 2'); }));
store.add(toDisposable(() => { disposedValues.add(4); }));
let thrownError: any;
try {
store.dispose();
} catch (e) {
thrownError = e;
}
assert.ok(disposedValues.has(1));
assert.ok(disposedValues.has(4));
assert.ok(thrownError instanceof MultiDisposeError);
assert.strictEqual((thrownError as MultiDisposeError).errors.length, 2);
assert.strictEqual((thrownError as MultiDisposeError).errors[0].message, 'I am error 1');
assert.strictEqual((thrownError as MultiDisposeError).errors[1].message, 'I am error 2');
});
});
suite('Reference Collection', () => {
class Collection extends ReferenceCollection<number> {
private _count = 0;
get count() { return this._count; }
protected createReferencedObject(key: string): number { this._count++; return key.length; }
protected destroyReferencedObject(key: string, object: number): void { this._count--; }
}
test('simple', () => {
const collection = new Collection();
const ref1 = collection.acquire('test');
assert(ref1);
assert.strictEqual(ref1.object, 4);
assert.strictEqual(collection.count, 1);
ref1.dispose();
assert.strictEqual(collection.count, 0);
const ref2 = collection.acquire('test');
const ref3 = collection.acquire('test');
assert.strictEqual(ref2.object, ref3.object);
assert.strictEqual(collection.count, 1);
const ref4 = collection.acquire('monkey');
assert.strictEqual(ref4.object, 6);
assert.strictEqual(collection.count, 2);
ref2.dispose();
assert.strictEqual(collection.count, 2);
ref3.dispose();
assert.strictEqual(collection.count, 1);
ref4.dispose();
assert.strictEqual(collection.count, 0);
});
});
function assertThrows(fn: () => void, test: (error: any) => void) {
try {
fn();
assert.fail('Expected function to throw, but it did not.');
} catch (e) {
assert.ok(test(e));
}
}
suite('No Leakage Utilities', () => {
suite('throwIfDisposablesAreLeaked', () => {
test('throws if an event subscription is not cleaned up', () => {
const eventEmitter = new Emitter();
assertThrows(() => {
throwIfDisposablesAreLeaked(() => {
eventEmitter.event(() => {
// noop
});
});
}, e => e.message.indexOf('These disposables were not disposed') !== -1);
});
test('throws if a disposable is not disposed', () => {
assertThrows(() => {
throwIfDisposablesAreLeaked(() => {
new DisposableStore();
});
}, e => e.message.indexOf('These disposables were not disposed') !== -1);
});
test('does not throw if all event subscriptions are cleaned up', () => {
const eventEmitter = new Emitter();
throwIfDisposablesAreLeaked(() => {
eventEmitter.event(() => {
// noop
}).dispose();
});
});
test('does not throw if all disposables are disposed', () => {
// This disposable is reported before the test and not tracked.
toDisposable(() => { });
throwIfDisposablesAreLeaked(() => {
// This disposable is marked as singleton
markAsSingleton(toDisposable(() => { }));
// These disposables are also marked as singleton
const disposableStore = new DisposableStore();
disposableStore.add(toDisposable(() => { }));
markAsSingleton(disposableStore);
toDisposable(() => { }).dispose();
});
});
});
suite('ensureNoDisposablesAreLeakedInTest', () => {
ensureNoDisposablesAreLeakedInTestSuite();
test('Basic Test', () => {
toDisposable(() => { }).dispose();
});
});
});
| src/vs/base/test/common/lifecycle.test.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017620129801798612,
0.00017208021017722785,
0.0001670229685259983,
0.00017230749654117972,
0.000002677835254871752
] |
{
"id": 5,
"code_window": [
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--tabs-border-bottom-color);\n",
"\twidth: 100%;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 48
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution';
KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({
layout: { id: 'com.apple.keylayout.French', lang: 'fr', localizedName: 'French' },
secondaryLayouts: [],
mapping: {
KeyA: ['q', 'Q', '‡', 'Ω', 0],
KeyB: ['b', 'B', 'ß', '∫', 0],
KeyC: ['c', 'C', '©', '¢', 0],
KeyD: ['d', 'D', '∂', '∆', 0],
KeyE: ['e', 'E', 'ê', 'Ê', 0],
KeyF: ['f', 'F', 'ƒ', '·', 0],
KeyG: ['g', 'G', 'fi', 'fl', 0],
KeyH: ['h', 'H', 'Ì', 'Î', 0],
KeyI: ['i', 'I', 'î', 'ï', 0],
KeyJ: ['j', 'J', 'Ï', 'Í', 0],
KeyK: ['k', 'K', 'È', 'Ë', 0],
KeyL: ['l', 'L', '¬', '|', 0],
KeyM: [',', '?', '∞', '¿', 0],
KeyN: ['n', 'N', '~', 'ı', 4],
KeyO: ['o', 'O', 'œ', 'Œ', 0],
KeyP: ['p', 'P', 'π', '∏', 0],
KeyQ: ['a', 'A', 'æ', 'Æ', 0],
KeyR: ['r', 'R', '®', '‚', 0],
KeyS: ['s', 'S', 'Ò', '∑', 0],
KeyT: ['t', 'T', '†', '™', 0],
KeyU: ['u', 'U', 'º', 'ª', 0],
KeyV: ['v', 'V', '◊', '√', 0],
KeyW: ['z', 'Z', 'Â', 'Å', 0],
KeyX: ['x', 'X', '≈', '⁄', 0],
KeyY: ['y', 'Y', 'Ú', 'Ÿ', 0],
KeyZ: ['w', 'W', '‹', '›', 0],
Digit1: ['&', '1', '', '´', 8],
Digit2: ['é', '2', 'ë', '„', 0],
Digit3: ['"', '3', '“', '”', 0],
Digit4: ['\'', '4', '‘', '’', 0],
Digit5: ['(', '5', '{', '[', 0],
Digit6: ['§', '6', '¶', 'å', 0],
Digit7: ['è', '7', '«', '»', 0],
Digit8: ['!', '8', '¡', 'Û', 0],
Digit9: ['ç', '9', 'Ç', 'Á', 0],
Digit0: ['à', '0', 'ø', 'Ø', 0],
Enter: [],
Escape: [],
Backspace: [],
Tab: [],
Space: [' ', ' ', ' ', ' ', 0],
Minus: [')', '°', '}', ']', 0],
Equal: ['-', '_', '—', '–', 0],
BracketLeft: ['^', '¨', 'ô', 'Ô', 3],
BracketRight: ['$', '*', '€', '¥', 0],
Backslash: ['`', '£', '@', '#', 1],
Semicolon: ['m', 'M', 'µ', 'Ó', 0],
Quote: ['ù', '%', 'Ù', '‰', 0],
Backquote: ['<', '>', '≤', '≥', 0],
Comma: [';', '.', '…', '•', 0],
Period: [':', '/', '÷', '\\', 0],
Slash: ['=', '+', '≠', '±', 0],
CapsLock: [],
F1: [],
F2: [],
F3: [],
F4: [],
F5: [],
F6: [],
F7: [],
F8: [],
F9: [],
F10: [],
F11: [],
F12: [],
Insert: [],
Home: [],
PageUp: [],
Delete: [],
End: [],
PageDown: [],
ArrowRight: [],
ArrowLeft: [],
ArrowDown: [],
ArrowUp: [],
NumLock: [],
NumpadDivide: ['/', '/', '/', '/', 0],
NumpadMultiply: ['*', '*', '*', '*', 0],
NumpadSubtract: ['-', '-', '-', '-', 0],
NumpadAdd: ['+', '+', '+', '+', 0],
NumpadEnter: [],
Numpad1: ['1', '1', '1', '1', 0],
Numpad2: ['2', '2', '2', '2', 0],
Numpad3: ['3', '3', '3', '3', 0],
Numpad4: ['4', '4', '4', '4', 0],
Numpad5: ['5', '5', '5', '5', 0],
Numpad6: ['6', '6', '6', '6', 0],
Numpad7: ['7', '7', '7', '7', 0],
Numpad8: ['8', '8', '8', '8', 0],
Numpad9: ['9', '9', '9', '9', 0],
Numpad0: ['0', '0', '0', '0', 0],
NumpadDecimal: [',', '.', ',', '.', 0],
IntlBackslash: ['@', '#', '•', 'Ÿ', 0],
ContextMenu: [],
NumpadEqual: ['=', '=', '=', '=', 0],
F13: [],
F14: [],
F15: [],
F16: [],
F17: [],
F18: [],
F19: [],
F20: [],
AudioVolumeMute: [],
AudioVolumeUp: ['', '=', '', '=', 0],
AudioVolumeDown: [],
NumpadComma: [],
IntlRo: [],
KanaMode: [],
IntlYen: [],
ControlLeft: [],
ShiftLeft: [],
AltLeft: [],
MetaLeft: [],
ControlRight: [],
ShiftRight: [],
AltRight: [],
MetaRight: []
}
});
| src/vs/workbench/services/keybinding/browser/keyboardLayouts/fr.darwin.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.000174225089722313,
0.000169107093825005,
0.00016383733600378036,
0.00016939266060944647,
0.0000027261842205916764
] |
{
"id": 5,
"code_window": [
"\tposition: absolute;\n",
"\tbottom: 0;\n",
"\tleft: 0;\n",
"\tz-index: 5;\n",
"\tpointer-events: none;\n",
"\tbackground-color: var(--tabs-border-bottom-color);\n",
"\twidth: 100%;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 9;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 48
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .inputarea {
min-width: 0;
min-height: 0;
margin: 0;
padding: 0;
position: absolute;
outline: none !important;
resize: none;
border: none;
overflow: hidden;
color: transparent;
background-color: transparent;
}
/*.monaco-editor .inputarea {
position: fixed !important;
width: 800px !important;
height: 500px !important;
top: initial !important;
left: initial !important;
bottom: 0 !important;
right: 0 !important;
color: black !important;
background: white !important;
line-height: 15px !important;
font-size: 14px !important;
}*/
.monaco-editor .inputarea.ime-input {
z-index: 10;
}
| src/vs/editor/browser/controller/textAreaHandler.css | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0009983876952901483,
0.0003755417710635811,
0.00016627166769467294,
0.0001687538460828364,
0.000359604659024626
] |
{
"id": 6,
"code_window": [
"\tflex: 1;\n",
"}\n",
"\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {\n",
"\tz-index: 7;\n",
"\tcursor: default;\n",
"}\n",
"\n",
"/* Tabs Container */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 11;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .part {
box-sizing: border-box;
overflow: hidden;
}
.monaco-workbench .part > .drop-block-overlay.visible {
visibility: visible;
}
.monaco-workbench .part > .drop-block-overlay {
position: absolute;
top: 0;
width: 100%;
height: 100%;
visibility: hidden;
opacity: 0;
z-index: 10;
}
.monaco-workbench .part > .title {
display: none; /* Parts have to opt in to show title area */
}
.monaco-workbench .part > .title {
height: 35px;
display: flex;
box-sizing: border-box;
overflow: hidden;
}
.monaco-workbench .part > .title {
padding-left: 8px;
padding-right: 8px;
}
.monaco-workbench .part > .title > .title-label {
line-height: 35px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.monaco-workbench .part > .title > .title-label {
padding-left: 12px;
}
.monaco-workbench .part > .title > .title-label h2 {
font-size: 11px;
cursor: default;
font-weight: normal;
margin: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.monaco-workbench .part > .title > .title-label a {
text-decoration: none;
font-size: 13px;
cursor: default;
}
.monaco-workbench .part > .title > .title-actions {
height: 35px;
flex: 1;
padding-left: 5px;
}
.monaco-workbench .part > .title > .title-actions .action-label {
display: block;
background-size: 16px;
background-position: center center;
background-repeat: no-repeat;
}
.monaco-workbench .part > .title > .title-actions .action-label .label {
display: none;
}
.monaco-workbench .part > .title > .title-actions .action-label.codicon {
color: inherit;
}
.monaco-workbench .part > .content {
font-size: 13px;
}
.monaco-workbench .part > .content > .monaco-progress-container,
.monaco-workbench .part.editor > .content .monaco-progress-container {
position: absolute;
left: 0;
top: 33px; /* at the bottom of the 35px height title container */
z-index: 5; /* on top of things */
height: 2px;
}
.monaco-workbench .part > .content > .monaco-progress-container .progress-bit,
.monaco-workbench
.part.editor
> .content
.monaco-progress-container
.progress-bit {
height: 2px;
}
| src/vs/workbench/browser/media/part.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0018580086762085557,
0.000852548168040812,
0.0001646265882300213,
0.0006817259709350765,
0.0005058399983681738
] |
{
"id": 6,
"code_window": [
"\tflex: 1;\n",
"}\n",
"\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {\n",
"\tz-index: 7;\n",
"\tcursor: default;\n",
"}\n",
"\n",
"/* Tabs Container */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 11;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 60
} | @echo off
setlocal
SET VSCODE_PATH=%~dp0..\..\..\..
FOR /F "tokens=* USEBACKQ" %%g IN (`where /r "%VSCODE_PATH%\.build\node" node.exe`) do (SET "NODE=%%g")
call "%NODE%" "%VSCODE_PATH%\out\vs\server\cli.js" "Code Server - Dev" "" "" "code.cmd" %*
endlocal
| resources/server/bin-dev/remote-cli/code.cmd | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00016775619587861001,
0.00016775619587861001,
0.00016775619587861001,
0.00016775619587861001,
0
] |
{
"id": 6,
"code_window": [
"\tflex: 1;\n",
"}\n",
"\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {\n",
"\tz-index: 7;\n",
"\tcursor: default;\n",
"}\n",
"\n",
"/* Tabs Container */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 11;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Code } from './code';
import { ILocalizedStrings, ILocaleInfo } from './driver';
export class Localization {
constructor(private code: Code) { }
async getLocaleInfo(): Promise<ILocaleInfo> {
return this.code.getLocaleInfo();
}
async getLocalizedStrings(): Promise<ILocalizedStrings> {
return this.code.getLocalizedStrings();
}
}
| test/automation/src/localization.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0001760187733452767,
0.00017452187603339553,
0.00017302497872151434,
0.00017452187603339553,
0.0000014968973118811846
] |
{
"id": 6,
"code_window": [
"\tflex: 1;\n",
"}\n",
"\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {\n",
"\tz-index: 7;\n",
"\tcursor: default;\n",
"}\n",
"\n",
"/* Tabs Container */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 11;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { timeout } from 'vs/base/common/async';
import { consumeReadable, consumeStream, isReadableBufferedStream, isReadableStream, listenStream, newWriteableStream, peekReadable, peekStream, prefixedReadable, prefixedStream, Readable, ReadableStream, toReadable, toStream, transform } from 'vs/base/common/stream';
suite('Stream', () => {
test('isReadableStream', () => {
assert.ok(!isReadableStream(Object.create(null)));
assert.ok(isReadableStream(newWriteableStream(d => d)));
});
test('isReadableBufferedStream', async () => {
assert.ok(!isReadableBufferedStream(Object.create(null)));
const stream = newWriteableStream(d => d);
stream.end();
const bufferedStream = await peekStream(stream, 1);
assert.ok(isReadableBufferedStream(bufferedStream));
});
test('WriteableStream - basics', () => {
const stream = newWriteableStream<string>(strings => strings.join());
let error = false;
stream.on('error', e => {
error = true;
});
let end = false;
stream.on('end', () => {
end = true;
});
stream.write('Hello');
const chunks: string[] = [];
stream.on('data', data => {
chunks.push(data);
});
assert.strictEqual(chunks[0], 'Hello');
stream.write('World');
assert.strictEqual(chunks[1], 'World');
assert.strictEqual(error, false);
assert.strictEqual(end, false);
stream.pause();
stream.write('1');
stream.write('2');
stream.write('3');
assert.strictEqual(chunks.length, 2);
stream.resume();
assert.strictEqual(chunks.length, 3);
assert.strictEqual(chunks[2], '1,2,3');
stream.error(new Error());
assert.strictEqual(error, true);
error = false;
stream.error(new Error());
assert.strictEqual(error, true);
stream.end('Final Bit');
assert.strictEqual(chunks.length, 4);
assert.strictEqual(chunks[3], 'Final Bit');
assert.strictEqual(end, true);
stream.destroy();
stream.write('Unexpected');
assert.strictEqual(chunks.length, 4);
});
test('WriteableStream - end with empty string works', async () => {
const reducer = (strings: string[]) => strings.length > 0 ? strings.join() : 'error';
const stream = newWriteableStream<string>(reducer);
stream.end('');
const result = await consumeStream(stream, reducer);
assert.strictEqual(result, '');
});
test('WriteableStream - end with error works', async () => {
const reducer = (errors: Error[]) => errors[0];
const stream = newWriteableStream<Error>(reducer);
stream.end(new Error('error'));
const result = await consumeStream(stream, reducer);
assert.ok(result instanceof Error);
});
test('WriteableStream - removeListener', () => {
const stream = newWriteableStream<string>(strings => strings.join());
let error = false;
const errorListener = (e: Error) => {
error = true;
};
stream.on('error', errorListener);
let data = false;
const dataListener = () => {
data = true;
};
stream.on('data', dataListener);
stream.write('Hello');
assert.strictEqual(data, true);
data = false;
stream.removeListener('data', dataListener);
stream.write('World');
assert.strictEqual(data, false);
stream.error(new Error());
assert.strictEqual(error, true);
error = false;
stream.removeListener('error', errorListener);
// always leave at least one error listener to streams to avoid unexpected errors during test running
stream.on('error', () => { });
stream.error(new Error());
assert.strictEqual(error, false);
});
test('WriteableStream - highWaterMark', async () => {
const stream = newWriteableStream<string>(strings => strings.join(), { highWaterMark: 3 });
let res = stream.write('1');
assert.ok(!res);
res = stream.write('2');
assert.ok(!res);
res = stream.write('3');
assert.ok(!res);
let promise1 = stream.write('4');
assert.ok(promise1 instanceof Promise);
let promise2 = stream.write('5');
assert.ok(promise2 instanceof Promise);
let drained1 = false;
(async () => {
await promise1;
drained1 = true;
})();
let drained2 = false;
(async () => {
await promise2;
drained2 = true;
})();
let data: string | undefined = undefined;
stream.on('data', chunk => {
data = chunk;
});
assert.ok(data);
await timeout(0);
assert.strictEqual(drained1, true);
assert.strictEqual(drained2, true);
});
test('consumeReadable', () => {
const readable = arrayToReadable(['1', '2', '3', '4', '5']);
const consumed = consumeReadable(readable, strings => strings.join());
assert.strictEqual(consumed, '1,2,3,4,5');
});
test('peekReadable', () => {
for (let i = 0; i < 5; i++) {
const readable = arrayToReadable(['1', '2', '3', '4', '5']);
const consumedOrReadable = peekReadable(readable, strings => strings.join(), i);
if (typeof consumedOrReadable === 'string') {
assert.fail('Unexpected result');
} else {
const consumed = consumeReadable(consumedOrReadable, strings => strings.join());
assert.strictEqual(consumed, '1,2,3,4,5');
}
}
let readable = arrayToReadable(['1', '2', '3', '4', '5']);
let consumedOrReadable = peekReadable(readable, strings => strings.join(), 5);
assert.strictEqual(consumedOrReadable, '1,2,3,4,5');
readable = arrayToReadable(['1', '2', '3', '4', '5']);
consumedOrReadable = peekReadable(readable, strings => strings.join(), 6);
assert.strictEqual(consumedOrReadable, '1,2,3,4,5');
});
test('peekReadable - error handling', async () => {
// 0 Chunks
let stream = newWriteableStream(data => data);
let error: Error | undefined = undefined;
let promise = (async () => {
try {
await peekStream(stream, 1);
} catch (err) {
error = err;
}
})();
stream.error(new Error());
await promise;
assert.ok(error);
// 1 Chunk
stream = newWriteableStream(data => data);
error = undefined;
promise = (async () => {
try {
await peekStream(stream, 1);
} catch (err) {
error = err;
}
})();
stream.write('foo');
stream.error(new Error());
await promise;
assert.ok(error);
// 2 Chunks
stream = newWriteableStream(data => data);
error = undefined;
promise = (async () => {
try {
await peekStream(stream, 1);
} catch (err) {
error = err;
}
})();
stream.write('foo');
stream.write('bar');
stream.error(new Error());
await promise;
assert.ok(!error);
stream.on('error', err => error = err);
stream.on('data', chunk => { });
assert.ok(error);
});
function arrayToReadable<T>(array: T[]): Readable<T> {
return {
read: () => array.shift() || null
};
}
function readableToStream(readable: Readable<string>): ReadableStream<string> {
const stream = newWriteableStream<string>(strings => strings.join());
// Simulate async behavior
setTimeout(() => {
let chunk: string | null = null;
while ((chunk = readable.read()) !== null) {
stream.write(chunk);
}
stream.end();
}, 0);
return stream;
}
test('consumeStream', async () => {
const stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5']));
const consumed = await consumeStream(stream, strings => strings.join());
assert.strictEqual(consumed, '1,2,3,4,5');
});
test('consumeStream - without reducer', async () => {
const stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5']));
const consumed = await consumeStream(stream);
assert.strictEqual(consumed, undefined);
});
test('consumeStream - without reducer and error', async () => {
const stream = newWriteableStream<string>(strings => strings.join());
stream.error(new Error());
const consumed = await consumeStream(stream);
assert.strictEqual(consumed, undefined);
});
test('listenStream', () => {
const stream = newWriteableStream<string>(strings => strings.join());
let error = false;
let end = false;
let data = '';
listenStream(stream, {
onData: d => {
data = d;
},
onError: e => {
error = true;
},
onEnd: () => {
end = true;
}
});
stream.write('Hello');
assert.strictEqual(data, 'Hello');
stream.write('World');
assert.strictEqual(data, 'World');
assert.strictEqual(error, false);
assert.strictEqual(end, false);
stream.error(new Error());
assert.strictEqual(error, true);
stream.end('Final Bit');
assert.strictEqual(end, true);
});
test('listenStream - dispose', () => {
const stream = newWriteableStream<string>(strings => strings.join());
let error = false;
let end = false;
let data = '';
const disposable = listenStream(stream, {
onData: d => {
data = d;
},
onError: e => {
error = true;
},
onEnd: () => {
end = true;
}
});
disposable.dispose();
stream.write('Hello');
assert.strictEqual(data, '');
stream.write('World');
assert.strictEqual(data, '');
stream.error(new Error());
assert.strictEqual(error, false);
stream.end('Final Bit');
assert.strictEqual(end, false);
});
test('peekStream', async () => {
for (let i = 0; i < 5; i++) {
const stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5']));
const result = await peekStream(stream, i);
assert.strictEqual(stream, result.stream);
if (result.ended) {
assert.fail('Unexpected result, stream should not have ended yet');
} else {
assert.strictEqual(result.buffer.length, i + 1, `maxChunks: ${i}`);
const additionalResult: string[] = [];
await consumeStream(stream, strings => {
additionalResult.push(...strings);
return strings.join();
});
assert.strictEqual([...result.buffer, ...additionalResult].join(), '1,2,3,4,5');
}
}
let stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5']));
let result = await peekStream(stream, 5);
assert.strictEqual(stream, result.stream);
assert.strictEqual(result.buffer.join(), '1,2,3,4,5');
assert.strictEqual(result.ended, true);
stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5']));
result = await peekStream(stream, 6);
assert.strictEqual(stream, result.stream);
assert.strictEqual(result.buffer.join(), '1,2,3,4,5');
assert.strictEqual(result.ended, true);
});
test('toStream', async () => {
const stream = toStream('1,2,3,4,5', strings => strings.join());
const consumed = await consumeStream(stream, strings => strings.join());
assert.strictEqual(consumed, '1,2,3,4,5');
});
test('toReadable', async () => {
const readable = toReadable('1,2,3,4,5');
const consumed = consumeReadable(readable, strings => strings.join());
assert.strictEqual(consumed, '1,2,3,4,5');
});
test('transform', async () => {
const source = newWriteableStream<string>(strings => strings.join());
const result = transform(source, { data: string => string + string }, strings => strings.join());
// Simulate async behavior
setTimeout(() => {
source.write('1');
source.write('2');
source.write('3');
source.write('4');
source.end('5');
}, 0);
const consumed = await consumeStream(result, strings => strings.join());
assert.strictEqual(consumed, '11,22,33,44,55');
});
test('events are delivered even if a listener is removed during delivery', () => {
const stream = newWriteableStream<string>(strings => strings.join());
let listener1Called = false;
let listener2Called = false;
const listener1 = () => { stream.removeListener('end', listener1); listener1Called = true; };
const listener2 = () => { listener2Called = true; };
stream.on('end', listener1);
stream.on('end', listener2);
stream.on('data', () => { });
stream.end('');
assert.strictEqual(listener1Called, true);
assert.strictEqual(listener2Called, true);
});
test('prefixedReadable', () => {
// Basic
let readable = prefixedReadable('1,2', arrayToReadable(['3', '4', '5']), val => val.join(','));
assert.strictEqual(consumeReadable(readable, val => val.join(',')), '1,2,3,4,5');
// Empty
readable = prefixedReadable('empty', arrayToReadable<string>([]), val => val.join(','));
assert.strictEqual(consumeReadable(readable, val => val.join(',')), 'empty');
});
test('prefixedStream', async () => {
// Basic
let stream = newWriteableStream<string>(strings => strings.join());
stream.write('3');
stream.write('4');
stream.write('5');
stream.end();
let prefixStream = prefixedStream<string>('1,2', stream, val => val.join(','));
assert.strictEqual(await consumeStream(prefixStream, val => val.join(',')), '1,2,3,4,5');
// Empty
stream = newWriteableStream<string>(strings => strings.join());
stream.end();
prefixStream = prefixedStream<string>('1,2', stream, val => val.join(','));
assert.strictEqual(await consumeStream(prefixStream, val => val.join(',')), '1,2');
// Error
stream = newWriteableStream<string>(strings => strings.join());
stream.error(new Error('fail'));
prefixStream = prefixedStream<string>('error', stream, val => val.join(','));
let error;
try {
await consumeStream(prefixStream, val => val.join(','));
} catch (e) {
error = e;
}
assert.ok(error);
});
});
| src/vs/base/test/common/stream.test.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017601254512555897,
0.0001715484104352072,
0.00016430886171292514,
0.00017186019977089018,
0.000002335907311135088
] |
{
"id": 7,
"code_window": [
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {\n",
"\n",
"\t/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */\n",
"\tposition: sticky;\n",
"\tz-index: 4;\n",
"\n",
"\t/** Sticky compact/shrink tabs are even and never grow */\n",
"\tflex-basis: 0;\n",
"\tflex-grow: 0;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 8;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 138
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.9978912472724915,
0.029617102816700935,
0.00016089246491901577,
0.0025856047868728638,
0.14713342487812042
] |
{
"id": 7,
"code_window": [
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {\n",
"\n",
"\t/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */\n",
"\tposition: sticky;\n",
"\tz-index: 4;\n",
"\n",
"\t/** Sticky compact/shrink tabs are even and never grow */\n",
"\tflex-basis: 0;\n",
"\tflex-grow: 0;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 8;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 138
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IExtensionGalleryService, IExtensionManagementService, IGlobalExtensionEnablementService, InstallOperation } from 'vs/platform/extensionManagement/common/extensionManagement';
import { areSameExtensions, getExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { IExtensionStorageService } from 'vs/platform/extensionManagement/common/extensionStorage';
import { ExtensionType } from 'vs/platform/extensions/common/extensions';
import { ILogService } from 'vs/platform/log/common/log';
/**
* Migrates the installed unsupported nightly extension to a supported pre-release extension. It includes following:
* - Uninstall the Unsupported extension
* - Install (with optional storage migration) the Pre-release extension only if
* - the extension is not installed
* - or it is a release version and the unsupported extension is enabled.
*/
export async function migrateUnsupportedExtensions(extensionManagementService: IExtensionManagementService, galleryService: IExtensionGalleryService, extensionStorageService: IExtensionStorageService, extensionEnablementService: IGlobalExtensionEnablementService, logService: ILogService): Promise<void> {
try {
const extensionsControlManifest = await extensionManagementService.getExtensionsControlManifest();
if (!extensionsControlManifest.unsupportedPreReleaseExtensions) {
return;
}
const installed = await extensionManagementService.getInstalled(ExtensionType.User);
for (const [unsupportedExtensionId, { id: preReleaseExtensionId, migrateStorage }] of Object.entries(extensionsControlManifest.unsupportedPreReleaseExtensions)) {
const unsupportedExtension = installed.find(i => areSameExtensions(i.identifier, { id: unsupportedExtensionId }));
// Unsupported Extension is not installed
if (!unsupportedExtension) {
continue;
}
const gallery = await galleryService.getCompatibleExtension({ id: preReleaseExtensionId }, true, await extensionManagementService.getTargetPlatform());
if (!gallery) {
logService.info(`Skipping migrating '${unsupportedExtension.identifier.id}' extension because, the comaptible target '${preReleaseExtensionId}' extension is not found`);
continue;
}
try {
logService.info(`Migrating '${unsupportedExtension.identifier.id}' extension to '${preReleaseExtensionId}' extension...`);
const isUnsupportedExtensionEnabled = !extensionEnablementService.getDisabledExtensions().some(e => areSameExtensions(e, unsupportedExtension.identifier));
await extensionManagementService.uninstall(unsupportedExtension);
logService.info(`Uninstalled the unsupported extension '${unsupportedExtension.identifier.id}'`);
let preReleaseExtension = installed.find(i => areSameExtensions(i.identifier, { id: preReleaseExtensionId }));
if (!preReleaseExtension || (!preReleaseExtension.isPreReleaseVersion && isUnsupportedExtensionEnabled)) {
preReleaseExtension = await extensionManagementService.installFromGallery(gallery, { installPreReleaseVersion: true, isMachineScoped: unsupportedExtension.isMachineScoped, operation: InstallOperation.Migrate });
logService.info(`Installed the pre-release extension '${preReleaseExtension.identifier.id}'`);
if (!isUnsupportedExtensionEnabled) {
await extensionEnablementService.disableExtension(preReleaseExtension.identifier);
logService.info(`Disabled the pre-release extension '${preReleaseExtension.identifier.id}' because the unsupported extension '${unsupportedExtension.identifier.id}' is disabled`);
}
if (migrateStorage) {
extensionStorageService.addToMigrationList(getExtensionId(unsupportedExtension.manifest.publisher, unsupportedExtension.manifest.name), getExtensionId(preReleaseExtension.manifest.publisher, preReleaseExtension.manifest.name));
logService.info(`Added pre-release extension to the storage migration list`);
}
}
logService.info(`Migrated '${unsupportedExtension.identifier.id}' extension to '${preReleaseExtensionId}' extension.`);
} catch (error) {
logService.error(error);
}
}
} catch (error) {
logService.error(error);
}
}
| src/vs/platform/extensionManagement/common/unsupportedExtensionsMigration.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00017059619131032377,
0.00016802507161628455,
0.00016479258192703128,
0.00016819810844026506,
0.0000019193435036868323
] |
{
"id": 7,
"code_window": [
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {\n",
"\n",
"\t/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */\n",
"\tposition: sticky;\n",
"\tz-index: 4;\n",
"\n",
"\t/** Sticky compact/shrink tabs are even and never grow */\n",
"\tflex-basis: 0;\n",
"\tflex-grow: 0;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 8;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 138
} | @echo off
setlocal
title VSCode Dev
pushd %~dp0\..
:: Node modules
if not exist node_modules call .\scripts\npm.bat install
:: Get electron
node .\node_modules\gulp\bin\gulp.js electron
:: Build
if not exist out node .\node_modules\gulp\bin\gulp.js compile
:: Configuration
set NODE_ENV=development
call echo %%LINE:rem +=%%
popd
endlocal | extensions/vscode-colorize-tests/test/colorize-fixtures/test.bat | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.0001690726785454899,
0.0001681991998339072,
0.00016751387738622725,
0.0001680110435700044,
6.501370535261231e-7
] |
{
"id": 7,
"code_window": [
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {\n",
"\n",
"\t/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */\n",
"\tposition: sticky;\n",
"\tz-index: 4;\n",
"\n",
"\t/** Sticky compact/shrink tabs are even and never grow */\n",
"\tflex-basis: 0;\n",
"\tflex-grow: 0;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 8;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"edit_start_line_idx": 138
} | /*---------------------------------------------------------------------------------------------
* 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/runtimeExtensionsEditor';
import * as nls from 'vs/nls';
import { Action, IAction, Separator } from 'vs/base/common/actions';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IExtensionsWorkbenchService, IExtension } from 'vs/workbench/contrib/extensions/common/extensions';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IExtensionService, IExtensionsStatus, IExtensionHostProfile, ExtensionRunningLocation } from 'vs/workbench/services/extensions/common/extensions';
import { IListVirtualDelegate, IListRenderer } from 'vs/base/browser/ui/list/list';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
import { append, $, Dimension, clearNode, addDisposableListener } from 'vs/base/browser/dom';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { EnablementState } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { memoize } from 'vs/base/common/decorators';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ILabelService } from 'vs/platform/label/common/label';
import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { editorBackground } from 'vs/platform/theme/common/colorRegistry';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { RuntimeExtensionsInput } from 'vs/workbench/contrib/extensions/common/runtimeExtensionsInput';
import { Action2 } from 'vs/platform/actions/common/actions';
import { CATEGORIES } from 'vs/workbench/common/actions';
import { DefaultIconPath } from 'vs/platform/extensionManagement/common/extensionManagement';
interface IExtensionProfileInformation {
/**
* segment when the extension was running.
* 2*i = segment start time
* 2*i+1 = segment end time
*/
segments: number[];
/**
* total time when the extension was running.
* (sum of all segment lengths).
*/
totalTime: number;
}
export interface IRuntimeExtension {
originalIndex: number;
description: IExtensionDescription;
marketplaceInfo: IExtension | undefined;
status: IExtensionsStatus;
profileInfo?: IExtensionProfileInformation;
unresponsiveProfile?: IExtensionHostProfile;
}
export abstract class AbstractRuntimeExtensionsEditor extends EditorPane {
public static readonly ID: string = 'workbench.editor.runtimeExtensions';
private _list: WorkbenchList<IRuntimeExtension> | null;
private _elements: IRuntimeExtension[] | null;
private _updateSoon: RunOnceScheduler;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IContextKeyService contextKeyService: IContextKeyService,
@IExtensionsWorkbenchService private readonly _extensionsWorkbenchService: IExtensionsWorkbenchService,
@IExtensionService private readonly _extensionService: IExtensionService,
@INotificationService private readonly _notificationService: INotificationService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IInstantiationService protected readonly _instantiationService: IInstantiationService,
@IStorageService storageService: IStorageService,
@ILabelService private readonly _labelService: ILabelService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
) {
super(AbstractRuntimeExtensionsEditor.ID, telemetryService, themeService, storageService);
this._list = null;
this._elements = null;
this._updateSoon = this._register(new RunOnceScheduler(() => this._updateExtensions(), 200));
this._register(this._extensionService.onDidChangeExtensionsStatus(() => this._updateSoon.schedule()));
this._updateExtensions();
}
protected async _updateExtensions(): Promise<void> {
this._elements = await this._resolveExtensions();
if (this._list) {
this._list.splice(0, this._list.length, this._elements);
}
}
private async _resolveExtensions(): Promise<IRuntimeExtension[]> {
// We only deal with extensions with source code!
const extensionsDescriptions = (await this._extensionService.getExtensions()).filter((extension) => {
return Boolean(extension.main) || Boolean(extension.browser);
});
let marketplaceMap: { [id: string]: IExtension; } = Object.create(null);
const marketPlaceExtensions = await this._extensionsWorkbenchService.queryLocal();
for (let extension of marketPlaceExtensions) {
marketplaceMap[ExtensionIdentifier.toKey(extension.identifier.id)] = extension;
}
let statusMap = this._extensionService.getExtensionsStatus();
// group profile segments by extension
let segments: { [id: string]: number[]; } = Object.create(null);
const profileInfo = this._getProfileInfo();
if (profileInfo) {
let currentStartTime = profileInfo.startTime;
for (let i = 0, len = profileInfo.deltas.length; i < len; i++) {
const id = profileInfo.ids[i];
const delta = profileInfo.deltas[i];
let extensionSegments = segments[ExtensionIdentifier.toKey(id)];
if (!extensionSegments) {
extensionSegments = [];
segments[ExtensionIdentifier.toKey(id)] = extensionSegments;
}
extensionSegments.push(currentStartTime);
currentStartTime = currentStartTime + delta;
extensionSegments.push(currentStartTime);
}
}
let result: IRuntimeExtension[] = [];
for (let i = 0, len = extensionsDescriptions.length; i < len; i++) {
const extensionDescription = extensionsDescriptions[i];
let extProfileInfo: IExtensionProfileInformation | null = null;
if (profileInfo) {
let extensionSegments = segments[ExtensionIdentifier.toKey(extensionDescription.identifier)] || [];
let extensionTotalTime = 0;
for (let j = 0, lenJ = extensionSegments.length / 2; j < lenJ; j++) {
const startTime = extensionSegments[2 * j];
const endTime = extensionSegments[2 * j + 1];
extensionTotalTime += (endTime - startTime);
}
extProfileInfo = {
segments: extensionSegments,
totalTime: extensionTotalTime
};
}
result[i] = {
originalIndex: i,
description: extensionDescription,
marketplaceInfo: marketplaceMap[ExtensionIdentifier.toKey(extensionDescription.identifier)],
status: statusMap[extensionDescription.identifier.value],
profileInfo: extProfileInfo || undefined,
unresponsiveProfile: this._getUnresponsiveProfile(extensionDescription.identifier)
};
}
result = result.filter(element => element.status.activationTimes);
// bubble up extensions that have caused slowness
const isUnresponsive = (extension: IRuntimeExtension): boolean =>
extension.unresponsiveProfile === profileInfo;
const profileTime = (extension: IRuntimeExtension): number =>
extension.profileInfo?.totalTime ?? 0;
const activationTime = (extension: IRuntimeExtension): number =>
(extension.status.activationTimes?.codeLoadingTime ?? 0) +
(extension.status.activationTimes?.activateCallTime ?? 0);
result = result.sort((a, b) => {
if (isUnresponsive(a) || isUnresponsive(b)) {
return +isUnresponsive(b) - +isUnresponsive(a);
} else if (profileTime(a) || profileTime(b)) {
return profileTime(b) - profileTime(a);
} else if (activationTime(a) || activationTime(b)) {
return activationTime(b) - activationTime(a);
}
return a.originalIndex - b.originalIndex;
});
return result;
}
protected createEditor(parent: HTMLElement): void {
parent.classList.add('runtime-extensions-editor');
const TEMPLATE_ID = 'runtimeExtensionElementTemplate';
const delegate = new class implements IListVirtualDelegate<IRuntimeExtension>{
getHeight(element: IRuntimeExtension): number {
return 62;
}
getTemplateId(element: IRuntimeExtension): string {
return TEMPLATE_ID;
}
};
interface IRuntimeExtensionTemplateData {
root: HTMLElement;
element: HTMLElement;
icon: HTMLImageElement;
name: HTMLElement;
version: HTMLElement;
msgContainer: HTMLElement;
actionbar: ActionBar;
activationTime: HTMLElement;
profileTime: HTMLElement;
disposables: IDisposable[];
elementDisposables: IDisposable[];
}
const renderer: IListRenderer<IRuntimeExtension, IRuntimeExtensionTemplateData> = {
templateId: TEMPLATE_ID,
renderTemplate: (root: HTMLElement): IRuntimeExtensionTemplateData => {
const element = append(root, $('.extension'));
const iconContainer = append(element, $('.icon-container'));
const icon = append(iconContainer, $<HTMLImageElement>('img.icon'));
const desc = append(element, $('div.desc'));
const headerContainer = append(desc, $('.header-container'));
const header = append(headerContainer, $('.header'));
const name = append(header, $('div.name'));
const version = append(header, $('span.version'));
const msgContainer = append(desc, $('div.msg'));
const actionbar = new ActionBar(desc, { animated: false });
actionbar.onDidRun(({ error }) => error && this._notificationService.error(error));
const timeContainer = append(element, $('.time'));
const activationTime = append(timeContainer, $('div.activation-time'));
const profileTime = append(timeContainer, $('div.profile-time'));
const disposables = [actionbar];
return {
root,
element,
icon,
name,
version,
actionbar,
activationTime,
profileTime,
msgContainer,
disposables,
elementDisposables: [],
};
},
renderElement: (element: IRuntimeExtension, index: number, data: IRuntimeExtensionTemplateData): void => {
data.elementDisposables = dispose(data.elementDisposables);
data.root.classList.toggle('odd', index % 2 === 1);
data.elementDisposables.push(addDisposableListener(data.icon, 'error', () => data.icon.src = element.marketplaceInfo?.iconUrlFallback || DefaultIconPath, { once: true }));
data.icon.src = element.marketplaceInfo?.iconUrl || DefaultIconPath;
if (!data.icon.complete) {
data.icon.style.visibility = 'hidden';
data.icon.onload = () => data.icon.style.visibility = 'inherit';
} else {
data.icon.style.visibility = 'inherit';
}
data.name.textContent = (element.marketplaceInfo?.displayName || element.description.identifier.value).substr(0, 50);
data.version.textContent = element.description.version;
const activationTimes = element.status.activationTimes!;
let syncTime = activationTimes.codeLoadingTime + activationTimes.activateCallTime;
data.activationTime.textContent = activationTimes.activationReason.startup ? `Startup Activation: ${syncTime}ms` : `Activation: ${syncTime}ms`;
data.actionbar.clear();
const slowExtensionAction = this._createSlowExtensionAction(element);
if (slowExtensionAction) {
data.actionbar.push(slowExtensionAction, { icon: true, label: true });
}
if (isNonEmptyArray(element.status.runtimeErrors)) {
const reportExtensionIssueAction = this._createReportExtensionIssueAction(element);
if (reportExtensionIssueAction) {
data.actionbar.push(reportExtensionIssueAction, { icon: true, label: true });
}
}
let title: string;
const activationId = activationTimes.activationReason.extensionId.value;
const activationEvent = activationTimes.activationReason.activationEvent;
if (activationEvent === '*') {
title = nls.localize({
key: 'starActivation',
comment: [
'{0} will be an extension identifier'
]
}, "Activated by {0} on start-up", activationId);
} else if (/^workspaceContains:/.test(activationEvent)) {
let fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
title = nls.localize({
key: 'workspaceContainsGlobActivation',
comment: [
'{0} will be a glob pattern',
'{1} will be an extension identifier'
]
}, "Activated by {1} because a file matching {0} exists in your workspace", fileNameOrGlob, activationId);
} else {
title = nls.localize({
key: 'workspaceContainsFileActivation',
comment: [
'{0} will be a file name',
'{1} will be an extension identifier'
]
}, "Activated by {1} because file {0} exists in your workspace", fileNameOrGlob, activationId);
}
} else if (/^workspaceContainsTimeout:/.test(activationEvent)) {
const glob = activationEvent.substr('workspaceContainsTimeout:'.length);
title = nls.localize({
key: 'workspaceContainsTimeout',
comment: [
'{0} will be a glob pattern',
'{1} will be an extension identifier'
]
}, "Activated by {1} because searching for {0} took too long", glob, activationId);
} else if (activationEvent === 'onStartupFinished') {
title = nls.localize({
key: 'startupFinishedActivation',
comment: [
'This refers to an extension. {0} will be an activation event.'
]
}, "Activated by {0} after start-up finished", activationId);
} else if (/^onLanguage:/.test(activationEvent)) {
let language = activationEvent.substr('onLanguage:'.length);
title = nls.localize('languageActivation', "Activated by {1} because you opened a {0} file", language, activationId);
} else {
title = nls.localize({
key: 'workspaceGenericActivation',
comment: [
'{0} will be an activation event, like e.g. \'language:typescript\', \'debug\', etc.',
'{1} will be an extension identifier'
]
}, "Activated by {1} on {0}", activationEvent, activationId);
}
data.activationTime.title = title;
clearNode(data.msgContainer);
if (this._getUnresponsiveProfile(element.description.identifier)) {
const el = $('span', undefined, ...renderLabelWithIcons(` $(alert) Unresponsive`));
el.title = nls.localize('unresponsive.title', "Extension has caused the extension host to freeze.");
data.msgContainer.appendChild(el);
}
if (isNonEmptyArray(element.status.runtimeErrors)) {
const el = $('span', undefined, ...renderLabelWithIcons(`$(bug) ${nls.localize('errors', "{0} uncaught errors", element.status.runtimeErrors.length)}`));
data.msgContainer.appendChild(el);
}
if (element.status.messages && element.status.messages.length > 0) {
const el = $('span', undefined, ...renderLabelWithIcons(`$(alert) ${element.status.messages[0].message}`));
data.msgContainer.appendChild(el);
}
let extraLabel: string | null = null;
if (element.description.extensionLocation.scheme === Schemas.vscodeRemote) {
const hostLabel = this._labelService.getHostLabel(Schemas.vscodeRemote, this._environmentService.remoteAuthority);
if (hostLabel) {
extraLabel = `$(remote) ${hostLabel}`;
} else {
extraLabel = `$(remote) ${element.description.extensionLocation.authority}`;
}
} else if (element.status.runningLocation === ExtensionRunningLocation.LocalWebWorker) {
extraLabel = `$(globe) web worker`;
}
if (extraLabel) {
const el = $('span', undefined, ...renderLabelWithIcons(extraLabel));
data.msgContainer.appendChild(el);
}
if (element.profileInfo) {
data.profileTime.textContent = `Profile: ${(element.profileInfo.totalTime / 1000).toFixed(2)}ms`;
} else {
data.profileTime.textContent = '';
}
},
disposeTemplate: (data: IRuntimeExtensionTemplateData): void => {
data.disposables = dispose(data.disposables);
}
};
this._list = <WorkbenchList<IRuntimeExtension>>this._instantiationService.createInstance(WorkbenchList,
'RuntimeExtensions',
parent, delegate, [renderer], {
multipleSelectionSupport: false,
setRowLineHeight: false,
horizontalScrolling: false,
overrideStyles: {
listBackground: editorBackground
},
accessibilityProvider: new class implements IListAccessibilityProvider<IRuntimeExtension> {
getWidgetAriaLabel(): string {
return nls.localize('runtimeExtensions', "Runtime Extensions");
}
getAriaLabel(element: IRuntimeExtension): string | null {
return element.description.name;
}
}
});
this._list.splice(0, this._list.length, this._elements || undefined);
this._list.onContextMenu((e) => {
if (!e.element) {
return;
}
const actions: IAction[] = [];
const reportExtensionIssueAction = this._createReportExtensionIssueAction(e.element);
if (reportExtensionIssueAction) {
actions.push(reportExtensionIssueAction);
actions.push(new Separator());
}
if (e.element!.marketplaceInfo) {
actions.push(new Action('runtimeExtensionsEditor.action.disableWorkspace', nls.localize('disable workspace', "Disable (Workspace)"), undefined, true, () => this._extensionsWorkbenchService.setEnablement(e.element!.marketplaceInfo!, EnablementState.DisabledWorkspace)));
actions.push(new Action('runtimeExtensionsEditor.action.disable', nls.localize('disable', "Disable"), undefined, true, () => this._extensionsWorkbenchService.setEnablement(e.element!.marketplaceInfo!, EnablementState.DisabledGlobally)));
}
actions.push(new Separator());
const profileAction = this._createProfileAction();
if (profileAction) {
actions.push(profileAction);
}
const saveExtensionHostProfileAction = this.saveExtensionHostProfileAction;
if (saveExtensionHostProfileAction) {
actions.push(saveExtensionHostProfileAction);
}
this._contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => actions
});
});
}
@memoize
private get saveExtensionHostProfileAction(): IAction | null {
return this._createSaveExtensionHostProfileAction();
}
public layout(dimension: Dimension): void {
if (this._list) {
this._list.layout(dimension.height);
}
}
protected abstract _getProfileInfo(): IExtensionHostProfile | null;
protected abstract _getUnresponsiveProfile(extensionId: ExtensionIdentifier): IExtensionHostProfile | undefined;
protected abstract _createSlowExtensionAction(element: IRuntimeExtension): Action | null;
protected abstract _createReportExtensionIssueAction(element: IRuntimeExtension): Action | null;
protected abstract _createSaveExtensionHostProfileAction(): Action | null;
protected abstract _createProfileAction(): Action | null;
}
export class ShowRuntimeExtensionsAction extends Action2 {
constructor() {
super({
id: 'workbench.action.showRuntimeExtensions',
title: { value: nls.localize('showRuntimeExtensions', "Show Running Extensions"), original: 'Show Running Extensions' },
category: CATEGORIES.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
await accessor.get(IEditorService).openEditor(RuntimeExtensionsInput.instance, { pinned: true });
}
}
| src/vs/workbench/contrib/extensions/browser/abstractRuntimeExtensionsEditor.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00027087374473921955,
0.00017155671957880259,
0.00016368305659852922,
0.00016777924611233175,
0.000020069925085408613
] |
{
"id": 8,
"code_window": [
"}\n",
"\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {\n",
"\tz-index: 2;\n",
"\ttop: 0;\n",
"\theight: 1px;\n",
"\tbackground-color: var(--tab-border-top-color);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 6;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"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.
*--------------------------------------------------------------------------------------------*/
/*
################################### z-index explainer ###################################
Tabs have various levels of z-index depending on state, typically:
- scrollbar should be above all
- sticky (compact, shrink) tabs need to be above non-sticky tabs for scroll under effect
including non-sticky tabs-top borders, otherwise these borders would not scroll under
(https://github.com/microsoft/vscode/issues/111641)
- bottom-border needs to be above tabs bottom border to win but also support sticky tabs
(https://github.com/microsoft/vscode/issues/99084) <- this currently cannot be done and
is still broken. putting sticky-tabs above tabs bottom border would not render this
border at all for sticky tabs.
On top of that there is 2 borders with a z-index for a general border below tabs
- tabs bottom border
- editor title bottom border (when breadcrumbs are disabled, this border will appear
same as tabs bottom border)
The following tabls shows the current stacking order:
[z-index] [kind]
7 scrollbar
6 active-tab border-bottom
5 tabs, title border bottom
4 sticky-tab
2 active/dirty-tab border top
0 tab
##########################################################################################
*/
/* Title Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container {
display: flex;
position: relative; /* position tabs border bottom or editor actions (when tabs wrap) relative to this container */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 5;
pointer-events: none;
background-color: var(--tabs-border-bottom-color);
width: 100%;
height: 1px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element {
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container > .monaco-scrollable-element .scrollbar {
z-index: 7;
cursor: default;
}
/* Tabs Container */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container {
display: flex;
height: 35px;
scrollbar-width: none; /* Firefox: hide scrollbar */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.scroll {
overflow: scroll !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container {
/* Enable wrapping via flex layout and dynamic height */
height: auto;
flex-wrap: wrap;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container::-webkit-scrollbar {
display: none; /* Chrome + Safari: hide scrollbar */
}
/* Tab */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab {
position: relative;
display: flex;
white-space: nowrap;
cursor: pointer;
height: 35px;
box-sizing: border-box;
padding-left: 10px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab:last-child {
margin-right: var(--last-tab-margin-right); /* when tabs wrap, we need a margin away from the absolute positioned editor actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.last-in-row:not(:last-child) {
border-right: 0 !important; /* ensure no border for every last tab in a row except last row (#115046) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-right,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.has-icon.tab-actions-off:not(.sticky-compact) {
padding-left: 5px; /* reduce padding when we show icons and are in shrinking mode and tab actions is not left (unless sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit {
width: 120px;
min-width: fit-content;
min-width: -moz-fit-content;
flex-shrink: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab.sizing-fit.last-in-row:not(:last-child) {
flex-grow: 1; /* grow the last tab in a row for a more homogeneous look except for last row (#113801) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink {
min-width: 80px;
flex-basis: 0; /* all tabs are even */
flex-grow: 1; /* all tabs grow even */
max-width: fit-content;
max-width: -moz-fit-content;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky compact/shrink tabs do not scroll in case of overflow and are always above unsticky tabs which scroll under */
position: sticky;
z-index: 4;
/** Sticky compact/shrink tabs are even and never grow */
flex-basis: 0;
flex-grow: 0;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-compact {
/** Sticky compact tabs have a fixed width of 38px */
width: 38px;
min-width: 38px;
max-width: 38px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.sticky-shrink {
/** Sticky shrink tabs have a fixed width of 80px */
width: 80px;
min-width: 80px;
max-width: 80px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-compact,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-fit.sticky-shrink,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container.disable-sticky-tabs > .tab.sizing-shrink.sticky-shrink {
position: static; /** disable sticky positions for sticky compact/shrink tabs if the available space is too little */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left .action-label {
margin-right: 4px !important;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left::after,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off::after {
content: '';
display: flex;
flex: 0;
width: 5px; /* reserve space to hide tab fade when close button is left or off (fixes https://github.com/microsoft/vscode/issues/45728) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-left {
min-width: 80px; /* make more room for close button when it shows to the left */
padding-right: 5px; /* we need less room when sizing is shrink */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged {
transform: translate3d(0px, 0px, 0px); /* forces tab to be drawn on a separate layer (fixes https://github.com/microsoft/vscode/issues/18733) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dragged-over div {
pointer-events: none; /* prevents cursor flickering (fixes https://github.com/microsoft/vscode/issues/38753) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-left {
flex-direction: row-reverse;
padding-left: 0;
padding-right: 10px;
}
/* Tab border top/bottom */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-border-bottom-container {
display: none; /* hidden by default until a color is provided (see below) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
display: block;
position: absolute;
left: 0;
pointer-events: none;
width: 100%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 1px;
background-color: var(--tab-border-top-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-bottom > .tab-border-bottom-container {
z-index: 6;
bottom: 0;
height: 1px;
background-color: var(--tab-border-bottom-color);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty-border-top > .tab-border-top-container {
z-index: 2;
top: 0;
height: 2px;
background-color: var(--tab-dirty-border-top-color);
}
/* Tab Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
margin-top: auto;
margin-bottom: auto;
line-height: 35px; /* aligns icon and label vertically centered in the tab */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink .tab-label {
position: relative;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label > .monaco-icon-label-container::after {
content: ''; /* enables a linear gradient to overlay the end of the label when tabs overflow */
position: absolute;
right: 0;
width: 5px;
opacity: 1;
padding: 0;
/* the rules below ensure that the gradient does not impact top/bottom borders (https://github.com/microsoft/vscode/issues/115129) */
top: 1px;
bottom: 1px;
height: calc(100% - 2px);
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink:focus > .tab-label > .monaco-icon-label-container::after {
opacity: 0; /* when tab has the focus this shade breaks the tab border (fixes https://github.com/microsoft/vscode/issues/57819) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .tab-label.tab-label-has-badge::after {
padding-right: 5px; /* with tab sizing shrink and badges, we want a right-padding because the close button is hidden */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky-compact:not(.has-icon) .monaco-icon-label {
text-align: center; /* ensure that sticky-compact tabs without icon have label centered */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-fit .monaco-icon-label > .monaco-icon-label-container {
overflow: visible; /* fixes https://github.com/microsoft/vscode/issues/20182 */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: clip;
flex: none;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink > .monaco-icon-label > .monaco-icon-label-container {
text-overflow: ellipsis;
}
/* Tab Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions {
margin-top: auto;
margin-bottom: auto;
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions > .monaco-action-bar {
width: 28px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions {
flex: 0;
overflow: hidden; /* let the tab actions be pushed out of view when sizing is set to shrink to make more room */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.tab-actions-right.sizing-shrink > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink:hover > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-right.sizing-shrink > .tab-actions:focus-within {
overflow: visible; /* ...but still show the tab actions on hover, focus and when dirty or sticky */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off:not(.dirty):not(.sticky) > .tab-actions,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky-compact > .tab-actions {
display: none; /* hide the tab actions when we are configured to hide it (unless dirty or sticky, but always when sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active > .tab-actions .action-label, /* always show tab actions for active tab */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label:focus, /* always show tab actions on focus */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover > .tab-actions .action-label, /* always show tab actions on hover */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky > .tab-actions .action-label, /* always show tab actions for sticky tabs */
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label { /* always show tab actions for dirty tabs */
opacity: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .actions-container {
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab > .tab-actions .action-label.codicon {
color: inherit;
font-size: 16px;
padding: 2px;
width: 16px;
height: 16px;
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ebb2"; /* use `pinned-dirty` icon unicode for sticky-dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label:not(:hover)::before {
content: "\ea71"; /* use `circle-filled` icon unicode for dirty indication */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
opacity: 0.5; /* show tab actions dimmed for inactive group */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab > .tab-actions .action-label {
opacity: 0;
}
/* Tab Actions: Off */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off {
padding-right: 10px; /* give a little bit more room if tab actions is off */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sizing-shrink.tab-actions-off:not(.sticky-compact) {
padding-right: 5px; /* we need less room when sizing is shrink (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty-border-top > .tab-actions {
display: none; /* hide dirty state when highlightModifiedTabs is enabled and when running without tab actions */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.dirty:not(.dirty-border-top):not(.sticky-compact),
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off.sticky:not(.sticky-compact) {
padding-right: 0; /* remove extra padding when we are running without tab actions (unless tab is sticky-compact) */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.tab-actions-off > .tab-actions {
pointer-events: none; /* don't allow tab actions to be clicked when running without tab actions */
}
/* Breadcrumbs */
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control {
flex: 1 100%;
height: 22px;
cursor: default;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label {
height: 22px;
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-icon-label::before {
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .outline-element-icon {
padding-right: 3px;
height: 22px; /* tweak the icon size of the editor labels when icons are enabled */
line-height: 22px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item {
max-width: 80%;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item::before {
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child {
padding-right: 8px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-breadcrumbs .breadcrumbs-control .monaco-breadcrumb-item:last-child .codicon:last-child {
display: none; /* hides chevrons when last item */
}
/* Editor Actions Toolbar */
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
cursor: default;
flex: initial;
padding: 0 8px 0 4px;
height: 35px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-item {
margin-right: 4px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .editor-actions {
/* When tabs are wrapped, position the editor actions at the end of the very last row */
position: absolute;
bottom: 0;
right: 0;
}
| src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css | 1 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.7464046478271484,
0.033837415277957916,
0.00016354623949155211,
0.003280612174421549,
0.12103862315416336
] |
{
"id": 8,
"code_window": [
"}\n",
"\n",
".monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active.tab-border-top > .tab-border-top-container {\n",
"\tz-index: 2;\n",
"\ttop: 0;\n",
"\theight: 1px;\n",
"\tbackground-color: var(--tab-border-top-color);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tz-index: 6;\n"
],
"file_path": "src/vs/workbench/browser/parts/editor/media/tabstitlecontrol.css",
"type": "replace",
"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 { onUnexpectedError } from 'vs/base/common/errors';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker';
import { IModelService } from 'vs/editor/common/services/model';
import { ILanguageService } from 'vs/editor/common/services/language';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { ExtHostContext, ExtHostDocumentContentProvidersShape, IExtHostContext, MainContext, MainThreadDocumentContentProvidersShape } from '../common/extHost.protocol';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
@extHostNamedCustomer(MainContext.MainThreadDocumentContentProviders)
export class MainThreadDocumentContentProviders implements MainThreadDocumentContentProvidersShape {
private readonly _resourceContentProvider = new Map<number, IDisposable>();
private readonly _pendingUpdate = new Map<string, CancellationTokenSource>();
private readonly _proxy: ExtHostDocumentContentProvidersShape;
constructor(
extHostContext: IExtHostContext,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@IModelService private readonly _modelService: IModelService,
@IEditorWorkerService private readonly _editorWorkerService: IEditorWorkerService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDocumentContentProviders);
}
dispose(): void {
dispose(this._resourceContentProvider.values());
dispose(this._pendingUpdate.values());
}
$registerTextContentProvider(handle: number, scheme: string): void {
const registration = this._textModelResolverService.registerTextModelContentProvider(scheme, {
provideTextContent: (uri: URI): Promise<ITextModel | null> => {
return this._proxy.$provideTextDocumentContent(handle, uri).then(value => {
if (typeof value === 'string') {
const firstLineText = value.substr(0, 1 + value.search(/\r?\n/));
const languageSelection = this._languageService.createByFilepathOrFirstLine(uri, firstLineText);
return this._modelService.createModel(value, languageSelection, uri);
}
return null;
});
}
});
this._resourceContentProvider.set(handle, registration);
}
$unregisterTextContentProvider(handle: number): void {
const registration = this._resourceContentProvider.get(handle);
if (registration) {
registration.dispose();
this._resourceContentProvider.delete(handle);
}
}
$onVirtualDocumentChange(uri: UriComponents, value: string): void {
const model = this._modelService.getModel(URI.revive(uri));
if (!model) {
return;
}
// cancel and dispose an existing update
const pending = this._pendingUpdate.get(model.id);
if (pending) {
pending.cancel();
}
// create and keep update token
const myToken = new CancellationTokenSource();
this._pendingUpdate.set(model.id, myToken);
this._editorWorkerService.computeMoreMinimalEdits(model.uri, [{ text: value, range: model.getFullModelRange() }]).then(edits => {
// remove token
this._pendingUpdate.delete(model.id);
if (myToken.token.isCancellationRequested) {
// ignore this
return;
}
if (edits && edits.length > 0) {
// use the evil-edit as these models show in readonly-editor only
model.applyEdits(edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
}
}).catch(onUnexpectedError);
}
}
| src/vs/workbench/api/browser/mainThreadDocumentContentProviders.ts | 0 | https://github.com/microsoft/vscode/commit/b61f91f54a081567fd9faf501c520172d046e99a | [
0.00025409896625205874,
0.00017713506531435996,
0.0001642668794374913,
0.00016894220607355237,
0.00002581294029369019
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.