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": 1,
"code_window": [
"\t\t\tconst cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]);\n",
"\n",
"\t\t\t// Create the top level menu button element\n",
"\t\t\tif (firstTimeSetup) {\n",
"\n",
"\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n",
"\t\t\t\tconst titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true });\n",
"\n",
"\t\t\t\tbuttonElement.appendChild(titleElement);\n",
"\t\t\t\tthis.container.appendChild(buttonElement);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': -1, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 700
} | /*---------------------------------------------------------------------------------------------
* 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 { ITextModel, FindMatch } from 'vs/editor/common/model';
import { editorMatchesToTextSearchResults, addContextToEditorMatches } from 'vs/workbench/services/search/common/searchHelpers';
import { Range } from 'vs/editor/common/core/range';
import { ITextQuery, QueryType, ITextSearchContext } from 'vs/platform/search/common/search';
suite('SearchHelpers', () => {
suite('editorMatchesToTextSearchResults', () => {
const mockTextModel: ITextModel = <ITextModel>{
getLineContent(lineNumber: number): string {
return '' + lineNumber;
}
};
test('simple', () => {
const results = editorMatchesToTextSearchResults([new FindMatch(new Range(6, 1, 6, 2), null)], mockTextModel);
assert.equal(results.length, 1);
assert.equal(results[0].preview.text, '6\n');
assert.deepEqual(results[0].preview.matches, [new Range(0, 0, 0, 1)]);
assert.deepEqual(results[0].ranges, [new Range(5, 0, 5, 1)]);
});
test('multiple', () => {
const results = editorMatchesToTextSearchResults(
[
new FindMatch(new Range(6, 1, 6, 2), null),
new FindMatch(new Range(6, 4, 8, 2), null),
new FindMatch(new Range(9, 1, 10, 3), null),
],
mockTextModel);
assert.equal(results.length, 2);
assert.deepEqual(results[0].preview.matches, [
new Range(0, 0, 0, 1),
new Range(0, 3, 2, 1),
]);
assert.deepEqual(results[0].ranges, [
new Range(5, 0, 5, 1),
new Range(5, 3, 7, 1),
]);
assert.equal(results[0].preview.text, '6\n7\n8\n');
assert.deepEqual(results[1].preview.matches, [
new Range(0, 0, 1, 2),
]);
assert.deepEqual(results[1].ranges, [
new Range(8, 0, 9, 2),
]);
assert.equal(results[1].preview.text, '9\n10\n');
});
});
suite('addContextToEditorMatches', () => {
const MOCK_LINE_COUNT = 100;
const mockTextModel: ITextModel = <ITextModel>{
getLineContent(lineNumber: number): string {
if (lineNumber < 1 || lineNumber > MOCK_LINE_COUNT) {
throw new Error(`invalid line count: ${lineNumber}`);
}
return '' + lineNumber;
},
getLineCount(): number {
return MOCK_LINE_COUNT;
}
};
function getQuery(beforeContext?: number, afterContext?: number): ITextQuery {
return {
type: QueryType.Text,
contentPattern: { pattern: 'test' },
beforeContext,
afterContext
};
}
test('no context', () => {
const matches = [{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(0, 0, 0, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery()), matches);
});
test('simple', () => {
const matches = [{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(1, 0, 1, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [
<ITextSearchContext>{
text: '1',
lineNumber: 0
},
...matches,
<ITextSearchContext>{
text: '3',
lineNumber: 2
},
<ITextSearchContext>{
text: '4',
lineNumber: 3
},
]);
});
test('multiple matches next to each other', () => {
const matches = [
{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(1, 0, 1, 10)
},
{
preview: {
text: 'bar',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(2, 0, 2, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [
<ITextSearchContext>{
text: '1',
lineNumber: 0
},
...matches,
<ITextSearchContext>{
text: '4',
lineNumber: 3
},
<ITextSearchContext>{
text: '5',
lineNumber: 4
},
]);
});
test('boundaries', () => {
const matches = [
{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(0, 0, 0, 10)
},
{
preview: {
text: 'bar',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(MOCK_LINE_COUNT - 1, 0, MOCK_LINE_COUNT - 1, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [
matches[0],
<ITextSearchContext>{
text: '2',
lineNumber: 1
},
<ITextSearchContext>{
text: '3',
lineNumber: 2
},
<ITextSearchContext>{
text: '' + (MOCK_LINE_COUNT - 1),
lineNumber: MOCK_LINE_COUNT - 2
},
matches[1]
]);
});
});
}); | src/vs/workbench/services/search/test/common/searchHelpers.test.ts | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017506402218714356,
0.00017200049478560686,
0.00016800640150904655,
0.00017213814135175198,
0.000001964481953109498
] |
{
"id": 1,
"code_window": [
"\t\t\tconst cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]);\n",
"\n",
"\t\t\t// Create the top level menu button element\n",
"\t\t\tif (firstTimeSetup) {\n",
"\n",
"\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n",
"\t\t\t\tconst titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true });\n",
"\n",
"\t\t\t\tbuttonElement.appendChild(titleElement);\n",
"\t\t\t\tthis.container.appendChild(buttonElement);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': -1, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 700
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#f6f6f6;}.icon-canvas-transparent{opacity:0;}.icon-disabled-grey{fill:#848484;}</style></defs><title>breakpoint-disabled</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,0V16H0V0Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M12.632,8A4.632,4.632,0,1,1,8,3.368,4.638,4.638,0,0,1,12.632,8Z"/></g><g id="iconBg"><path class="icon-disabled-grey" d="M11.789,8A3.789,3.789,0,1,1,8,4.211,3.788,3.788,0,0,1,11.789,8Z"/></g></svg> | src/vs/workbench/parts/debug/browser/media/breakpoint-disabled.svg | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017350062262266874,
0.00017350062262266874,
0.00017350062262266874,
0.00017350062262266874,
0
] |
{
"id": 2,
"code_window": [
"\t\t\tthis._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => {\n",
"\t\t\t\tlet event = new StandardKeyboardEvent(e as KeyboardEvent);\n",
"\t\t\t\tlet eventHandled = true;\n",
"\t\t\t\tconst key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown;\n",
"\n",
"\t\t\t\tif (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusPrevious();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tif (event.equals(KeyCode.LeftArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 844
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as browser from 'vs/base/browser/browser';
import * as strings from 'vs/base/common/strings';
import { IMenubarMenu, IMenubarMenuItemAction, IMenubarMenuItemSubmenu, IMenubarKeybinding, IMenubarService, IMenubarData } from 'vs/platform/menubar/common/menubar';
import { IMenuService, MenuId, IMenu, SubmenuItemAction } from 'vs/platform/actions/common/actions';
import { registerThemingParticipant, ITheme, ICssStyleCollector, IThemeService } from 'vs/platform/theme/common/themeService';
import { IWindowService, MenuBarVisibility, IWindowsService, getTitleBarStyle } from 'vs/platform/windows/common/windows';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ActionRunner, IActionRunner, IAction, Action } from 'vs/base/common/actions';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import * as DOM from 'vs/base/browser/dom';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { isMacintosh, isLinux } from 'vs/base/common/platform';
import { Menu, IMenuOptions, SubmenuAction, MENU_MNEMONIC_REGEX, cleanMnemonic, MENU_ESCAPED_MNEMONIC_REGEX } from 'vs/base/browser/ui/menu/menu';
import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { Event, Emitter } from 'vs/base/common/event';
import { IDisposable, Disposable, dispose } from 'vs/base/common/lifecycle';
import { domEvent } from 'vs/base/browser/event';
import { IRecentlyOpened } from 'vs/platform/history/common/history';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { RunOnceScheduler } from 'vs/base/common/async';
import { MENUBAR_SELECTION_FOREGROUND, MENUBAR_SELECTION_BACKGROUND, MENUBAR_SELECTION_BORDER, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND } from 'vs/workbench/common/theme';
import { URI } from 'vs/base/common/uri';
import { ILabelService } from 'vs/platform/label/common/label';
import { IUpdateService, StateType } from 'vs/platform/update/common/update';
import { Gesture, EventType, GestureEvent } from 'vs/base/browser/touch';
import { attachMenuStyler } from 'vs/platform/theme/common/styler';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
const $ = DOM.$;
interface CustomMenu {
title: string;
buttonElement: HTMLElement;
titleElement: HTMLElement;
actions?: IAction[];
}
enum MenubarState {
HIDDEN,
VISIBLE,
FOCUSED,
OPEN
}
export class MenubarControl extends Disposable {
private keys = [
'files.autoSave',
'window.menuBarVisibility',
'editor.multiCursorModifier',
'workbench.sideBar.location',
'workbench.statusBar.visible',
'workbench.activityBar.visible',
'window.enableMenuBarMnemonics',
'window.nativeTabs'
];
private topLevelMenus: {
'File': IMenu;
'Edit': IMenu;
'Selection': IMenu;
'View': IMenu;
'Go': IMenu;
'Debug': IMenu;
'Terminal': IMenu;
'Window'?: IMenu;
'Help': IMenu;
[index: string]: IMenu;
};
private topLevelTitles = {
'File': nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File"),
'Edit': nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit"),
'Selection': nls.localize({ key: 'mSelection', comment: ['&& denotes a mnemonic'] }, "&&Selection"),
'View': nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View"),
'Go': nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go"),
'Debug': nls.localize({ key: 'mDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"),
'Terminal': nls.localize({ key: 'mTerminal', comment: ['&& denotes a mnemonic'] }, "&&Terminal"),
'Help': nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")
};
private focusedMenu: {
index: number;
holder?: HTMLElement;
widget?: Menu;
};
private customMenus: CustomMenu[];
private menuUpdater: RunOnceScheduler;
private actionRunner: IActionRunner;
private focusToReturn: HTMLElement;
private container: HTMLElement;
private recentlyOpened: IRecentlyOpened;
private updatePending: boolean;
private _focusState: MenubarState;
// Input-related
private _mnemonicsInUse: boolean;
private openedViaKeyboard: boolean;
private awaitingAltRelease: boolean;
private ignoreNextMouseUp: boolean;
private mnemonics: Map<KeyCode, number>;
private _onVisibilityChange: Emitter<boolean>;
private _onFocusStateChange: Emitter<boolean>;
private static MAX_MENU_RECENT_ENTRIES = 10;
constructor(
@IThemeService private themeService: IThemeService,
@IMenubarService private menubarService: IMenubarService,
@IMenuService private menuService: IMenuService,
@IWindowService private windowService: IWindowService,
@IWindowsService private windowsService: IWindowsService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IKeybindingService private keybindingService: IKeybindingService,
@IConfigurationService private configurationService: IConfigurationService,
@ILabelService private labelService: ILabelService,
@IUpdateService private updateService: IUpdateService,
@IStorageService private storageService: IStorageService,
@INotificationService private notificationService: INotificationService,
@IPreferencesService private preferencesService: IPreferencesService,
@IEnvironmentService private environmentService: IEnvironmentService
) {
super();
this.topLevelMenus = {
'File': this._register(this.menuService.createMenu(MenuId.MenubarFileMenu, this.contextKeyService)),
'Edit': this._register(this.menuService.createMenu(MenuId.MenubarEditMenu, this.contextKeyService)),
'Selection': this._register(this.menuService.createMenu(MenuId.MenubarSelectionMenu, this.contextKeyService)),
'View': this._register(this.menuService.createMenu(MenuId.MenubarViewMenu, this.contextKeyService)),
'Go': this._register(this.menuService.createMenu(MenuId.MenubarGoMenu, this.contextKeyService)),
'Debug': this._register(this.menuService.createMenu(MenuId.MenubarDebugMenu, this.contextKeyService)),
'Terminal': this._register(this.menuService.createMenu(MenuId.MenubarTerminalMenu, this.contextKeyService)),
'Help': this._register(this.menuService.createMenu(MenuId.MenubarHelpMenu, this.contextKeyService))
};
if (isMacintosh) {
this.topLevelMenus['Preferences'] = this._register(this.menuService.createMenu(MenuId.MenubarPreferencesMenu, this.contextKeyService));
}
this.menuUpdater = this._register(new RunOnceScheduler(() => this.doSetupMenubar(), 200));
this.actionRunner = this._register(new ActionRunner());
this._register(this.actionRunner.onDidBeforeRun(() => {
this.setUnfocusedState();
}));
this._onVisibilityChange = this._register(new Emitter<boolean>());
this._onFocusStateChange = this._register(new Emitter<boolean>());
if (isMacintosh || this.currentTitlebarStyleSetting !== 'custom') {
for (let topLevelMenuName of Object.keys(this.topLevelMenus)) {
this._register(this.topLevelMenus[topLevelMenuName].onDidChange(() => this.setupMenubar()));
}
this.doSetupMenubar();
}
this._focusState = MenubarState.HIDDEN;
this.windowService.getRecentlyOpened().then((recentlyOpened) => {
this.recentlyOpened = recentlyOpened;
});
this.detectAndRecommendCustomTitlebar();
this.registerListeners();
}
private get currentEnableMenuBarMnemonics(): boolean {
let enableMenuBarMnemonics = this.configurationService.getValue<boolean>('window.enableMenuBarMnemonics');
if (typeof enableMenuBarMnemonics !== 'boolean') {
enableMenuBarMnemonics = true;
}
return enableMenuBarMnemonics;
}
private get currentSidebarPosition(): string {
return this.configurationService.getValue<string>('workbench.sideBar.location');
}
private get currentStatusBarVisibility(): boolean {
let setting = this.configurationService.getValue<boolean>('workbench.statusBar.visible');
if (typeof setting !== 'boolean') {
setting = true;
}
return setting;
}
private get currentActivityBarVisibility(): boolean {
let setting = this.configurationService.getValue<boolean>('workbench.activityBar.visible');
if (typeof setting !== 'boolean') {
setting = true;
}
return setting;
}
private get currentMenubarVisibility(): MenuBarVisibility {
return this.configurationService.getValue<MenuBarVisibility>('window.menuBarVisibility');
}
private get currentTitlebarStyleSetting(): string {
return getTitleBarStyle(this.configurationService, this.environmentService);
}
private get focusState(): MenubarState {
return this._focusState;
}
private set focusState(value: MenubarState) {
if (this._focusState >= MenubarState.FOCUSED && value < MenubarState.FOCUSED) {
// Losing focus, update the menu if needed
if (this.updatePending) {
this.menuUpdater.schedule();
this.updatePending = false;
}
}
if (value === this._focusState) {
return;
}
const isVisible = this.isVisible;
const isOpen = this.isOpen;
const isFocused = this.isFocused;
this._focusState = value;
switch (value) {
case MenubarState.HIDDEN:
if (isVisible) {
this.hideMenubar();
}
if (isOpen) {
this.cleanupCustomMenu();
}
if (isFocused) {
this.focusedMenu = null;
if (this.focusToReturn) {
this.focusToReturn.focus();
this.focusToReturn = null;
}
}
break;
case MenubarState.VISIBLE:
if (!isVisible) {
this.showMenubar();
}
if (isOpen) {
this.cleanupCustomMenu();
}
if (isFocused) {
if (this.focusedMenu) {
this.customMenus[this.focusedMenu.index].buttonElement.blur();
}
this.focusedMenu = null;
if (this.focusToReturn) {
this.focusToReturn.focus();
this.focusToReturn = null;
}
}
break;
case MenubarState.FOCUSED:
if (!isVisible) {
this.showMenubar();
}
if (isOpen) {
this.cleanupCustomMenu();
}
if (this.focusedMenu) {
this.customMenus[this.focusedMenu.index].buttonElement.focus();
}
break;
case MenubarState.OPEN:
if (!isVisible) {
this.showMenubar();
}
if (this.focusedMenu) {
this.showCustomMenu(this.focusedMenu.index, this.openedViaKeyboard);
}
break;
}
this._focusState = value;
this._onFocusStateChange.fire(this.focusState >= MenubarState.FOCUSED);
}
private get mnemonicsInUse(): boolean {
return this._mnemonicsInUse;
}
private set mnemonicsInUse(value: boolean) {
this._mnemonicsInUse = value;
}
private get isVisible(): boolean {
return this.focusState >= MenubarState.VISIBLE;
}
private get isFocused(): boolean {
return this.focusState >= MenubarState.FOCUSED;
}
private get isOpen(): boolean {
return this.focusState >= MenubarState.OPEN;
}
private onDidChangeFullscreen(): void {
this.setUnfocusedState();
}
private onDidChangeWindowFocus(hasFocus: boolean): void {
if (this.container) {
if (hasFocus) {
DOM.removeClass(this.container, 'inactive');
} else {
DOM.addClass(this.container, 'inactive');
this.setUnfocusedState();
this.awaitingAltRelease = false;
}
}
}
private onConfigurationUpdated(event: IConfigurationChangeEvent): void {
if (this.keys.some(key => event.affectsConfiguration(key))) {
this.setupMenubar();
}
if (event.affectsConfiguration('window.menuBarVisibility')) {
this.setUnfocusedState();
this.detectAndRecommendCustomTitlebar();
}
}
private setUnfocusedState(): void {
if (this.currentMenubarVisibility === 'toggle' || this.currentMenubarVisibility === 'hidden') {
this.focusState = MenubarState.HIDDEN;
} else if (this.currentMenubarVisibility === 'default' && browser.isFullscreen()) {
this.focusState = MenubarState.HIDDEN;
} else {
this.focusState = MenubarState.VISIBLE;
}
this.ignoreNextMouseUp = false;
this.mnemonicsInUse = false;
this.updateMnemonicVisibility(false);
}
private hideMenubar(): void {
if (this.container.style.display !== 'none') {
this.container.style.display = 'none';
this._onVisibilityChange.fire(false);
}
}
private showMenubar(): void {
if (this.container.style.display !== 'flex') {
this.container.style.display = 'flex';
this._onVisibilityChange.fire(true);
}
}
private onModifierKeyToggled(modifierKeyStatus: IModifierKeyStatus): void {
const allModifiersReleased = !modifierKeyStatus.altKey && !modifierKeyStatus.ctrlKey && !modifierKeyStatus.shiftKey;
if (this.currentMenubarVisibility === 'hidden') {
return;
}
// Alt key pressed while menu is focused. This should return focus away from the menubar
if (this.isFocused && modifierKeyStatus.lastKeyPressed === 'alt' && modifierKeyStatus.altKey) {
this.setUnfocusedState();
this.mnemonicsInUse = false;
this.awaitingAltRelease = true;
}
// Clean alt key press and release
if (allModifiersReleased && modifierKeyStatus.lastKeyPressed === 'alt' && modifierKeyStatus.lastKeyReleased === 'alt') {
if (!this.awaitingAltRelease) {
if (!this.isFocused) {
this.mnemonicsInUse = true;
this.focusedMenu = { index: 0 };
this.focusState = MenubarState.FOCUSED;
} else if (!this.isOpen) {
this.setUnfocusedState();
}
}
}
// Alt key released
if (!modifierKeyStatus.altKey && modifierKeyStatus.lastKeyReleased === 'alt') {
this.awaitingAltRelease = false;
}
if (this.currentEnableMenuBarMnemonics && this.customMenus && !this.isOpen) {
this.updateMnemonicVisibility((!this.awaitingAltRelease && modifierKeyStatus.altKey) || this.mnemonicsInUse);
}
}
private updateMnemonicVisibility(visible: boolean): void {
if (this.customMenus) {
this.customMenus.forEach(customMenu => {
if (customMenu.titleElement.children.length) {
let child = customMenu.titleElement.children.item(0) as HTMLElement;
if (child) {
child.style.textDecoration = visible ? 'underline' : null;
}
}
});
}
}
private onRecentlyOpenedChange(): void {
this.windowService.getRecentlyOpened().then(recentlyOpened => {
this.recentlyOpened = recentlyOpened;
this.setupMenubar();
});
}
private detectAndRecommendCustomTitlebar(): void {
if (!isLinux) {
return;
}
if (!this.storageService.getBoolean('menubar/electronFixRecommended', StorageScope.GLOBAL, false)) {
if (this.currentMenubarVisibility === 'hidden' || this.currentTitlebarStyleSetting === 'custom') {
// Issue will not arise for user, abort notification
return;
}
const message = nls.localize('menubar.electronFixRecommendation', "If you experience hard to read text in the menu bar, we recommend trying out the custom title bar.");
this.notificationService.prompt(Severity.Info, message, [
{
label: nls.localize('goToSetting', "Open Settings"),
run: () => {
return this.preferencesService.openGlobalSettings(undefined, { query: 'window.titleBarStyle' });
}
},
{
label: nls.localize('moreInfo', "More Info"),
run: () => {
window.open('https://go.microsoft.com/fwlink/?linkid=2038566');
}
},
{
label: nls.localize('neverShowAgain', "Don't Show Again"),
run: () => {
this.storageService.store('menubar/electronFixRecommended', true, StorageScope.GLOBAL);
}
}
]);
}
}
private registerListeners(): void {
// Update when config changes
this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e)));
// Listen to update service
this.updateService.onStateChange(() => this.setupMenubar());
// Listen for changes in recently opened menu
this._register(this.windowsService.onRecentlyOpenedChange(() => { this.onRecentlyOpenedChange(); }));
// Listen to keybindings change
this._register(this.keybindingService.onDidUpdateKeybindings(() => this.setupMenubar()));
// These listeners only apply when the custom menubar is being used
if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') {
// Listen to fullscreen changes
this._register(browser.onDidChangeFullscreen(() => this.onDidChangeFullscreen()));
// Listen for alt key presses
this._register(ModifierKeyEmitter.getInstance(this.windowService).event(this.onModifierKeyToggled, this));
// Listen for window focus changes
this._register(this.windowService.onDidChangeFocus(e => this.onDidChangeWindowFocus(e)));
}
}
private doSetupMenubar(): void {
if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') {
this.setupCustomMenubar();
} else {
// Send menus to main process to be rendered by Electron
const menubarData = { menus: {}, keybindings: {} };
if (this.getMenubarMenus(menubarData)) {
this.menubarService.updateMenubar(this.windowService.getCurrentWindowId(), menubarData);
}
}
}
private setupMenubar(): void {
this.menuUpdater.schedule();
}
private registerMnemonic(menuIndex: number, mnemonic: string): void {
this.mnemonics.set(KeyCodeUtils.fromString(mnemonic), menuIndex);
}
private calculateActionLabel(action: IAction | IMenubarMenuItemAction): string {
let label = action.label;
switch (action.id) {
case 'workbench.action.toggleSidebarPosition':
if (this.currentSidebarPosition !== 'right') {
label = nls.localize({ key: 'miMoveSidebarRight', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Right");
} else {
label = nls.localize({ key: 'miMoveSidebarLeft', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Left");
}
break;
case 'workbench.action.toggleStatusbarVisibility':
if (this.currentStatusBarVisibility) {
label = nls.localize({ key: 'miHideStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Hide Status Bar");
} else {
label = nls.localize({ key: 'miShowStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Show Status Bar");
}
break;
case 'workbench.action.toggleActivityBarVisibility':
if (this.currentActivityBarVisibility) {
label = nls.localize({ key: 'miHideActivityBar', comment: ['&& denotes a mnemonic'] }, "Hide &&Activity Bar");
} else {
label = nls.localize({ key: 'miShowActivityBar', comment: ['&& denotes a mnemonic'] }, "Show &&Activity Bar");
}
break;
default:
break;
}
return label;
}
private createOpenRecentMenuAction(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI, commandId: string, isFile: boolean): IAction {
let label: string;
let uri: URI;
if (isSingleFolderWorkspaceIdentifier(workspace) && !isFile) {
label = this.labelService.getWorkspaceLabel(workspace, { verbose: true });
uri = workspace;
} else if (isWorkspaceIdentifier(workspace)) {
label = this.labelService.getWorkspaceLabel(workspace, { verbose: true });
uri = URI.file(workspace.configPath);
} else {
uri = workspace;
label = this.labelService.getUriLabel(uri);
}
return new Action(commandId, label, undefined, undefined, (event) => {
const openInNewWindow = event && ((!isMacintosh && (event.ctrlKey || event.shiftKey)) || (isMacintosh && (event.metaKey || event.altKey)));
return this.windowService.openWindow([uri], {
forceNewWindow: openInNewWindow,
forceOpenWorkspaceAsFile: isFile
});
});
}
private getOpenRecentActions(): IAction[] {
if (!this.recentlyOpened) {
return [];
}
const { workspaces, files } = this.recentlyOpened;
const result: IAction[] = [];
if (workspaces.length > 0) {
for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < workspaces.length; i++) {
result.push(this.createOpenRecentMenuAction(workspaces[i], 'openRecentWorkspace', false));
}
result.push(new Separator());
}
if (files.length > 0) {
for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) {
result.push(this.createOpenRecentMenuAction(files[i], 'openRecentFile', false));
}
result.push(new Separator());
}
return result;
}
private getUpdateAction(): IAction | null {
const state = this.updateService.state;
switch (state.type) {
case StateType.Uninitialized:
return null;
case StateType.Idle:
const windowId = this.windowService.getCurrentWindowId();
return new Action('update.check', nls.localize({ key: 'checkForUpdates', comment: ['&& denotes a mnemonic'] }, "Check for &&Updates..."), undefined, true, () =>
this.updateService.checkForUpdates({ windowId }));
case StateType.CheckingForUpdates:
return new Action('update.checking', nls.localize('checkingForUpdates', "Checking For Updates..."), undefined, false);
case StateType.AvailableForDownload:
return new Action('update.downloadNow', nls.localize({ key: 'download now', comment: ['&& denotes a mnemonic'] }, "D&&ownload Now"), null, true, () =>
this.updateService.downloadUpdate());
case StateType.Downloading:
return new Action('update.downloading', nls.localize('DownloadingUpdate', "Downloading Update..."), undefined, false);
case StateType.Downloaded:
return new Action('update.install', nls.localize({ key: 'installUpdate...', comment: ['&& denotes a mnemonic'] }, "Install &&Update..."), undefined, true, () =>
this.updateService.applyUpdate());
case StateType.Updating:
return new Action('update.updating', nls.localize('installingUpdate', "Installing Update..."), undefined, false);
case StateType.Ready:
return new Action('update.restart', nls.localize({ key: 'restartToUpdate', comment: ['&& denotes a mnemonic'] }, "Restart to &&Update..."), undefined, true, () =>
this.updateService.quitAndInstall());
}
}
private insertActionsBefore(nextAction: IAction, target: IAction[]): void {
switch (nextAction.id) {
case 'workbench.action.openRecent':
target.push(...this.getOpenRecentActions());
break;
case 'workbench.action.showAboutDialog':
if (!isMacintosh) {
const updateAction = this.getUpdateAction();
if (updateAction) {
target.push(updateAction);
target.push(new Separator());
}
}
break;
default:
break;
}
}
private setupCustomMenubar(): void {
// Don't update while using the menu
if (this.isFocused) {
this.updatePending = true;
return;
}
this.container.attributes['role'] = 'menubar';
const firstTimeSetup = this.customMenus === undefined;
if (firstTimeSetup) {
this.customMenus = [];
this.mnemonics = new Map<KeyCode, number>();
}
let idx = 0;
for (let menuTitle of Object.keys(this.topLevelMenus)) {
const menu: IMenu = this.topLevelMenus[menuTitle];
let menuIndex = idx++;
const cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]);
// Create the top level menu button element
if (firstTimeSetup) {
const buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });
const titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true });
buttonElement.appendChild(titleElement);
this.container.appendChild(buttonElement);
this.customMenus.push({
title: menuTitle,
buttonElement: buttonElement,
titleElement: titleElement
});
}
// Update the button label to reflect mnemonics
this.customMenus[menuIndex].titleElement.innerHTML = this.currentEnableMenuBarMnemonics ?
strings.escape(this.topLevelTitles[menuTitle]).replace(MENU_ESCAPED_MNEMONIC_REGEX, '<mnemonic aria-hidden="true">$1</mnemonic>') :
cleanMenuLabel;
let mnemonicMatches = MENU_MNEMONIC_REGEX.exec(this.topLevelTitles[menuTitle]);
// Register mnemonics
if (mnemonicMatches) {
let mnemonic = !!mnemonicMatches[1] ? mnemonicMatches[1] : mnemonicMatches[2];
if (firstTimeSetup) {
this.registerMnemonic(menuIndex, mnemonic);
}
if (this.currentEnableMenuBarMnemonics) {
this.customMenus[menuIndex].buttonElement.setAttribute('aria-keyshortcuts', 'Alt+' + mnemonic.toLocaleLowerCase());
} else {
this.customMenus[menuIndex].buttonElement.removeAttribute('aria-keyshortcuts');
}
}
// Update the menu actions
const updateActions = (menu: IMenu, target: IAction[]) => {
target.splice(0);
let groups = menu.getActions();
for (let group of groups) {
const [, actions] = group;
for (let action of actions) {
this.insertActionsBefore(action, target);
if (action instanceof SubmenuItemAction) {
const submenu = this.menuService.createMenu(action.item.submenu, this.contextKeyService);
const submenuActions: SubmenuAction[] = [];
updateActions(submenu, submenuActions);
target.push(new SubmenuAction(action.label, submenuActions));
submenu.dispose();
} else {
action.label = this.calculateActionLabel(action);
target.push(action);
}
}
target.push(new Separator());
}
target.pop();
};
this.customMenus[menuIndex].actions = [];
if (firstTimeSetup) {
this._register(menu.onDidChange(() => updateActions(menu, this.customMenus[menuIndex].actions)));
}
updateActions(menu, this.customMenus[menuIndex].actions);
if (firstTimeSetup) {
this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.KEY_UP, (e) => {
let event = new StandardKeyboardEvent(e as KeyboardEvent);
let eventHandled = true;
if ((event.equals(KeyCode.DownArrow) || event.equals(KeyCode.Enter)) && !this.isOpen) {
this.focusedMenu = { index: menuIndex };
this.openedViaKeyboard = true;
this.focusState = MenubarState.OPEN;
} else {
eventHandled = false;
}
if (eventHandled) {
event.preventDefault();
event.stopPropagation();
}
}));
Gesture.addTarget(this.customMenus[menuIndex].buttonElement);
this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, EventType.Tap, (e: GestureEvent) => {
// Ignore this touch if the menu is touched
if (this.isOpen && this.focusedMenu.holder && DOM.isAncestor(e.initialTarget as HTMLElement, this.focusedMenu.holder)) {
return;
}
this.ignoreNextMouseUp = false;
this.onMenuTriggered(menuIndex, true);
e.preventDefault();
e.stopPropagation();
}));
this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_DOWN, (e) => {
if (!this.isOpen) {
// Open the menu with mouse down and ignore the following mouse up event
this.ignoreNextMouseUp = true;
this.onMenuTriggered(menuIndex, true);
} else {
this.ignoreNextMouseUp = false;
}
e.preventDefault();
e.stopPropagation();
}));
this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_UP, (e) => {
if (!this.ignoreNextMouseUp) {
if (this.isFocused) {
this.onMenuTriggered(menuIndex, true);
}
} else {
this.ignoreNextMouseUp = false;
}
}));
this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_ENTER, () => {
if (this.isOpen && !this.isCurrentMenu(menuIndex)) {
this.customMenus[menuIndex].buttonElement.focus();
this.cleanupCustomMenu();
this.showCustomMenu(menuIndex, false);
} else if (this.isFocused && !this.isOpen) {
this.focusedMenu = { index: menuIndex };
this.customMenus[menuIndex].buttonElement.focus();
}
}));
}
}
if (firstTimeSetup) {
this._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => {
let event = new StandardKeyboardEvent(e as KeyboardEvent);
let eventHandled = true;
const key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown;
if (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) {
this.focusPrevious();
} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) {
this.focusNext();
} else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) {
this.setUnfocusedState();
} else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) {
const menuIndex = this.mnemonics.get(key);
this.onMenuTriggered(menuIndex, false);
} else {
eventHandled = false;
}
if (eventHandled) {
event.preventDefault();
event.stopPropagation();
}
}));
this._register(DOM.addDisposableListener(window, DOM.EventType.MOUSE_DOWN, () => {
// This mouse event is outside the menubar so it counts as a focus out
if (this.isFocused) {
this.setUnfocusedState();
}
}));
this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_IN, (e) => {
let event = e as FocusEvent;
if (event.relatedTarget) {
if (!this.container.contains(event.relatedTarget as HTMLElement)) {
this.focusToReturn = event.relatedTarget as HTMLElement;
}
}
}));
this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_OUT, (e) => {
let event = e as FocusEvent;
if (event.relatedTarget) {
if (!this.container.contains(event.relatedTarget as HTMLElement)) {
this.focusToReturn = null;
this.setUnfocusedState();
}
}
}));
this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
if (!this.currentEnableMenuBarMnemonics || !e.altKey || e.ctrlKey || e.defaultPrevented) {
return;
}
const key = KeyCodeUtils.fromString(e.key);
if (!this.mnemonics.has(key)) {
return;
}
// Prevent conflicts with keybindings
const standardKeyboardEvent = new StandardKeyboardEvent(e);
const resolvedResult = this.keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target);
if (resolvedResult) {
return;
}
this.mnemonicsInUse = true;
this.updateMnemonicVisibility(true);
const menuIndex = this.mnemonics.get(key);
this.onMenuTriggered(menuIndex, false);
}));
}
}
private onMenuTriggered(menuIndex: number, clicked: boolean) {
if (this.isOpen) {
if (this.isCurrentMenu(menuIndex)) {
this.setUnfocusedState();
} else {
this.cleanupCustomMenu();
this.showCustomMenu(menuIndex, this.openedViaKeyboard);
}
} else {
this.focusedMenu = { index: menuIndex };
this.openedViaKeyboard = !clicked;
this.focusState = MenubarState.OPEN;
}
}
private focusPrevious(): void {
if (!this.focusedMenu) {
return;
}
let newFocusedIndex = (this.focusedMenu.index - 1 + this.customMenus.length) % this.customMenus.length;
if (newFocusedIndex === this.focusedMenu.index) {
return;
}
if (this.isOpen) {
this.cleanupCustomMenu();
this.showCustomMenu(newFocusedIndex);
} else if (this.isFocused) {
this.focusedMenu.index = newFocusedIndex;
this.customMenus[newFocusedIndex].buttonElement.focus();
}
}
private focusNext(): void {
if (!this.focusedMenu) {
return;
}
let newFocusedIndex = (this.focusedMenu.index + 1) % this.customMenus.length;
if (newFocusedIndex === this.focusedMenu.index) {
return;
}
if (this.isOpen) {
this.cleanupCustomMenu();
this.showCustomMenu(newFocusedIndex);
} else if (this.isFocused) {
this.focusedMenu.index = newFocusedIndex;
this.customMenus[newFocusedIndex].buttonElement.focus();
}
}
private getMenubarKeybinding(id: string): IMenubarKeybinding {
const binding = this.keybindingService.lookupKeybinding(id);
if (!binding) {
return undefined;
}
// first try to resolve a native accelerator
const electronAccelerator = binding.getElectronAccelerator();
if (electronAccelerator) {
return { label: electronAccelerator };
}
// we need this fallback to support keybindings that cannot show in electron menus (e.g. chords)
const acceleratorLabel = binding.getLabel();
if (acceleratorLabel) {
return { label: acceleratorLabel, isNative: false };
}
return null;
}
private populateMenuItems(menu: IMenu, menuToPopulate: IMenubarMenu, keybindings: { [id: string]: IMenubarKeybinding }) {
let groups = menu.getActions();
for (let group of groups) {
const [, actions] = group;
actions.forEach(menuItem => {
if (menuItem instanceof SubmenuItemAction) {
const submenu = { items: [] };
const menuToDispose = this.menuService.createMenu(menuItem.item.submenu, this.contextKeyService);
this.populateMenuItems(menuToDispose, submenu, keybindings);
let menubarSubmenuItem: IMenubarMenuItemSubmenu = {
id: menuItem.id,
label: menuItem.label,
submenu: submenu
};
menuToPopulate.items.push(menubarSubmenuItem);
menuToDispose.dispose();
} else {
let menubarMenuItem: IMenubarMenuItemAction = {
id: menuItem.id,
label: menuItem.label
};
if (menuItem.checked) {
menubarMenuItem.checked = true;
}
if (!menuItem.enabled) {
menubarMenuItem.enabled = false;
}
menubarMenuItem.label = this.calculateActionLabel(menubarMenuItem);
keybindings[menuItem.id] = this.getMenubarKeybinding(menuItem.id);
menuToPopulate.items.push(menubarMenuItem);
}
});
menuToPopulate.items.push({ id: 'vscode.menubar.separator' });
}
if (menuToPopulate.items.length > 0) {
menuToPopulate.items.pop();
}
}
private getAdditionalKeybindings(): { [id: string]: IMenubarKeybinding } {
const keybindings = {};
if (isMacintosh) {
keybindings['workbench.action.quit'] = (this.getMenubarKeybinding('workbench.action.quit'));
}
return keybindings;
}
private getMenubarMenus(menubarData: IMenubarData): boolean {
if (!menubarData) {
return false;
}
menubarData.keybindings = this.getAdditionalKeybindings();
for (let topLevelMenuName of Object.keys(this.topLevelMenus)) {
const menu = this.topLevelMenus[topLevelMenuName];
let menubarMenu: IMenubarMenu = { items: [] };
this.populateMenuItems(menu, menubarMenu, menubarData.keybindings);
if (menubarMenu.items.length === 0) {
// Menus are incomplete
return false;
}
menubarData.menus[topLevelMenuName] = menubarMenu;
}
return true;
}
private isCurrentMenu(menuIndex: number): boolean {
if (!this.focusedMenu) {
return false;
}
return this.focusedMenu.index === menuIndex;
}
private cleanupCustomMenu(): void {
if (this.focusedMenu) {
// Remove focus from the menus first
this.customMenus[this.focusedMenu.index].buttonElement.focus();
if (this.focusedMenu.holder) {
DOM.removeClass(this.focusedMenu.holder.parentElement, 'open');
this.focusedMenu.holder.remove();
}
if (this.focusedMenu.widget) {
this.focusedMenu.widget.dispose();
}
this.focusedMenu = { index: this.focusedMenu.index };
}
}
private showCustomMenu(menuIndex: number, selectFirst = true): void {
const customMenu = this.customMenus[menuIndex];
const menuHolder = $('div.menubar-menu-items-holder');
DOM.addClass(customMenu.buttonElement, 'open');
menuHolder.style.top = `${this.container.clientHeight}px`;
menuHolder.style.left = `${customMenu.buttonElement.getBoundingClientRect().left}px`;
customMenu.buttonElement.appendChild(menuHolder);
let menuOptions: IMenuOptions = {
getKeyBinding: (action) => this.keybindingService.lookupKeybinding(action.id),
actionRunner: this.actionRunner,
enableMnemonics: this.mnemonicsInUse && this.currentEnableMenuBarMnemonics,
ariaLabel: customMenu.buttonElement.attributes['aria-label'].value
};
let menuWidget = this._register(new Menu(menuHolder, customMenu.actions, menuOptions));
this._register(attachMenuStyler(menuWidget, this.themeService));
this._register(menuWidget.onDidCancel(() => {
this.focusState = MenubarState.FOCUSED;
}));
this._register(menuWidget.onDidBlur(() => {
setTimeout(() => {
this.cleanupCustomMenu();
}, 100);
}));
menuWidget.focus(selectFirst);
this.focusedMenu = {
index: menuIndex,
holder: menuHolder,
widget: menuWidget
};
}
public get onVisibilityChange(): Event<boolean> {
return this._onVisibilityChange.event;
}
public get onFocusStateChange(): Event<boolean> {
return this._onFocusStateChange.event;
}
public layout(dimension: DOM.Dimension) {
if (this.container) {
this.container.style.height = `${dimension.height}px`;
}
if (!this.isVisible) {
this.hideMenubar();
} else {
this.showMenubar();
}
}
public getMenubarItemsDimensions(): DOM.Dimension {
if (this.customMenus) {
const left = this.customMenus[0].buttonElement.getBoundingClientRect().left;
const right = this.customMenus[this.customMenus.length - 1].buttonElement.getBoundingClientRect().right;
return new DOM.Dimension(right - left, this.container.clientHeight);
}
return new DOM.Dimension(0, 0);
}
public create(parent: HTMLElement): HTMLElement {
this.container = parent;
// Build the menubar
if (this.container) {
this.doSetupMenubar();
if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') {
this.setUnfocusedState();
}
}
return this.container;
}
}
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const menubarActiveWindowFgColor = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND);
if (menubarActiveWindowFgColor) {
collector.addRule(`
.monaco-workbench .menubar > .menubar-menu-button {
color: ${menubarActiveWindowFgColor};
}
`);
}
const menubarInactiveWindowFgColor = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND);
if (menubarInactiveWindowFgColor) {
collector.addRule(`
.monaco-workbench .menubar.inactive > .menubar-menu-button {
color: ${menubarInactiveWindowFgColor};
}
`);
}
const menubarSelectedFgColor = theme.getColor(MENUBAR_SELECTION_FOREGROUND);
if (menubarSelectedFgColor) {
collector.addRule(`
.monaco-workbench .menubar > .menubar-menu-button.open,
.monaco-workbench .menubar > .menubar-menu-button:focus,
.monaco-workbench .menubar:not(:focus-within) > .menubar-menu-button:hover {
color: ${menubarSelectedFgColor};
}
`);
}
const menubarSelectedBgColor = theme.getColor(MENUBAR_SELECTION_BACKGROUND);
if (menubarSelectedBgColor) {
collector.addRule(`
.monaco-workbench .menubar > .menubar-menu-button.open,
.monaco-workbench .menubar > .menubar-menu-button:focus,
.monaco-workbench .menubar:not(:focus-within) > .menubar-menu-button:hover {
background-color: ${menubarSelectedBgColor};
}
`);
}
const menubarSelectedBorderColor = theme.getColor(MENUBAR_SELECTION_BORDER);
if (menubarSelectedBorderColor) {
collector.addRule(`
.monaco-workbench .menubar > .menubar-menu-button:hover {
outline: dashed 1px;
}
.monaco-workbench .menubar > .menubar-menu-button.open,
.monaco-workbench .menubar > .menubar-menu-button:focus {
outline: solid 1px;
}
.monaco-workbench .menubar > .menubar-menu-button.open,
.monaco-workbench .menubar > .menubar-menu-button:focus,
.monaco-workbench .menubar > .menubar-menu-button:hover {
outline-offset: -1px;
outline-color: ${menubarSelectedBorderColor};
}
`);
}
});
type ModifierKey = 'alt' | 'ctrl' | 'shift';
interface IModifierKeyStatus {
altKey: boolean;
shiftKey: boolean;
ctrlKey: boolean;
lastKeyPressed?: ModifierKey;
lastKeyReleased?: ModifierKey;
}
class ModifierKeyEmitter extends Emitter<IModifierKeyStatus> {
private _subscriptions: IDisposable[] = [];
private _keyStatus: IModifierKeyStatus;
private static instance: ModifierKeyEmitter;
private constructor(windowService: IWindowService) {
super();
this._keyStatus = {
altKey: false,
shiftKey: false,
ctrlKey: false
};
this._subscriptions.push(domEvent(document.body, 'keydown')(e => {
const event = new StandardKeyboardEvent(e);
if (e.altKey && !this._keyStatus.altKey) {
this._keyStatus.lastKeyPressed = 'alt';
} else if (e.ctrlKey && !this._keyStatus.ctrlKey) {
this._keyStatus.lastKeyPressed = 'ctrl';
} else if (e.shiftKey && !this._keyStatus.shiftKey) {
this._keyStatus.lastKeyPressed = 'shift';
} else if (event.keyCode !== KeyCode.Alt) {
this._keyStatus.lastKeyPressed = undefined;
} else {
return;
}
this._keyStatus.altKey = e.altKey;
this._keyStatus.ctrlKey = e.ctrlKey;
this._keyStatus.shiftKey = e.shiftKey;
if (this._keyStatus.lastKeyPressed) {
this.fire(this._keyStatus);
}
}));
this._subscriptions.push(domEvent(document.body, 'keyup')(e => {
if (!e.altKey && this._keyStatus.altKey) {
this._keyStatus.lastKeyReleased = 'alt';
} else if (!e.ctrlKey && this._keyStatus.ctrlKey) {
this._keyStatus.lastKeyReleased = 'ctrl';
} else if (!e.shiftKey && this._keyStatus.shiftKey) {
this._keyStatus.lastKeyReleased = 'shift';
} else {
this._keyStatus.lastKeyReleased = undefined;
}
if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {
this._keyStatus.lastKeyPressed = undefined;
}
this._keyStatus.altKey = e.altKey;
this._keyStatus.ctrlKey = e.ctrlKey;
this._keyStatus.shiftKey = e.shiftKey;
if (this._keyStatus.lastKeyReleased) {
this.fire(this._keyStatus);
}
}));
this._subscriptions.push(domEvent(document.body, 'mousedown')(e => {
this._keyStatus.lastKeyPressed = undefined;
}));
this._subscriptions.push(windowService.onDidChangeFocus(focused => {
if (!focused) {
this._keyStatus.lastKeyPressed = undefined;
this._keyStatus.lastKeyReleased = undefined;
this._keyStatus.altKey = false;
this._keyStatus.shiftKey = false;
this._keyStatus.shiftKey = false;
this.fire(this._keyStatus);
}
}));
}
static getInstance(windowService: IWindowService) {
if (!ModifierKeyEmitter.instance) {
ModifierKeyEmitter.instance = new ModifierKeyEmitter(windowService);
}
return ModifierKeyEmitter.instance;
}
dispose() {
super.dispose();
this._subscriptions = dispose(this._subscriptions);
}
}
| src/vs/workbench/browser/parts/titlebar/menubarControl.ts | 1 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.9985983967781067,
0.049726199358701706,
0.00016272290667984635,
0.0001718433341011405,
0.20789246261119843
] |
{
"id": 2,
"code_window": [
"\t\t\tthis._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => {\n",
"\t\t\t\tlet event = new StandardKeyboardEvent(e as KeyboardEvent);\n",
"\t\t\t\tlet eventHandled = true;\n",
"\t\t\t\tconst key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown;\n",
"\n",
"\t\t\t\tif (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusPrevious();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tif (event.equals(KeyCode.LeftArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 844
} | <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><polygon points="9,3 8,5 8,2 6,2 6,0 2,0 2,2 0,2 0,6 2,6 2,8 2,15 16,15 16,3" fill="#F6F6F6"/><path d="M14 4h-4.382l-1 2h-2.618v2h-3v6h12v-10h-1zm0 2h-3.882l.5-1h3.382v1z" fill="#656565"/><polygon points="7,3.018 5,3.018 5,1 3.019,1 3.019,3.018 1,3.018 1,5 3.019,5 3.019,7 5,7 5,5 7,5" fill="#388A34"/><polygon points="14,5 14,6 10.118,6 10.618,5" fill="#F0EFF1"/></svg> | src/vs/workbench/parts/files/electron-browser/media/AddFolder.svg | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017444150580558926,
0.00017444150580558926,
0.00017444150580558926,
0.00017444150580558926,
0
] |
{
"id": 2,
"code_window": [
"\t\t\tthis._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => {\n",
"\t\t\t\tlet event = new StandardKeyboardEvent(e as KeyboardEvent);\n",
"\t\t\t\tlet eventHandled = true;\n",
"\t\t\t\tconst key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown;\n",
"\n",
"\t\t\t\tif (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusPrevious();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tif (event.equals(KeyCode.LeftArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 844
} | /*---------------------------------------------------------------------------------------------
* 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 { IFilter, or, matchesPrefix, matchesStrictPrefix, matchesCamelCase, matchesSubString, matchesContiguousSubString, matchesWords, fuzzyScore, IMatch, fuzzyScoreGraceful, fuzzyScoreGracefulAggressive, FuzzyScorer } from 'vs/base/common/filters';
function filterOk(filter: IFilter, word: string, wordToMatchAgainst: string, highlights?: { start: number; end: number; }[]) {
let r = filter(word, wordToMatchAgainst);
assert(r);
if (highlights) {
assert.deepEqual(r, highlights);
}
}
function filterNotOk(filter: IFilter, word: string, suggestion: string) {
assert(!filter(word, suggestion));
}
suite('Filters', () => {
test('or', () => {
let filter: IFilter;
let counters: number[];
let newFilter = function (i: number, r: boolean): IFilter {
return function (): IMatch[] { counters[i]++; return r as any; };
};
counters = [0, 0];
filter = or(newFilter(0, false), newFilter(1, false));
filterNotOk(filter, 'anything', 'anything');
assert.deepEqual(counters, [1, 1]);
counters = [0, 0];
filter = or(newFilter(0, true), newFilter(1, false));
filterOk(filter, 'anything', 'anything');
assert.deepEqual(counters, [1, 0]);
counters = [0, 0];
filter = or(newFilter(0, true), newFilter(1, true));
filterOk(filter, 'anything', 'anything');
assert.deepEqual(counters, [1, 0]);
counters = [0, 0];
filter = or(newFilter(0, false), newFilter(1, true));
filterOk(filter, 'anything', 'anything');
assert.deepEqual(counters, [1, 1]);
});
test('PrefixFilter - case sensitive', function () {
filterNotOk(matchesStrictPrefix, '', '');
filterOk(matchesStrictPrefix, '', 'anything', []);
filterOk(matchesStrictPrefix, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
filterOk(matchesStrictPrefix, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
filterNotOk(matchesStrictPrefix, 'alpha', 'alp');
filterOk(matchesStrictPrefix, 'a', 'alpha', [{ start: 0, end: 1 }]);
filterNotOk(matchesStrictPrefix, 'x', 'alpha');
filterNotOk(matchesStrictPrefix, 'A', 'alpha');
filterNotOk(matchesStrictPrefix, 'AlPh', 'alPHA');
});
test('PrefixFilter - ignore case', function () {
filterOk(matchesPrefix, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
filterOk(matchesPrefix, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
filterNotOk(matchesPrefix, 'alpha', 'alp');
filterOk(matchesPrefix, 'a', 'alpha', [{ start: 0, end: 1 }]);
filterOk(matchesPrefix, 'ä', 'Älpha', [{ start: 0, end: 1 }]);
filterNotOk(matchesPrefix, 'x', 'alpha');
filterOk(matchesPrefix, 'A', 'alpha', [{ start: 0, end: 1 }]);
filterOk(matchesPrefix, 'AlPh', 'alPHA', [{ start: 0, end: 4 }]);
filterNotOk(matchesPrefix, 'T', '4'); // see https://github.com/Microsoft/vscode/issues/22401
});
test('CamelCaseFilter', () => {
filterNotOk(matchesCamelCase, '', '');
filterOk(matchesCamelCase, '', 'anything', []);
filterOk(matchesCamelCase, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
filterOk(matchesCamelCase, 'AlPhA', 'alpha', [{ start: 0, end: 5 }]);
filterOk(matchesCamelCase, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
filterNotOk(matchesCamelCase, 'alpha', 'alp');
filterOk(matchesCamelCase, 'c', 'CamelCaseRocks', [
{ start: 0, end: 1 }
]);
filterOk(matchesCamelCase, 'cc', 'CamelCaseRocks', [
{ start: 0, end: 1 },
{ start: 5, end: 6 }
]);
filterOk(matchesCamelCase, 'ccr', 'CamelCaseRocks', [
{ start: 0, end: 1 },
{ start: 5, end: 6 },
{ start: 9, end: 10 }
]);
filterOk(matchesCamelCase, 'cacr', 'CamelCaseRocks', [
{ start: 0, end: 2 },
{ start: 5, end: 6 },
{ start: 9, end: 10 }
]);
filterOk(matchesCamelCase, 'cacar', 'CamelCaseRocks', [
{ start: 0, end: 2 },
{ start: 5, end: 7 },
{ start: 9, end: 10 }
]);
filterOk(matchesCamelCase, 'ccarocks', 'CamelCaseRocks', [
{ start: 0, end: 1 },
{ start: 5, end: 7 },
{ start: 9, end: 14 }
]);
filterOk(matchesCamelCase, 'cr', 'CamelCaseRocks', [
{ start: 0, end: 1 },
{ start: 9, end: 10 }
]);
filterOk(matchesCamelCase, 'fba', 'FooBarAbe', [
{ start: 0, end: 1 },
{ start: 3, end: 5 }
]);
filterOk(matchesCamelCase, 'fbar', 'FooBarAbe', [
{ start: 0, end: 1 },
{ start: 3, end: 6 }
]);
filterOk(matchesCamelCase, 'fbara', 'FooBarAbe', [
{ start: 0, end: 1 },
{ start: 3, end: 7 }
]);
filterOk(matchesCamelCase, 'fbaa', 'FooBarAbe', [
{ start: 0, end: 1 },
{ start: 3, end: 5 },
{ start: 6, end: 7 }
]);
filterOk(matchesCamelCase, 'fbaab', 'FooBarAbe', [
{ start: 0, end: 1 },
{ start: 3, end: 5 },
{ start: 6, end: 8 }
]);
filterOk(matchesCamelCase, 'c2d', 'canvasCreation2D', [
{ start: 0, end: 1 },
{ start: 14, end: 16 }
]);
filterOk(matchesCamelCase, 'cce', '_canvasCreationEvent', [
{ start: 1, end: 2 },
{ start: 7, end: 8 },
{ start: 15, end: 16 }
]);
});
test('CamelCaseFilter - #19256', function () {
assert(matchesCamelCase('Debug Console', 'Open: Debug Console'));
assert(matchesCamelCase('Debug console', 'Open: Debug Console'));
assert(matchesCamelCase('debug console', 'Open: Debug Console'));
});
test('matchesContiguousSubString', () => {
filterOk(matchesContiguousSubString, 'cela', 'cancelAnimationFrame()', [
{ start: 3, end: 7 }
]);
});
test('matchesSubString', () => {
filterOk(matchesSubString, 'cmm', 'cancelAnimationFrame()', [
{ start: 0, end: 1 },
{ start: 9, end: 10 },
{ start: 18, end: 19 }
]);
filterOk(matchesSubString, 'abc', 'abcabc', [
{ start: 0, end: 3 },
]);
filterOk(matchesSubString, 'abc', 'aaabbbccc', [
{ start: 0, end: 1 },
{ start: 3, end: 4 },
{ start: 6, end: 7 },
]);
});
test('matchesSubString performance (#35346)', function () {
filterNotOk(matchesSubString, 'aaaaaaaaaaaaaaaaaaaax', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
});
test('WordFilter', () => {
filterOk(matchesWords, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
filterOk(matchesWords, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
filterNotOk(matchesWords, 'alpha', 'alp');
filterOk(matchesWords, 'a', 'alpha', [{ start: 0, end: 1 }]);
filterNotOk(matchesWords, 'x', 'alpha');
filterOk(matchesWords, 'A', 'alpha', [{ start: 0, end: 1 }]);
filterOk(matchesWords, 'AlPh', 'alPHA', [{ start: 0, end: 4 }]);
assert(matchesWords('Debug Console', 'Open: Debug Console'));
filterOk(matchesWords, 'gp', 'Git: Pull', [{ start: 0, end: 1 }, { start: 5, end: 6 }]);
filterOk(matchesWords, 'g p', 'Git: Pull', [{ start: 0, end: 1 }, { start: 4, end: 6 }]);
filterOk(matchesWords, 'gipu', 'Git: Pull', [{ start: 0, end: 2 }, { start: 5, end: 7 }]);
filterOk(matchesWords, 'gp', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 15, end: 16 }]);
filterOk(matchesWords, 'g p', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 14, end: 16 }]);
filterOk(matchesWords, 'gipu', 'Category: Git: Pull', [{ start: 10, end: 12 }, { start: 15, end: 17 }]);
filterNotOk(matchesWords, 'it', 'Git: Pull');
filterNotOk(matchesWords, 'll', 'Git: Pull');
filterOk(matchesWords, 'git: プル', 'git: プル', [{ start: 0, end: 7 }]);
filterOk(matchesWords, 'git プル', 'git: プル', [{ start: 0, end: 3 }, { start: 4, end: 7 }]);
filterOk(matchesWords, 'öäk', 'Öhm: Älles Klar', [{ start: 0, end: 1 }, { start: 5, end: 6 }, { start: 11, end: 12 }]);
assert.ok(matchesWords('gipu', 'Category: Git: Pull', true) === null);
assert.deepEqual(matchesWords('pu', 'Category: Git: Pull', true), [{ start: 15, end: 17 }]);
});
function assertMatches(pattern: string, word: string, decoratedWord: string, filter: FuzzyScorer, opts: { patternPos?: number, wordPos?: number, firstMatchCanBeWeak?: boolean } = {}) {
let r = filter(pattern, pattern.toLowerCase(), opts.patternPos || 0, word, word.toLowerCase(), opts.wordPos || 0, opts.firstMatchCanBeWeak || false);
assert.ok(!decoratedWord === (!r || r[1].length === 0));
if (r) {
const [, matches] = r;
let pos = 0;
for (let i = 0; i < matches.length; i++) {
let actual = matches[i];
let expected = decoratedWord.indexOf('^', pos) - i;
assert.equal(actual, expected);
pos = expected + 1 + i;
}
}
}
test('fuzzyScore, #23215', function () {
assertMatches('tit', 'win.tit', 'win.^t^i^t', fuzzyScore);
assertMatches('title', 'win.title', 'win.^t^i^t^l^e', fuzzyScore);
assertMatches('WordCla', 'WordCharacterClassifier', '^W^o^r^dCharacter^C^l^assifier', fuzzyScore);
assertMatches('WordCCla', 'WordCharacterClassifier', '^W^o^r^d^Character^C^l^assifier', fuzzyScore);
});
test('fuzzyScore, #23332', function () {
assertMatches('dete', '"editor.quickSuggestionsDelay"', undefined, fuzzyScore);
});
test('fuzzyScore, #23190', function () {
assertMatches('c:\\do', '& \'C:\\Documents and Settings\'', '& \'^C^:^\\^D^ocuments and Settings\'', fuzzyScore);
assertMatches('c:\\do', '& \'c:\\Documents and Settings\'', '& \'^c^:^\\^D^ocuments and Settings\'', fuzzyScore);
});
test('fuzzyScore, #23581', function () {
assertMatches('close', 'css.lint.importStatement', '^css.^lint.imp^ort^Stat^ement', fuzzyScore);
assertMatches('close', 'css.colorDecorators.enable', '^css.co^l^orDecorator^s.^enable', fuzzyScore);
assertMatches('close', 'workbench.quickOpen.closeOnFocusOut', 'workbench.quickOpen.^c^l^o^s^eOnFocusOut', fuzzyScore);
assertTopScore(fuzzyScore, 'close', 2, 'css.lint.importStatement', 'css.colorDecorators.enable', 'workbench.quickOpen.closeOnFocusOut');
});
test('fuzzyScore, #23458', function () {
assertMatches('highlight', 'editorHoverHighlight', 'editorHover^H^i^g^h^l^i^g^h^t', fuzzyScore);
assertMatches('hhighlight', 'editorHoverHighlight', 'editor^Hover^H^i^g^h^l^i^g^h^t', fuzzyScore);
assertMatches('dhhighlight', 'editorHoverHighlight', undefined, fuzzyScore);
});
test('fuzzyScore, #23746', function () {
assertMatches('-moz', '-moz-foo', '^-^m^o^z-foo', fuzzyScore);
assertMatches('moz', '-moz-foo', '-^m^o^z-foo', fuzzyScore);
assertMatches('moz', '-moz-animation', '-^m^o^z-animation', fuzzyScore);
assertMatches('moza', '-moz-animation', '-^m^o^z-^animation', fuzzyScore);
});
test('fuzzyScore', () => {
assertMatches('ab', 'abA', '^a^bA', fuzzyScore);
assertMatches('ccm', 'cacmelCase', '^ca^c^melCase', fuzzyScore);
assertMatches('bti', 'the_black_knight', undefined, fuzzyScore);
assertMatches('ccm', 'camelCase', undefined, fuzzyScore);
assertMatches('cmcm', 'camelCase', undefined, fuzzyScore);
assertMatches('BK', 'the_black_knight', 'the_^black_^knight', fuzzyScore);
assertMatches('KeyboardLayout=', 'KeyboardLayout', undefined, fuzzyScore);
assertMatches('LLL', 'SVisualLoggerLogsList', 'SVisual^Logger^Logs^List', fuzzyScore);
assertMatches('LLLL', 'SVilLoLosLi', undefined, fuzzyScore);
assertMatches('LLLL', 'SVisualLoggerLogsList', undefined, fuzzyScore);
assertMatches('TEdit', 'TextEdit', '^Text^E^d^i^t', fuzzyScore);
assertMatches('TEdit', 'TextEditor', '^Text^E^d^i^tor', fuzzyScore);
assertMatches('TEdit', 'Textedit', '^T^exte^d^i^t', fuzzyScore);
assertMatches('TEdit', 'text_edit', '^text_^e^d^i^t', fuzzyScore);
assertMatches('TEditDit', 'TextEditorDecorationType', '^Text^E^d^i^tor^Decorat^ion^Type', fuzzyScore);
assertMatches('TEdit', 'TextEditorDecorationType', '^Text^E^d^i^torDecorationType', fuzzyScore);
assertMatches('Tedit', 'TextEdit', '^Text^E^d^i^t', fuzzyScore);
assertMatches('ba', '?AB?', undefined, fuzzyScore);
assertMatches('bkn', 'the_black_knight', 'the_^black_^k^night', fuzzyScore);
assertMatches('bt', 'the_black_knight', 'the_^black_knigh^t', fuzzyScore);
assertMatches('ccm', 'camelCasecm', '^camel^Casec^m', fuzzyScore);
assertMatches('fdm', 'findModel', '^fin^d^Model', fuzzyScore);
assertMatches('fob', 'foobar', '^f^oo^bar', fuzzyScore);
assertMatches('fobz', 'foobar', undefined, fuzzyScore);
assertMatches('foobar', 'foobar', '^f^o^o^b^a^r', fuzzyScore);
assertMatches('form', 'editor.formatOnSave', 'editor.^f^o^r^matOnSave', fuzzyScore);
assertMatches('g p', 'Git: Pull', '^Git:^ ^Pull', fuzzyScore);
assertMatches('g p', 'Git: Pull', '^Git:^ ^Pull', fuzzyScore);
assertMatches('gip', 'Git: Pull', '^G^it: ^Pull', fuzzyScore);
assertMatches('gip', 'Git: Pull', '^G^it: ^Pull', fuzzyScore);
assertMatches('gp', 'Git: Pull', '^Git: ^Pull', fuzzyScore);
assertMatches('gp', 'Git_Git_Pull', '^Git_Git_^Pull', fuzzyScore);
assertMatches('is', 'ImportStatement', '^Import^Statement', fuzzyScore);
assertMatches('is', 'isValid', '^i^sValid', fuzzyScore);
assertMatches('lowrd', 'lowWord', '^l^o^wWo^r^d', fuzzyScore);
assertMatches('myvable', 'myvariable', '^m^y^v^aria^b^l^e', fuzzyScore);
assertMatches('no', '', undefined, fuzzyScore);
assertMatches('no', 'match', undefined, fuzzyScore);
assertMatches('ob', 'foobar', undefined, fuzzyScore);
assertMatches('sl', 'SVisualLoggerLogsList', '^SVisual^LoggerLogsList', fuzzyScore);
assertMatches('sllll', 'SVisualLoggerLogsList', '^SVisua^l^Logger^Logs^List', fuzzyScore);
assertMatches('Three', 'HTMLHRElement', undefined, fuzzyScore);
assertMatches('Three', 'Three', '^T^h^r^e^e', fuzzyScore);
assertMatches('fo', 'barfoo', undefined, fuzzyScore);
assertMatches('fo', 'bar_foo', 'bar_^f^oo', fuzzyScore);
assertMatches('fo', 'bar_Foo', 'bar_^F^oo', fuzzyScore);
assertMatches('fo', 'bar foo', 'bar ^f^oo', fuzzyScore);
assertMatches('fo', 'bar.foo', 'bar.^f^oo', fuzzyScore);
assertMatches('fo', 'bar/foo', 'bar/^f^oo', fuzzyScore);
assertMatches('fo', 'bar\\foo', 'bar\\^f^oo', fuzzyScore);
});
test('fuzzyScore (first match can be weak)', function () {
assertMatches('Three', 'HTMLHRElement', 'H^TML^H^R^El^ement', fuzzyScore, { firstMatchCanBeWeak: true });
assertMatches('tor', 'constructor', 'construc^t^o^r', fuzzyScore, { firstMatchCanBeWeak: true });
assertMatches('ur', 'constructor', 'constr^ucto^r', fuzzyScore, { firstMatchCanBeWeak: true });
assertTopScore(fuzzyScore, 'tor', 2, 'constructor', 'Thor', 'cTor');
});
test('fuzzyScore, many matches', function () {
assertMatches(
'aaaaaa',
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'^a^a^a^a^a^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
fuzzyScore
);
});
test('fuzzyScore, issue #26423', function () {
assertMatches('baba', 'abababab', undefined, fuzzyScore);
assertMatches(
'fsfsfs',
'dsafdsafdsafdsafdsafdsafdsafasdfdsa',
undefined,
fuzzyScore
);
assertMatches(
'fsfsfsfsfsfsfsf',
'dsafdsafdsafdsafdsafdsafdsafasdfdsafdsafdsafdsafdsfdsafdsfdfdfasdnfdsajfndsjnafjndsajlknfdsa',
undefined,
fuzzyScore
);
});
test('Fuzzy IntelliSense matching vs Haxe metadata completion, #26995', function () {
assertMatches('f', ':Foo', ':^Foo', fuzzyScore);
assertMatches('f', ':foo', ':^foo', fuzzyScore);
});
test('Cannot set property \'1\' of undefined, #26511', function () {
let word = new Array<void>(123).join('a');
let pattern = new Array<void>(120).join('a');
fuzzyScore(pattern, pattern.toLowerCase(), 0, word, word.toLowerCase(), 0, false);
assert.ok(true); // must not explode
});
test('Vscode 1.12 no longer obeys \'sortText\' in completion items (from language server), #26096', function () {
assertMatches(' ', ' group', undefined, fuzzyScore, { patternPos: 2 });
assertMatches(' g', ' group', ' ^group', fuzzyScore, { patternPos: 2 });
assertMatches('g', ' group', ' ^group', fuzzyScore);
assertMatches('g g', ' groupGroup', undefined, fuzzyScore);
assertMatches('g g', ' group Group', ' ^group^ ^Group', fuzzyScore);
assertMatches(' g g', ' group Group', ' ^group^ ^Group', fuzzyScore, { patternPos: 1 });
assertMatches('zz', 'zzGroup', '^z^zGroup', fuzzyScore);
assertMatches('zzg', 'zzGroup', '^z^z^Group', fuzzyScore);
assertMatches('g', 'zzGroup', 'zz^Group', fuzzyScore);
});
function assertTopScore(filter: typeof fuzzyScore, pattern: string, expected: number, ...words: string[]) {
let topScore = -(100 * 10);
let topIdx = 0;
for (let i = 0; i < words.length; i++) {
const word = words[i];
const m = filter(pattern, pattern.toLowerCase(), 0, word, word.toLowerCase(), 0, false);
if (m) {
const [score] = m;
if (score > topScore) {
topScore = score;
topIdx = i;
}
}
}
assert.equal(topIdx, expected, `${pattern} -> actual=${words[topIdx]} <> expected=${words[expected]}`);
}
test('topScore - fuzzyScore', function () {
assertTopScore(fuzzyScore, 'cons', 2, 'ArrayBufferConstructor', 'Console', 'console');
assertTopScore(fuzzyScore, 'Foo', 1, 'foo', 'Foo', 'foo');
// #24904
assertTopScore(fuzzyScore, 'onMess', 1, 'onmessage', 'onMessage', 'onThisMegaEscape');
assertTopScore(fuzzyScore, 'CC', 1, 'camelCase', 'CamelCase');
assertTopScore(fuzzyScore, 'cC', 0, 'camelCase', 'CamelCase');
// assertTopScore(fuzzyScore, 'cC', 1, 'ccfoo', 'camelCase');
// assertTopScore(fuzzyScore, 'cC', 1, 'ccfoo', 'camelCase', 'foo-cC-bar');
// issue #17836
// assertTopScore(fuzzyScore, 'TEdit', 1, 'TextEditorDecorationType', 'TextEdit', 'TextEditor');
assertTopScore(fuzzyScore, 'p', 4, 'parse', 'posix', 'pafdsa', 'path', 'p');
assertTopScore(fuzzyScore, 'pa', 0, 'parse', 'pafdsa', 'path');
// issue #14583
assertTopScore(fuzzyScore, 'log', 3, 'HTMLOptGroupElement', 'ScrollLogicalPosition', 'SVGFEMorphologyElement', 'log', 'logger');
assertTopScore(fuzzyScore, 'e', 2, 'AbstractWorker', 'ActiveXObject', 'else');
// issue #14446
assertTopScore(fuzzyScore, 'workbench.sideb', 1, 'workbench.editor.defaultSideBySideLayout', 'workbench.sideBar.location');
// issue #11423
assertTopScore(fuzzyScore, 'editor.r', 2, 'diffEditor.renderSideBySide', 'editor.overviewRulerlanes', 'editor.renderControlCharacter', 'editor.renderWhitespace');
// assertTopScore(fuzzyScore, 'editor.R', 1, 'diffEditor.renderSideBySide', 'editor.overviewRulerlanes', 'editor.renderControlCharacter', 'editor.renderWhitespace');
// assertTopScore(fuzzyScore, 'Editor.r', 0, 'diffEditor.renderSideBySide', 'editor.overviewRulerlanes', 'editor.renderControlCharacter', 'editor.renderWhitespace');
assertTopScore(fuzzyScore, '-mo', 1, '-ms-ime-mode', '-moz-columns');
// // dupe, issue #14861
assertTopScore(fuzzyScore, 'convertModelPosition', 0, 'convertModelPositionToViewPosition', 'convertViewToModelPosition');
// // dupe, issue #14942
assertTopScore(fuzzyScore, 'is', 0, 'isValidViewletId', 'import statement');
assertTopScore(fuzzyScore, 'title', 1, 'files.trimTrailingWhitespace', 'window.title');
assertTopScore(fuzzyScore, 'const', 1, 'constructor', 'const', 'cuOnstrul');
});
test('Unexpected suggestion scoring, #28791', function () {
assertTopScore(fuzzyScore, '_lines', 1, '_lineStarts', '_lines');
assertTopScore(fuzzyScore, '_lines', 1, '_lineS', '_lines');
assertTopScore(fuzzyScore, '_lineS', 0, '_lineS', '_lines');
});
test('HTML closing tag proposal filtered out #38880', function () {
assertMatches('\t\t<', '\t\t</body>', '^\t^\t^</body>', fuzzyScore, { patternPos: 0 });
assertMatches('\t\t<', '\t\t</body>', '\t\t^</body>', fuzzyScore, { patternPos: 2 });
assertMatches('\t<', '\t</body>', '\t^</body>', fuzzyScore, { patternPos: 1 });
});
test('fuzzyScoreGraceful', () => {
assertMatches('rlut', 'result', undefined, fuzzyScore);
assertMatches('rlut', 'result', '^res^u^l^t', fuzzyScoreGraceful);
assertMatches('cno', 'console', '^co^ns^ole', fuzzyScore);
assertMatches('cno', 'console', '^co^ns^ole', fuzzyScoreGraceful);
assertMatches('cno', 'console', '^c^o^nsole', fuzzyScoreGracefulAggressive);
assertMatches('cno', 'co_new', '^c^o_^new', fuzzyScoreGraceful);
assertMatches('cno', 'co_new', '^c^o_^new', fuzzyScoreGracefulAggressive);
});
});
| src/vs/base/test/common/filters.test.ts | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017808120173867792,
0.00017426373960915953,
0.0001650914055062458,
0.00017446330457460135,
0.0000025265069325541845
] |
{
"id": 2,
"code_window": [
"\t\t\tthis._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => {\n",
"\t\t\t\tlet event = new StandardKeyboardEvent(e as KeyboardEvent);\n",
"\t\t\t\tlet eventHandled = true;\n",
"\t\t\t\tconst key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown;\n",
"\n",
"\t\t\t\tif (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusPrevious();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\tif (event.equals(KeyCode.LeftArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 844
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare const enum LoaderEventType {
LoaderAvailable = 1,
BeginLoadingScript = 10,
EndLoadingScriptOK = 11,
EndLoadingScriptError = 12,
BeginInvokeFactory = 21,
EndInvokeFactory = 22,
NodeBeginEvaluatingScript = 31,
NodeEndEvaluatingScript = 32,
NodeBeginNativeRequire = 33,
NodeEndNativeRequire = 34
}
declare class LoaderEvent {
readonly type: LoaderEventType;
readonly timestamp: number;
readonly detail: string;
}
declare var define: {
(moduleName: string, dependencies: string[], callback: (...args: any[]) => any): any;
(moduleName: string, dependencies: string[], definition: any): any;
(moduleName: string, callback: (...args: any[]) => any): any;
(moduleName: string, definition: any): any;
(dependencies: string[], callback: (...args: any[]) => any): any;
(dependencies: string[], definition: any): any;
};
interface NodeRequire {
toUrl(path: string): string;
(dependencies: string[], callback: (...args: any[]) => any, errorback?: (err: any) => void): any;
config(data: any): any;
onError: Function;
__$__nodeRequire<T>(moduleName: string): T;
getStats(): ReadonlyArray<LoaderEvent>
}
| src/typings/require.d.ts | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00018479707068763673,
0.00017369781562592834,
0.0001691873330855742,
0.0001713893871055916,
0.0000058009245549328625
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tthis.focusPrevious();\n",
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusNext();\n",
"\t\t\t\t} else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) {\n",
"\t\t\t\t\tthis.setUnfocusedState();\n",
"\t\t\t\t} else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 846
} | /*---------------------------------------------------------------------------------------------
* 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.titlebar {
box-sizing: border-box;
width: 100%;
padding: 0 70px;
overflow: hidden;
flex-shrink: 0;
align-items: center;
justify-content: center;
user-select: none;
zoom: 1; /* prevent zooming */
line-height: 22px;
height: 22px;
display: flex;
}
.monaco-workbench > .part.titlebar > .titlebar-drag-region {
top: 0;
left: 0;
display: block;
position: absolute;
width: 100%;
height: 100%;
z-index: -1;
-webkit-app-region: drag;
}
.monaco-workbench > .part.titlebar > .window-title {
flex: 0 1 auto;
font-size: 12px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin-left: auto;
margin-right: auto;
zoom: 1; /* prevent zooming */
}
/* Windows/Linux: Rules for custom title (icon, window controls) */
.monaco-workbench.windows > .part.titlebar,
.monaco-workbench.linux > .part.titlebar {
padding: 0;
height: 30px;
line-height: 30px;
justify-content: left;
overflow: visible;
}
.monaco-workbench.windows > .part.titlebar > .window-title,
.monaco-workbench.linux > .part.titlebar > .window-title {
cursor: default;
}
.monaco-workbench.linux > .part.titlebar > .window-title {
font-size: inherit;
}
.monaco-workbench.windows > .part.titlebar > .resizer,
.monaco-workbench.linux > .part.titlebar > .resizer {
-webkit-app-region: no-drag;
position: absolute;
top: 0;
width: 100%;
height: 20%;
}
.monaco-workbench.windows.fullscreen > .part.titlebar > .resizer,
.monaco-workbench.linux.fullscreen > .part.titlebar > .resizer {
display: none;
}
.monaco-workbench > .part.titlebar > .window-appicon {
width: 35px;
height: 100%;
position: relative;
z-index: 99;
background-image: url('code-icon.svg');
background-repeat: no-repeat;
background-position: center center;
background-size: 16px;
flex-shrink: 0;
}
.monaco-workbench.fullscreen > .part.titlebar > .window-appicon {
display: none;
}
.monaco-workbench > .part.titlebar > .window-controls-container {
display: flex;
flex-grow: 0;
flex-shrink: 0;
text-align: center;
position: relative;
z-index: 99;
-webkit-app-region: no-drag;
height: 100%;
width: 138px;
margin-left: auto;
}
.monaco-workbench.fullscreen > .part.titlebar > .window-controls-container {
display: none;
}
.monaco-workbench > .part.titlebar > .window-controls-container > .window-icon-bg {
display: inline-block;
-webkit-app-region: no-drag;
height: 100%;
width: 33.34%;
}
.monaco-workbench > .part.titlebar > .window-controls-container .window-icon svg {
shape-rendering: crispEdges;
text-align: center;
}
.monaco-workbench > .part.titlebar.titlebar > .window-controls-container .window-close {
-webkit-mask: url('chrome-close.svg') no-repeat 50% 50%;
}
.monaco-workbench > .part.titlebar.titlebar > .window-controls-container .window-unmaximize {
-webkit-mask: url('chrome-restore.svg') no-repeat 50% 50%;
}
.monaco-workbench > .part.titlebar > .window-controls-container .window-maximize {
-webkit-mask: url('chrome-maximize.svg') no-repeat 50% 50%;
}
.monaco-workbench > .part.titlebar > .window-controls-container .window-minimize {
-webkit-mask: url('chrome-minimize.svg') no-repeat 50% 50%;
}
.monaco-workbench > .part.titlebar > .window-controls-container > .window-icon-bg > .window-icon {
height: 100%;
width: 100%;
-webkit-mask-size: 23.1%;
}
.monaco-workbench > .part.titlebar > .window-controls-container > .window-icon-bg:hover {
background-color: rgba(255, 255, 255, 0.1);
}
.monaco-workbench > .part.titlebar.light > .window-controls-container > .window-icon-bg:hover {
background-color: rgba(0, 0, 0, 0.1);
}
.monaco-workbench > .part.titlebar > .window-controls-container > .window-icon-bg.window-close-bg:hover {
background-color: rgba(232, 17, 35, 0.9);
}
.monaco-workbench > .part.titlebar > .window-controls-container .window-icon.window-close:hover {
background-color: white;
}
/* Menubar styles */
.monaco-workbench .menubar {
display: flex;
flex-shrink: 1;
box-sizing: border-box;
height: 30px;
-webkit-app-region: no-drag;
overflow: hidden;
flex-wrap: wrap;
}
.monaco-workbench.fullscreen .menubar {
margin: 0px;
padding: 0px 5px;
}
.monaco-workbench .menubar > .menubar-menu-button {
align-items: center;
box-sizing: border-box;
padding: 0px 8px;
cursor: default;
-webkit-app-region: no-drag;
zoom: 1;
white-space: nowrap;
}
.monaco-workbench .menubar .menubar-menu-items-holder {
position: absolute;
left: 0px;
opacity: 1;
z-index: 2000;
}
.monaco-workbench .menubar .menubar-menu-items-holder.monaco-menu-container {
font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif;
outline: 0;
border: none;
}
.monaco-workbench .menubar .menubar-menu-items-holder.monaco-menu-container :focus {
outline: 0;
} | src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css | 1 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017436983762308955,
0.00017010032024700195,
0.00016622585826553404,
0.0001698647829471156,
0.0000020688191852968885
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tthis.focusPrevious();\n",
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusNext();\n",
"\t\t\t\t} else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) {\n",
"\t\t\t\t\tthis.setUnfocusedState();\n",
"\t\t\t\t} else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 846
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as fs from 'fs';
import { execSync } from 'child_process';
import { Readable } from 'stream';
import * as crypto from 'crypto';
import * as azure from 'azure-storage';
import * as mime from 'mime';
import * as minimist from 'minimist';
import { DocumentClient, NewDocument } from 'documentdb';
if (process.argv.length < 6) {
console.error('Usage: node publish.js <product> <platform> <type> <name> <version> <commit> <is_update> <file>');
process.exit(-1);
}
function hashStream(hashName: string, stream: Readable): Promise<string> {
return new Promise<string>((c, e) => {
const shasum = crypto.createHash(hashName);
stream
.on('data', shasum.update.bind(shasum))
.on('error', e)
.on('close', () => c(shasum.digest('hex')));
});
}
interface Config {
id: string;
frozen: boolean;
}
function createDefaultConfig(quality: string): Config {
return {
id: quality,
frozen: false
};
}
function getConfig(quality: string): Promise<Config> {
const client = new DocumentClient(process.env['AZURE_DOCUMENTDB_ENDPOINT']!, { masterKey: process.env['AZURE_DOCUMENTDB_MASTERKEY'] });
const collection = 'dbs/builds/colls/config';
const query = {
query: `SELECT TOP 1 * FROM c WHERE c.id = @quality`,
parameters: [
{ name: '@quality', value: quality }
]
};
return new Promise<Config>((c, e) => {
client.queryDocuments(collection, query).toArray((err, results) => {
if (err && err.code !== 409) { return e(err); }
c(!results || results.length === 0 ? createDefaultConfig(quality) : results[0] as any as Config);
});
});
}
interface Asset {
platform: string;
type: string;
url: string;
mooncakeUrl: string;
hash: string;
sha256hash: string;
size: number;
supportsFastUpdate?: boolean;
}
function createOrUpdate(commit: string, quality: string, platform: string, type: string, release: NewDocument, asset: Asset, isUpdate: boolean): Promise<void> {
const client = new DocumentClient(process.env['AZURE_DOCUMENTDB_ENDPOINT']!, { masterKey: process.env['AZURE_DOCUMENTDB_MASTERKEY'] });
const collection = 'dbs/builds/colls/' + quality;
const updateQuery = {
query: 'SELECT TOP 1 * FROM c WHERE c.id = @id',
parameters: [{ name: '@id', value: commit }]
};
let updateTries = 0;
function update(): Promise<void> {
updateTries++;
return new Promise<void>((c, e) => {
client.queryDocuments(collection, updateQuery).toArray((err, results) => {
if (err) { return e(err); }
if (results.length !== 1) { return e(new Error('No documents')); }
const release = results[0];
release.assets = [
...release.assets.filter((a: any) => !(a.platform === platform && a.type === type)),
asset
];
if (isUpdate) {
release.updates[platform] = type;
}
client.replaceDocument(release._self, release, err => {
if (err && err.code === 409 && updateTries < 5) { return c(update()); }
if (err) { return e(err); }
console.log('Build successfully updated.');
c();
});
});
});
}
return new Promise<void>((c, e) => {
client.createDocument(collection, release, err => {
if (err && err.code === 409) { return c(update()); }
if (err) { return e(err); }
console.log('Build successfully published.');
c();
});
});
}
async function assertContainer(blobService: azure.BlobService, quality: string): Promise<void> {
await new Promise((c, e) => blobService.createContainerIfNotExists(quality, { publicAccessLevel: 'blob' }, err => err ? e(err) : c()));
}
async function doesAssetExist(blobService: azure.BlobService, quality: string, blobName: string): Promise<boolean | undefined> {
const existsResult = await new Promise<azure.BlobService.BlobResult>((c, e) => blobService.doesBlobExist(quality, blobName, (err, r) => err ? e(err) : c(r)));
return existsResult.exists;
}
async function uploadBlob(blobService: azure.BlobService, quality: string, blobName: string, file: string): Promise<void> {
const blobOptions: azure.BlobService.CreateBlockBlobRequestOptions = {
contentSettings: {
contentType: mime.lookup(file),
cacheControl: 'max-age=31536000, public'
}
};
await new Promise((c, e) => blobService.createBlockBlobFromLocalFile(quality, blobName, file, blobOptions, err => err ? e(err) : c()));
}
interface PublishOptions {
'upload-only': boolean;
}
async function publish(commit: string, quality: string, platform: string, type: string, name: string, version: string, _isUpdate: string, file: string, opts: PublishOptions): Promise<void> {
const isUpdate = _isUpdate === 'true';
const queuedBy = process.env['BUILD_QUEUEDBY']!;
const sourceBranch = process.env['BUILD_SOURCEBRANCH']!;
const isReleased = quality === 'insider'
&& /^master$|^refs\/heads\/master$/.test(sourceBranch)
&& /Project Collection Service Accounts|Microsoft.VisualStudio.Services.TFS/.test(queuedBy);
console.log('Publishing...');
console.log('Quality:', quality);
console.log('Platform:', platform);
console.log('Type:', type);
console.log('Name:', name);
console.log('Version:', version);
console.log('Commit:', commit);
console.log('Is Update:', isUpdate);
console.log('Is Released:', isReleased);
console.log('File:', file);
const stat = await new Promise<fs.Stats>((c, e) => fs.stat(file, (err, stat) => err ? e(err) : c(stat)));
const size = stat.size;
console.log('Size:', size);
const stream = fs.createReadStream(file);
const [sha1hash, sha256hash] = await Promise.all([hashStream('sha1', stream), hashStream('sha256', stream)]);
console.log('SHA1:', sha1hash);
console.log('SHA256:', sha256hash);
const blobName = commit + '/' + name;
const storageAccount = process.env['AZURE_STORAGE_ACCOUNT_2']!;
const blobService = azure.createBlobService(storageAccount, process.env['AZURE_STORAGE_ACCESS_KEY_2']!)
.withFilter(new azure.ExponentialRetryPolicyFilter(20));
const mooncakeBlobService = azure.createBlobService(storageAccount, process.env['MOONCAKE_STORAGE_ACCESS_KEY']!, `${storageAccount}.blob.core.chinacloudapi.cn`)
.withFilter(new azure.ExponentialRetryPolicyFilter(20));
// mooncake is fussy and far away, this is needed!
mooncakeBlobService.defaultClientRequestTimeoutInMs = 10 * 60 * 1000;
await Promise.all([
assertContainer(blobService, quality),
assertContainer(mooncakeBlobService, quality)
]);
const [blobExists, moooncakeBlobExists] = await Promise.all([
doesAssetExist(blobService, quality, blobName),
doesAssetExist(mooncakeBlobService, quality, blobName)
]);
const promises: Array<Promise<void>> = [];
if (!blobExists) {
promises.push(uploadBlob(blobService, quality, blobName, file));
}
if (!moooncakeBlobExists) {
promises.push(uploadBlob(mooncakeBlobService, quality, blobName, file));
}
if (promises.length === 0) {
console.log(`Blob ${quality}, ${blobName} already exists, not publishing again.`);
return;
}
console.log('Uploading blobs to Azure storage...');
await Promise.all(promises);
console.log('Blobs successfully uploaded.');
const config = await getConfig(quality);
console.log('Quality config:', config);
const asset: Asset = {
platform: platform,
type: type,
url: `${process.env['AZURE_CDN_URL']}/${quality}/${blobName}`,
mooncakeUrl: `${process.env['MOONCAKE_CDN_URL']}/${quality}/${blobName}`,
hash: sha1hash,
sha256hash,
size
};
// Remove this if we ever need to rollback fast updates for windows
if (/win32/.test(platform)) {
asset.supportsFastUpdate = true;
}
console.log('Asset:', JSON.stringify(asset, null, ' '));
const release = {
id: commit,
timestamp: (new Date()).getTime(),
version,
isReleased: config.frozen ? false : isReleased,
sourceBranch,
queuedBy,
assets: [] as Array<Asset>,
updates: {} as any
};
if (!opts['upload-only']) {
release.assets.push(asset);
if (isUpdate) {
release.updates[platform] = type;
}
}
await createOrUpdate(commit, quality, platform, type, release, asset, isUpdate);
}
function main(): void {
if (process.env['VSCODE_BUILD_SKIP_PUBLISH']) {
console.warn('Skipping publish due to VSCODE_BUILD_SKIP_PUBLISH');
return;
}
const opts = minimist<PublishOptions>(process.argv.slice(2), {
boolean: ['upload-only']
});
const [quality, platform, type, name, version, _isUpdate, file] = opts._;
const commit = execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();
publish(commit, quality, platform, type, name, version, _isUpdate, file, opts).catch(err => {
console.error(err);
process.exit(1);
});
}
main();
| build/azure-pipelines/common/publish.ts | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017697953444439918,
0.00017259579908568412,
0.00016697836690582335,
0.00017269517411477864,
0.0000022905551304575056
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tthis.focusPrevious();\n",
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusNext();\n",
"\t\t\t\t} else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) {\n",
"\t\t\t\t\tthis.setUnfocusedState();\n",
"\t\t\t\t} else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 846
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Application } from '../../application';
export function setup() {
describe('Editor', () => {
it('shows correct quick outline', async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('www');
await app.workbench.quickopen.openQuickOutline();
await app.workbench.quickopen.waitForQuickOpenElements(names => names.length >= 6);
});
it(`finds 'All References' to 'app'`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('www');
const references = await app.workbench.editor.findReferences('www', 'app', 7);
await references.waitForReferencesCountInTitle(3);
await references.waitForReferencesCount(3);
await references.close();
});
it(`renames local 'app' variable`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('www');
await app.workbench.editor.rename('www', 7, 'app', 'newApp');
await app.workbench.editor.waitForEditorContents('www', contents => contents.indexOf('newApp') > -1);
});
// it('folds/unfolds the code correctly', async function () {
// await app.workbench.quickopen.openFile('www');
// // Fold
// await app.workbench.editor.foldAtLine(3);
// await app.workbench.editor.waitUntilShown(3);
// await app.workbench.editor.waitUntilHidden(4);
// await app.workbench.editor.waitUntilHidden(5);
// // Unfold
// await app.workbench.editor.unfoldAtLine(3);
// await app.workbench.editor.waitUntilShown(3);
// await app.workbench.editor.waitUntilShown(4);
// await app.workbench.editor.waitUntilShown(5);
// });
it(`verifies that 'Go To Definition' works`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('app.js');
await app.workbench.editor.gotoDefinition('app.js', 'app', 14);
await app.workbench.editor.waitForHighlightingLine('app.js', 11);
});
it(`verifies that 'Peek Definition' works`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('app.js');
const peek = await app.workbench.editor.peekDefinition('app.js', 'app', 14);
await peek.waitForFile('app.js');
});
});
} | test/smoke/src/areas/editor/editor.test.ts | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017487234435975552,
0.00017060052778106183,
0.00016868217790033668,
0.00017000475781969726,
0.0000019073180510531529
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tthis.focusPrevious();\n",
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) {\n",
"\t\t\t\t\tthis.focusNext();\n",
"\t\t\t\t} else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) {\n",
"\t\t\t\t\tthis.setUnfocusedState();\n",
"\t\t\t\t} else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (event.equals(KeyCode.RightArrow)) {\n"
],
"file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts",
"type": "replace",
"edit_start_line_idx": 846
} | <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#424242" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg> | src/vs/editor/contrib/suggest/media/close.svg | 0 | https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535 | [
0.00017186757759191096,
0.00017186757759191096,
0.00017186757759191096,
0.00017186757759191096,
0
] |
{
"id": 0,
"code_window": [
"\t\"reportIssueUrl\": \"https://github.com/microsoft/vscode/issues/new\",\n",
"\t\"urlProtocol\": \"code-oss\",\n",
"\t\"extensionAllowedProposedApi\": [\n",
"\t\t\"ms-vscode.vscode-js-profile-flame\",\n",
"\t\t\"ms-vscode.vscode-js-profile-table\",\n",
"\t\t\"ms-vscode.references-view\",\n",
"\t\t\"ms-vscode.github-browser\",\n",
"\t\t\"ms-vscode.github-richnav\"\n",
"\t],\n",
"\t\"builtInExtensions\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IProductConfiguration } from 'vs/platform/product/common/productService';
import { isWeb } from 'vs/base/common/platform';
import { env } from 'vs/base/common/process';
import { FileAccess } from 'vs/base/common/network';
import { dirname, joinPath } from 'vs/base/common/resources';
let product: IProductConfiguration;
// Web or Native (sandbox TODO@sandbox need to add all properties of product.json)
if (isWeb || typeof require === 'undefined' || typeof require.__$__nodeRequire !== 'function') {
// Built time configuration (do NOT modify)
product = { /*BUILD->INSERT_PRODUCT_CONFIGURATION*/ } as IProductConfiguration;
// Running out of sources
if (Object.keys(product).length === 0) {
Object.assign(product, {
version: '1.52.0-dev',
nameShort: isWeb ? 'Code Web - OSS Dev' : 'Code - OSS Dev',
nameLong: isWeb ? 'Code Web - OSS Dev' : 'Code - OSS Dev',
applicationName: 'code-oss',
dataFolderName: '.vscode-oss',
urlProtocol: 'code-oss',
reportIssueUrl: 'https://github.com/microsoft/vscode/issues/new',
licenseName: 'MIT',
licenseUrl: 'https://github.com/microsoft/vscode/blob/master/LICENSE.txt',
extensionAllowedProposedApi: [
'ms-vscode.vscode-js-profile-flame',
'ms-vscode.vscode-js-profile-table',
'ms-vscode.references-view',
'ms-vscode.github-browser'
],
});
}
}
// Native (non-sandboxed)
else {
// Obtain values from product.json and package.json
const rootPath = dirname(FileAccess.asFileUri('', require));
product = require.__$__nodeRequire(joinPath(rootPath, 'product.json').fsPath);
const pkg = require.__$__nodeRequire(joinPath(rootPath, 'package.json').fsPath) as { version: string; };
// Running out of sources
if (env['VSCODE_DEV']) {
Object.assign(product, {
nameShort: `${product.nameShort} Dev`,
nameLong: `${product.nameLong} Dev`,
dataFolderName: `${product.dataFolderName}-dev`
});
}
Object.assign(product, {
version: pkg.version
});
}
export default product;
| src/vs/platform/product/common/product.ts | 1 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.0039235446602106094,
0.0008587673655711114,
0.00016804790357127786,
0.0001737408310873434,
0.0013037355383858085
] |
{
"id": 0,
"code_window": [
"\t\"reportIssueUrl\": \"https://github.com/microsoft/vscode/issues/new\",\n",
"\t\"urlProtocol\": \"code-oss\",\n",
"\t\"extensionAllowedProposedApi\": [\n",
"\t\t\"ms-vscode.vscode-js-profile-flame\",\n",
"\t\t\"ms-vscode.vscode-js-profile-table\",\n",
"\t\t\"ms-vscode.references-view\",\n",
"\t\t\"ms-vscode.github-browser\",\n",
"\t\t\"ms-vscode.github-richnav\"\n",
"\t],\n",
"\t\"builtInExtensions\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 27
} | name: English Please
on:
issues:
types: [edited]
# also make changes in ./on-label.yml and ./on-open.yml
jobs:
main:
runs-on: ubuntu-latest
steps:
- name: Checkout Actions
if: contains(github.event.issue.labels.*.name, '*english-please')
uses: actions/checkout@v2
with:
repository: "microsoft/vscode-github-triage-actions"
ref: v40
path: ./actions
- name: Install Actions
if: contains(github.event.issue.labels.*.name, '*english-please')
run: npm install --production --prefix ./actions
- name: Run English Please
if: contains(github.event.issue.labels.*.name, '*english-please')
uses: ./actions/english-please
with:
appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}}
token: ${{secrets.VSCODE_ISSUE_TRIAGE_BOT_PAT}}
cognitiveServicesAPIKey: ${{secrets.AZURE_TEXT_TRANSLATOR_KEY}}
nonEnglishLabel: "*english-please"
needsMoreInfoLabel: "needs more info"
translatorRequestedLabelPrefix: "translation-required-"
translatorRequestedLabelColor: "c29cff"
| .github/workflows/english-please.yml | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.00017491535982117057,
0.0001718563580652699,
0.00016877581947483122,
0.0001718671410344541,
0.000002172640961362049
] |
{
"id": 0,
"code_window": [
"\t\"reportIssueUrl\": \"https://github.com/microsoft/vscode/issues/new\",\n",
"\t\"urlProtocol\": \"code-oss\",\n",
"\t\"extensionAllowedProposedApi\": [\n",
"\t\t\"ms-vscode.vscode-js-profile-flame\",\n",
"\t\t\"ms-vscode.vscode-js-profile-table\",\n",
"\t\t\"ms-vscode.references-view\",\n",
"\t\t\"ms-vscode.github-browser\",\n",
"\t\t\"ms-vscode.github-richnav\"\n",
"\t],\n",
"\t\"builtInExtensions\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Keybinding, ResolvedKeybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
import { ScanCodeBinding } from 'vs/base/common/scanCode';
import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
export interface IKeyboardMapper {
dumpDebugInfo(): string;
resolveKeybinding(keybinding: Keybinding): ResolvedKeybinding[];
resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding;
resolveUserBinding(firstPart: (SimpleKeybinding | ScanCodeBinding)[]): ResolvedKeybinding[];
}
export class CachedKeyboardMapper implements IKeyboardMapper {
private _actual: IKeyboardMapper;
private _cache: Map<string, ResolvedKeybinding[]>;
constructor(actual: IKeyboardMapper) {
this._actual = actual;
this._cache = new Map<string, ResolvedKeybinding[]>();
}
public dumpDebugInfo(): string {
return this._actual.dumpDebugInfo();
}
public resolveKeybinding(keybinding: Keybinding): ResolvedKeybinding[] {
const hashCode = keybinding.getHashCode();
const resolved = this._cache.get(hashCode);
if (!resolved) {
const r = this._actual.resolveKeybinding(keybinding);
this._cache.set(hashCode, r);
return r;
}
return resolved;
}
public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding {
return this._actual.resolveKeyboardEvent(keyboardEvent);
}
public resolveUserBinding(parts: (SimpleKeybinding | ScanCodeBinding)[]): ResolvedKeybinding[] {
return this._actual.resolveUserBinding(parts);
}
}
| src/vs/platform/keyboardLayout/common/keyboardMapper.ts | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.0001728132920106873,
0.00016914888692554086,
0.00016001594485715032,
0.00017077421944122761,
0.000004692399670602754
] |
{
"id": 0,
"code_window": [
"\t\"reportIssueUrl\": \"https://github.com/microsoft/vscode/issues/new\",\n",
"\t\"urlProtocol\": \"code-oss\",\n",
"\t\"extensionAllowedProposedApi\": [\n",
"\t\t\"ms-vscode.vscode-js-profile-flame\",\n",
"\t\t\"ms-vscode.vscode-js-profile-table\",\n",
"\t\t\"ms-vscode.references-view\",\n",
"\t\t\"ms-vscode.github-browser\",\n",
"\t\t\"ms-vscode.github-richnav\"\n",
"\t],\n",
"\t\"builtInExtensions\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 27
} | {
"displayName": "Ruby Language Basics",
"description": "Provides syntax highlighting and bracket matching in Ruby files."
} | extensions/ruby/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.0001712255470920354,
0.0001712255470920354,
0.0001712255470920354,
0.0001712255470920354,
0
] |
{
"id": 1,
"code_window": [
"\t\t},\n",
"\t\t{\n",
"\t\t\t\"name\": \"ms-vscode.references-view\",\n",
"\t\t\t\"version\": \"0.0.73\",\n",
"\t\t\t\"repo\": \"https://github.com/microsoft/vscode-reference-view\",\n",
"\t\t\t\"metadata\": {\n",
"\t\t\t\t\"id\": \"dc489f46-520d-4556-ae85-1f9eab3c412d\",\n",
"\t\t\t\t\"publisherId\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\"version\": \"0.0.74\",\n"
],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 64
} | {
"nameShort": "Code - OSS",
"nameLong": "Code - OSS",
"applicationName": "code-oss",
"dataFolderName": ".vscode-oss",
"win32MutexName": "vscodeoss",
"licenseName": "MIT",
"licenseUrl": "https://github.com/microsoft/vscode/blob/master/LICENSE.txt",
"win32DirName": "Microsoft Code OSS",
"win32NameVersion": "Microsoft Code OSS",
"win32RegValueName": "CodeOSS",
"win32AppId": "{{E34003BB-9E10-4501-8C11-BE3FAA83F23F}",
"win32x64AppId": "{{D77B7E06-80BA-4137-BCF4-654B95CCEBC5}",
"win32arm64AppId": "{{D1ACE434-89C5-48D1-88D3-E2991DF85475}",
"win32UserAppId": "{{C6065F05-9603-4FC4-8101-B9781A25D88E}",
"win32x64UserAppId": "{{CC6B787D-37A0-49E8-AE24-8559A032BE0C}",
"win32arm64UserAppId": "{{3AEBF0C8-F733-4AD4-BADE-FDB816D53D7B}",
"win32AppUserModelId": "Microsoft.CodeOSS",
"win32ShellNameShort": "C&ode - OSS",
"darwinBundleIdentifier": "com.visualstudio.code.oss",
"linuxIconName": "com.visualstudio.code.oss",
"licenseFileName": "LICENSE.txt",
"reportIssueUrl": "https://github.com/microsoft/vscode/issues/new",
"urlProtocol": "code-oss",
"extensionAllowedProposedApi": [
"ms-vscode.vscode-js-profile-flame",
"ms-vscode.vscode-js-profile-table",
"ms-vscode.references-view",
"ms-vscode.github-browser",
"ms-vscode.github-richnav"
],
"builtInExtensions": [
{
"name": "ms-vscode.node-debug",
"version": "1.44.14",
"repo": "https://github.com/microsoft/vscode-node-debug",
"metadata": {
"id": "b6ded8fb-a0a0-4c1c-acbd-ab2a3bc995a6",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
},
{
"name": "ms-vscode.node-debug2",
"version": "1.42.5",
"repo": "https://github.com/microsoft/vscode-node-debug2",
"metadata": {
"id": "36d19e17-7569-4841-a001-947eb18602b2",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
},
{
"name": "ms-vscode.references-view",
"version": "0.0.73",
"repo": "https://github.com/microsoft/vscode-reference-view",
"metadata": {
"id": "dc489f46-520d-4556-ae85-1f9eab3c412d",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
},
{
"name": "ms-vscode.js-debug-companion",
"version": "1.0.8",
"repo": "https://github.com/microsoft/vscode-js-debug-companion",
"metadata": {
"id": "99cb0b7f-7354-4278-b8da-6cc79972169d",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
},
{
"name": "ms-vscode.js-debug",
"version": "1.51.0",
"repo": "https://github.com/microsoft/vscode-js-debug",
"metadata": {
"id": "25629058-ddac-4e17-abba-74678e126c5d",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
},
{
"name": "ms-vscode.vscode-js-profile-table",
"version": "0.0.11",
"repo": "https://github.com/microsoft/vscode-js-debug",
"metadata": {
"id": "7e52b41b-71ad-457b-ab7e-0620f1fc4feb",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
}
],
"webBuiltInExtensions": [
{
"name": "ms-vscode.github-browser",
"version": "0.0.13",
"repo": "https://github.com/microsoft/vscode-github-browser",
"metadata": {
"id": "c1bcff4b-4ecb-466e-b8f6-b02788b5fb5a",
"publisherId": {
"publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee",
"publisherName": "ms-vscode",
"displayName": "Microsoft",
"flags": "verified"
},
"publisherDisplayName": "Microsoft"
}
}
]
}
| product.json | 1 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.9747844338417053,
0.06691154837608337,
0.000170477811479941,
0.0008125896565616131,
0.2426493912935257
] |
{
"id": 1,
"code_window": [
"\t\t},\n",
"\t\t{\n",
"\t\t\t\"name\": \"ms-vscode.references-view\",\n",
"\t\t\t\"version\": \"0.0.73\",\n",
"\t\t\t\"repo\": \"https://github.com/microsoft/vscode-reference-view\",\n",
"\t\t\t\"metadata\": {\n",
"\t\t\t\t\"id\": \"dc489f46-520d-4556-ae85-1f9eab3c412d\",\n",
"\t\t\t\t\"publisherId\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\"version\": \"0.0.74\",\n"
],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 64
} | {
"displayName": "TypeScript Language Basics",
"description": "Provides snippets, syntax highlighting, bracket matching and folding in TypeScript files."
} | extensions/typescript-basics/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.00016643204435240477,
0.00016643204435240477,
0.00016643204435240477,
0.00016643204435240477,
0
] |
{
"id": 1,
"code_window": [
"\t\t},\n",
"\t\t{\n",
"\t\t\t\"name\": \"ms-vscode.references-view\",\n",
"\t\t\t\"version\": \"0.0.73\",\n",
"\t\t\t\"repo\": \"https://github.com/microsoft/vscode-reference-view\",\n",
"\t\t\t\"metadata\": {\n",
"\t\t\t\t\"id\": \"dc489f46-520d-4556-ae85-1f9eab3c412d\",\n",
"\t\t\t\t\"publisherId\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\"version\": \"0.0.74\",\n"
],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 64
} | /*---------------------------------------------------------------------------------------------
* 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';
import * as streams from 'vs/base/common/stream';
declare const Buffer: any;
const hasBuffer = (typeof Buffer !== 'undefined');
const hasTextEncoder = (typeof TextEncoder !== 'undefined');
const hasTextDecoder = (typeof TextDecoder !== 'undefined');
let textEncoder: TextEncoder | null;
let textDecoder: TextDecoder | null;
export class VSBuffer {
static alloc(byteLength: number): VSBuffer {
if (hasBuffer) {
return new VSBuffer(Buffer.allocUnsafe(byteLength));
} else {
return new VSBuffer(new Uint8Array(byteLength));
}
}
static wrap(actual: Uint8Array): VSBuffer {
if (hasBuffer && !(Buffer.isBuffer(actual))) {
// https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
// Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
}
return new VSBuffer(actual);
}
static fromString(source: string): VSBuffer {
if (hasBuffer) {
return new VSBuffer(Buffer.from(source));
} else if (hasTextEncoder) {
if (!textEncoder) {
textEncoder = new TextEncoder();
}
return new VSBuffer(textEncoder.encode(source));
} else {
return new VSBuffer(strings.encodeUTF8(source));
}
}
static concat(buffers: VSBuffer[], totalLength?: number): VSBuffer {
if (typeof totalLength === 'undefined') {
totalLength = 0;
for (let i = 0, len = buffers.length; i < len; i++) {
totalLength += buffers[i].byteLength;
}
}
const ret = VSBuffer.alloc(totalLength);
let offset = 0;
for (let i = 0, len = buffers.length; i < len; i++) {
const element = buffers[i];
ret.set(element, offset);
offset += element.byteLength;
}
return ret;
}
readonly buffer: Uint8Array;
readonly byteLength: number;
private constructor(buffer: Uint8Array) {
this.buffer = buffer;
this.byteLength = this.buffer.byteLength;
}
toString(): string {
if (hasBuffer) {
return this.buffer.toString();
} else if (hasTextDecoder) {
if (!textDecoder) {
textDecoder = new TextDecoder();
}
return textDecoder.decode(this.buffer);
} else {
return strings.decodeUTF8(this.buffer);
}
}
slice(start?: number, end?: number): VSBuffer {
// IMPORTANT: use subarray instead of slice because TypedArray#slice
// creates shallow copy and NodeBuffer#slice doesn't. The use of subarray
// ensures the same, performant, behaviour.
return new VSBuffer(this.buffer.subarray(start!/*bad lib.d.ts*/, end));
}
set(array: VSBuffer, offset?: number): void;
set(array: Uint8Array, offset?: number): void;
set(array: VSBuffer | Uint8Array, offset?: number): void {
if (array instanceof VSBuffer) {
this.buffer.set(array.buffer, offset);
} else {
this.buffer.set(array, offset);
}
}
readUInt32BE(offset: number): number {
return readUInt32BE(this.buffer, offset);
}
writeUInt32BE(value: number, offset: number): void {
writeUInt32BE(this.buffer, value, offset);
}
readUInt32LE(offset: number): number {
return readUInt32LE(this.buffer, offset);
}
writeUInt32LE(value: number, offset: number): void {
writeUInt32LE(this.buffer, value, offset);
}
readUInt8(offset: number): number {
return readUInt8(this.buffer, offset);
}
writeUInt8(value: number, offset: number): void {
writeUInt8(this.buffer, value, offset);
}
}
export function readUInt16LE(source: Uint8Array, offset: number): number {
return (
((source[offset + 0] << 0) >>> 0) |
((source[offset + 1] << 8) >>> 0)
);
}
export function writeUInt16LE(destination: Uint8Array, value: number, offset: number): void {
destination[offset + 0] = (value & 0b11111111);
value = value >>> 8;
destination[offset + 1] = (value & 0b11111111);
}
export function readUInt32BE(source: Uint8Array, offset: number): number {
return (
source[offset] * 2 ** 24
+ source[offset + 1] * 2 ** 16
+ source[offset + 2] * 2 ** 8
+ source[offset + 3]
);
}
export function writeUInt32BE(destination: Uint8Array, value: number, offset: number): void {
destination[offset + 3] = value;
value = value >>> 8;
destination[offset + 2] = value;
value = value >>> 8;
destination[offset + 1] = value;
value = value >>> 8;
destination[offset] = value;
}
export function readUInt32LE(source: Uint8Array, offset: number): number {
return (
((source[offset + 0] << 0) >>> 0) |
((source[offset + 1] << 8) >>> 0) |
((source[offset + 2] << 16) >>> 0) |
((source[offset + 3] << 24) >>> 0)
);
}
export function writeUInt32LE(destination: Uint8Array, value: number, offset: number): void {
destination[offset + 0] = (value & 0b11111111);
value = value >>> 8;
destination[offset + 1] = (value & 0b11111111);
value = value >>> 8;
destination[offset + 2] = (value & 0b11111111);
value = value >>> 8;
destination[offset + 3] = (value & 0b11111111);
}
export function readUInt8(source: Uint8Array, offset: number): number {
return source[offset];
}
export function writeUInt8(destination: Uint8Array, value: number, offset: number): void {
destination[offset] = value;
}
export interface VSBufferReadable extends streams.Readable<VSBuffer> { }
export interface VSBufferReadableStream extends streams.ReadableStream<VSBuffer> { }
export interface VSBufferWriteableStream extends streams.WriteableStream<VSBuffer> { }
export interface VSBufferReadableBufferedStream extends streams.ReadableBufferedStream<VSBuffer> { }
export function readableToBuffer(readable: VSBufferReadable): VSBuffer {
return streams.consumeReadable<VSBuffer>(readable, chunks => VSBuffer.concat(chunks));
}
export function bufferToReadable(buffer: VSBuffer): VSBufferReadable {
return streams.toReadable<VSBuffer>(buffer);
}
export function streamToBuffer(stream: streams.ReadableStream<VSBuffer>): Promise<VSBuffer> {
return streams.consumeStream<VSBuffer>(stream, chunks => VSBuffer.concat(chunks));
}
export async function bufferedStreamToBuffer(bufferedStream: streams.ReadableBufferedStream<VSBuffer>): Promise<VSBuffer> {
if (bufferedStream.ended) {
return VSBuffer.concat(bufferedStream.buffer);
}
return VSBuffer.concat([
// Include already read chunks...
...bufferedStream.buffer,
// ...and all additional chunks
await streamToBuffer(bufferedStream.stream)
]);
}
export function bufferToStream(buffer: VSBuffer): streams.ReadableStream<VSBuffer> {
return streams.toStream<VSBuffer>(buffer, chunks => VSBuffer.concat(chunks));
}
export function streamToBufferReadableStream(stream: streams.ReadableStreamEvents<Uint8Array | string>): streams.ReadableStream<VSBuffer> {
return streams.transform<Uint8Array | string, VSBuffer>(stream, { data: data => typeof data === 'string' ? VSBuffer.fromString(data) : VSBuffer.wrap(data) }, chunks => VSBuffer.concat(chunks));
}
export function newWriteableBufferStream(options?: streams.WriteableStreamOptions): streams.WriteableStream<VSBuffer> {
return streams.newWriteableStream<VSBuffer>(chunks => VSBuffer.concat(chunks), options);
}
| src/vs/base/common/buffer.ts | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.00025527935940772295,
0.00017286576621700078,
0.00016143293760251254,
0.00016858027083799243,
0.000018159069441026077
] |
{
"id": 1,
"code_window": [
"\t\t},\n",
"\t\t{\n",
"\t\t\t\"name\": \"ms-vscode.references-view\",\n",
"\t\t\t\"version\": \"0.0.73\",\n",
"\t\t\t\"repo\": \"https://github.com/microsoft/vscode-reference-view\",\n",
"\t\t\t\"metadata\": {\n",
"\t\t\t\t\"id\": \"dc489f46-520d-4556-ae85-1f9eab3c412d\",\n",
"\t\t\t\t\"publisherId\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\"version\": \"0.0.74\",\n"
],
"file_path": "product.json",
"type": "replace",
"edit_start_line_idx": 64
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
export default {
MARKERS_CONTAINER_ID: 'workbench.panel.markers',
MARKERS_VIEW_ID: 'workbench.panel.markers.view',
MARKERS_VIEW_STORAGE_ID: 'workbench.panel.markers',
MARKER_COPY_ACTION_ID: 'problems.action.copy',
MARKER_COPY_MESSAGE_ACTION_ID: 'problems.action.copyMessage',
RELATED_INFORMATION_COPY_MESSAGE_ACTION_ID: 'problems.action.copyRelatedInformationMessage',
FOCUS_PROBLEMS_FROM_FILTER: 'problems.action.focusProblemsFromFilter',
MARKERS_VIEW_FOCUS_FILTER: 'problems.action.focusFilter',
MARKERS_VIEW_CLEAR_FILTER_TEXT: 'problems.action.clearFilterText',
MARKERS_VIEW_SHOW_MULTILINE_MESSAGE: 'problems.action.showMultilineMessage',
MARKERS_VIEW_SHOW_SINGLELINE_MESSAGE: 'problems.action.showSinglelineMessage',
MARKER_OPEN_ACTION_ID: 'problems.action.open',
MARKER_OPEN_SIDE_ACTION_ID: 'problems.action.openToSide',
MARKER_SHOW_PANEL_ID: 'workbench.action.showErrorsWarnings',
MARKER_SHOW_QUICK_FIX: 'problems.action.showQuickFixes',
TOGGLE_MARKERS_VIEW_ACTION_ID: 'workbench.actions.view.toggleProblems',
MarkersViewSmallLayoutContextKey: new RawContextKey<boolean>(`problemsView.smallLayout`, false),
MarkerFocusContextKey: new RawContextKey<boolean>('problemFocus', false),
MarkerViewFilterFocusContextKey: new RawContextKey<boolean>('problemsFilterFocus', false),
RelatedInformationFocusContextKey: new RawContextKey<boolean>('relatedInformationFocus', false)
};
| src/vs/workbench/contrib/markers/browser/constants.ts | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.00017038403893820941,
0.00016784117906354368,
0.00016586866695433855,
0.00016755599062889814,
0.0000018538108861321234
] |
{
"id": 2,
"code_window": [
"\t\t\textensionAllowedProposedApi: [\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-flame',\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-table',\n",
"\t\t\t\t'ms-vscode.references-view',\n",
"\t\t\t\t'ms-vscode.github-browser'\n",
"\t\t\t],\n",
"\t\t});\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/product/common/product.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IProductConfiguration } from 'vs/platform/product/common/productService';
import { isWeb } from 'vs/base/common/platform';
import { env } from 'vs/base/common/process';
import { FileAccess } from 'vs/base/common/network';
import { dirname, joinPath } from 'vs/base/common/resources';
let product: IProductConfiguration;
// Web or Native (sandbox TODO@sandbox need to add all properties of product.json)
if (isWeb || typeof require === 'undefined' || typeof require.__$__nodeRequire !== 'function') {
// Built time configuration (do NOT modify)
product = { /*BUILD->INSERT_PRODUCT_CONFIGURATION*/ } as IProductConfiguration;
// Running out of sources
if (Object.keys(product).length === 0) {
Object.assign(product, {
version: '1.52.0-dev',
nameShort: isWeb ? 'Code Web - OSS Dev' : 'Code - OSS Dev',
nameLong: isWeb ? 'Code Web - OSS Dev' : 'Code - OSS Dev',
applicationName: 'code-oss',
dataFolderName: '.vscode-oss',
urlProtocol: 'code-oss',
reportIssueUrl: 'https://github.com/microsoft/vscode/issues/new',
licenseName: 'MIT',
licenseUrl: 'https://github.com/microsoft/vscode/blob/master/LICENSE.txt',
extensionAllowedProposedApi: [
'ms-vscode.vscode-js-profile-flame',
'ms-vscode.vscode-js-profile-table',
'ms-vscode.references-view',
'ms-vscode.github-browser'
],
});
}
}
// Native (non-sandboxed)
else {
// Obtain values from product.json and package.json
const rootPath = dirname(FileAccess.asFileUri('', require));
product = require.__$__nodeRequire(joinPath(rootPath, 'product.json').fsPath);
const pkg = require.__$__nodeRequire(joinPath(rootPath, 'package.json').fsPath) as { version: string; };
// Running out of sources
if (env['VSCODE_DEV']) {
Object.assign(product, {
nameShort: `${product.nameShort} Dev`,
nameLong: `${product.nameLong} Dev`,
dataFolderName: `${product.dataFolderName}-dev`
});
}
Object.assign(product, {
version: pkg.version
});
}
export default product;
| src/vs/platform/product/common/product.ts | 1 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.5489996671676636,
0.07857446372509003,
0.0001628596510272473,
0.00017080320685636252,
0.1920502632856369
] |
{
"id": 2,
"code_window": [
"\t\t\textensionAllowedProposedApi: [\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-flame',\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-table',\n",
"\t\t\t\t'ms-vscode.references-view',\n",
"\t\t\t\t'ms-vscode.github-browser'\n",
"\t\t\t],\n",
"\t\t});\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/product/common/product.ts",
"type": "replace",
"edit_start_line_idx": 34
} | The file `TypeScript.tmLanguage.json` and `TypeScriptReact.tmLanguage.json` are derived from [TypeScript.tmLanguage](https://github.com/microsoft/TypeScript-TmLanguage/blob/master/TypeScript.tmLanguage) and [TypeScriptReact.tmLanguage](https://github.com/microsoft/TypeScript-TmLanguage/blob/master/TypeScriptReact.tmLanguage).
To update to the latest version:
- `cd extensions/typescript` and run `npm run update-grammars`
- don't forget to run the integration tests at `./scripts/test-integration.sh`
Migration notes and todos:
- differentiate variable and function declarations from references
- I suggest we use a new scope segment 'function-call' to signal a function reference, and 'definition' to the declaration. An alternative is to use 'support.function' everywhere.
- I suggest we use a new scope segment 'definition' to the variable declarations. Haven't yet found a scope for references that other grammars use.
- rename scope to return.type to return-type, which is already used in other grammars
- rename entity.name.class to entity.name.type.class which is used in all other grammars I've seen
- do we really want to have the list of all the 'library' types (Math, Dom...). It adds a lot of size to the grammar, lots of special rules and is not really correct as it depends on the JavaScript runtime which types are present.
| extensions/typescript-basics/syntaxes/Readme.md | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.00016798045544419438,
0.0001647501194383949,
0.0001615197688806802,
0.0001647501194383949,
0.0000032303432817570865
] |
{
"id": 2,
"code_window": [
"\t\t\textensionAllowedProposedApi: [\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-flame',\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-table',\n",
"\t\t\t\t'ms-vscode.references-view',\n",
"\t\t\t\t'ms-vscode.github-browser'\n",
"\t\t\t],\n",
"\t\t});\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/product/common/product.ts",
"type": "replace",
"edit_start_line_idx": 34
} | {
"comments": {
"blockComment": [ "<!--", "-->" ]
},
"brackets": [
["<!--", "-->"],
["<", ">"],
["{", "}"],
["(", ")"]
],
"autoClosingPairs": [
{ "open": "{", "close": "}"},
{ "open": "[", "close": "]"},
{ "open": "(", "close": ")" },
{ "open": "\"", "close": "\"", "notIn": ["string"] },
{ "open": "'", "close": "'", "notIn": ["string"] },
{ "open": "<!--", "close": "-->", "notIn": [ "comment", "string" ]},
{ "open": "<![CDATA[", "close": "]]>", "notIn": [ "comment", "string" ]}
],
"surroundingPairs": [
{ "open": "'", "close": "'" },
{ "open": "\"", "close": "\"" },
{ "open": "{", "close": "}"},
{ "open": "[", "close": "]"},
{ "open": "(", "close": ")" },
{ "open": "<", "close": ">" }
],
"folding": {
"markers": {
"start": "^\\s*<!--\\s*#region\\b.*-->",
"end": "^\\s*<!--\\s*#endregion\\b.*-->"
}
}
}
| extensions/xml/xml.language-configuration.json | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.00017094204667955637,
0.00016877494635991752,
0.0001669360208325088,
0.000168610829859972,
0.0000015251105196512071
] |
{
"id": 2,
"code_window": [
"\t\t\textensionAllowedProposedApi: [\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-flame',\n",
"\t\t\t\t'ms-vscode.vscode-js-profile-table',\n",
"\t\t\t\t'ms-vscode.references-view',\n",
"\t\t\t\t'ms-vscode.github-browser'\n",
"\t\t\t],\n",
"\t\t});\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/product/common/product.ts",
"type": "replace",
"edit_start_line_idx": 34
} | name: Commands
on:
issue_comment:
types: [created]
# also make changes in ./on-label.yml
jobs:
main:
runs-on: ubuntu-latest
steps:
- name: Checkout Actions
uses: actions/checkout@v2
with:
repository: "microsoft/vscode-github-triage-actions"
path: ./actions
ref: v40
- name: Install Actions
run: npm install --production --prefix ./actions
- name: Run Commands
uses: ./actions/commands
with:
appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}}
token: ${{secrets.VSCODE_ISSUE_TRIAGE_BOT_PAT}}
config-path: commands
| .github/workflows/commands.yml | 0 | https://github.com/microsoft/vscode/commit/a4054cda6db164b2bf6acc0473635484697884d7 | [
0.0001735297410050407,
0.00017108717293012887,
0.0001689632481429726,
0.00017076852964237332,
0.0000018778292769638938
] |
{
"id": 0,
"code_window": [
"\tlet log_broadcast = BroadcastLogSink::new();\n",
"\tlog = log.tee(log_broadcast.clone());\n",
"\tlog::install_global_logger(log.clone()); // re-install so that library logs are captured\n",
"\n",
"\tlet shutdown = match gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tSome(pid) => ShutdownRequest::create_rx([\n",
"\t\t\tShutdownRequest::CtrlC,\n",
"\t\t\tShutdownRequest::ParentProcessKilled(pid),\n",
"\t\t]),\n",
"\t\tNone => ShutdownRequest::create_rx([ShutdownRequest::CtrlC]),\n",
"\t};\n",
"\n",
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "cli/src/commands/tunnels.rs",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.013721461407840252,
0.0021376435179263353,
0.0001707784686004743,
0.0006363791762851179,
0.004138510674238205
] |
{
"id": 0,
"code_window": [
"\tlet log_broadcast = BroadcastLogSink::new();\n",
"\tlog = log.tee(log_broadcast.clone());\n",
"\tlog::install_global_logger(log.clone()); // re-install so that library logs are captured\n",
"\n",
"\tlet shutdown = match gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tSome(pid) => ShutdownRequest::create_rx([\n",
"\t\t\tShutdownRequest::CtrlC,\n",
"\t\t\tShutdownRequest::ParentProcessKilled(pid),\n",
"\t\t]),\n",
"\t\tNone => ShutdownRequest::create_rx([ShutdownRequest::CtrlC]),\n",
"\t};\n",
"\n",
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "cli/src/commands/tunnels.rs",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { NewWorkerMessage, TerminateWorkerMessage } from 'vs/workbench/services/extensions/common/polyfillNestedWorker.protocol';
declare function postMessage(data: any, transferables?: Transferable[]): void;
declare type MessageEventHandler = ((ev: MessageEvent<any>) => any) | null;
const _bootstrapFnSource = (function _bootstrapFn(workerUrl: string) {
const listener: EventListener = (event: Event): void => {
// uninstall handler
globalThis.removeEventListener('message', listener);
// get data
const port = <MessagePort>(<MessageEvent>event).data;
// postMessage
// onmessage
Object.defineProperties(globalThis, {
'postMessage': {
value(data: any, transferOrOptions?: any) {
port.postMessage(data, transferOrOptions);
}
},
'onmessage': {
get() {
return port.onmessage;
},
set(value: MessageEventHandler) {
port.onmessage = value;
}
}
// todo onerror
});
port.addEventListener('message', msg => {
globalThis.dispatchEvent(new MessageEvent('message', { data: msg.data, ports: msg.ports ? [...msg.ports] : undefined }));
});
port.start();
// fake recursively nested worker
globalThis.Worker = <any>class { constructor() { throw new TypeError('Nested workers from within nested worker are NOT supported.'); } };
// load module
importScripts(workerUrl);
};
globalThis.addEventListener('message', listener);
}).toString();
export class NestedWorker extends EventTarget implements Worker {
onmessage: ((this: Worker, ev: MessageEvent<any>) => any) | null = null;
onmessageerror: ((this: Worker, ev: MessageEvent<any>) => any) | null = null;
onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null = null;
readonly terminate: () => void;
readonly postMessage: (message: any, options?: any) => void;
constructor(nativePostMessage: typeof postMessage, stringOrUrl: string | URL, options?: WorkerOptions) {
super();
// create bootstrap script
const bootstrap = `((${_bootstrapFnSource})('${stringOrUrl}'))`;
const blob = new Blob([bootstrap], { type: 'application/javascript' });
const blobUrl = URL.createObjectURL(blob);
const channel = new MessageChannel();
const id = blobUrl; // works because blob url is unique, needs ID pool otherwise
const msg: NewWorkerMessage = {
type: '_newWorker',
id,
port: channel.port2,
url: blobUrl,
options,
};
nativePostMessage(msg, [channel.port2]);
// worker-impl: functions
this.postMessage = channel.port1.postMessage.bind(channel.port1);
this.terminate = () => {
const msg: TerminateWorkerMessage = {
type: '_terminateWorker',
id
};
nativePostMessage(msg);
URL.revokeObjectURL(blobUrl);
channel.port1.close();
channel.port2.close();
};
// worker-impl: events
Object.defineProperties(this, {
'onmessage': {
get() {
return channel.port1.onmessage;
},
set(value: MessageEventHandler) {
channel.port1.onmessage = value;
}
},
'onmessageerror': {
get() {
return channel.port1.onmessageerror;
},
set(value: MessageEventHandler) {
channel.port1.onmessageerror = value;
}
},
// todo onerror
});
channel.port1.addEventListener('messageerror', evt => {
const msgEvent = new MessageEvent('messageerror', { data: evt.data });
this.dispatchEvent(msgEvent);
});
channel.port1.addEventListener('message', evt => {
const msgEvent = new MessageEvent('message', { data: evt.data });
this.dispatchEvent(msgEvent);
});
channel.port1.start();
}
}
| src/vs/workbench/services/extensions/worker/polyfillNestedWorker.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017602766456548125,
0.00017286770162172616,
0.00016845250502228737,
0.00017363889492116868,
0.0000020179822968202643
] |
{
"id": 0,
"code_window": [
"\tlet log_broadcast = BroadcastLogSink::new();\n",
"\tlog = log.tee(log_broadcast.clone());\n",
"\tlog::install_global_logger(log.clone()); // re-install so that library logs are captured\n",
"\n",
"\tlet shutdown = match gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tSome(pid) => ShutdownRequest::create_rx([\n",
"\t\t\tShutdownRequest::CtrlC,\n",
"\t\t\tShutdownRequest::ParentProcessKilled(pid),\n",
"\t\t]),\n",
"\t\tNone => ShutdownRequest::create_rx([ShutdownRequest::CtrlC]),\n",
"\t};\n",
"\n",
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "cli/src/commands/tunnels.rs",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* 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';
import { Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { IndentAction } from 'vs/editor/common/languages/languageConfiguration';
import { createScopedLineTokens } from 'vs/editor/common/languages/supports';
import { IndentConsts, IndentRulesSupport } from 'vs/editor/common/languages/supports/indentRules';
import { EditorAutoIndentStrategy } from 'vs/editor/common/config/editorOptions';
import { getScopedLineTokens, ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { LineTokens } from 'vs/editor/common/tokens/lineTokens';
export interface IVirtualModel {
tokenization: {
getLineTokens(lineNumber: number): LineTokens;
getLanguageId(): string;
getLanguageIdAtPosition(lineNumber: number, column: number): string;
};
getLineContent(lineNumber: number): string;
}
export interface IIndentConverter {
shiftIndent(indentation: string): string;
unshiftIndent(indentation: string): string;
normalizeIndentation?(indentation: string): string;
}
/**
* Get nearest preceding line which doesn't match unIndentPattern or contains all whitespace.
* Result:
* -1: run into the boundary of embedded languages
* 0: every line above are invalid
* else: nearest preceding line of the same language
*/
function getPrecedingValidLine(model: IVirtualModel, lineNumber: number, indentRulesSupport: IndentRulesSupport) {
const languageId = model.tokenization.getLanguageIdAtPosition(lineNumber, 0);
if (lineNumber > 1) {
let lastLineNumber: number;
let resultLineNumber = -1;
for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
if (model.tokenization.getLanguageIdAtPosition(lastLineNumber, 0) !== languageId) {
return resultLineNumber;
}
const text = model.getLineContent(lastLineNumber);
if (indentRulesSupport.shouldIgnore(text) || /^\s+$/.test(text) || text === '') {
resultLineNumber = lastLineNumber;
continue;
}
return lastLineNumber;
}
}
return -1;
}
/**
* Get inherited indentation from above lines.
* 1. Find the nearest preceding line which doesn't match unIndentedLinePattern.
* 2. If this line matches indentNextLinePattern or increaseIndentPattern, it means that the indent level of `lineNumber` should be 1 greater than this line.
* 3. If this line doesn't match any indent rules
* a. check whether the line above it matches indentNextLinePattern
* b. If not, the indent level of this line is the result
* c. If so, it means the indent of this line is *temporary*, go upward utill we find a line whose indent is not temporary (the same workflow a -> b -> c).
* 4. Otherwise, we fail to get an inherited indent from aboves. Return null and we should not touch the indent of `lineNumber`
*
* This function only return the inherited indent based on above lines, it doesn't check whether current line should decrease or not.
*/
export function getInheritIndentForLine(
autoIndent: EditorAutoIndentStrategy,
model: IVirtualModel,
lineNumber: number,
honorIntentialIndent: boolean = true,
languageConfigurationService: ILanguageConfigurationService
): { indentation: string; action: IndentAction | null; line?: number } | null {
if (autoIndent < EditorAutoIndentStrategy.Full) {
return null;
}
const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.tokenization.getLanguageId()).indentRulesSupport;
if (!indentRulesSupport) {
return null;
}
if (lineNumber <= 1) {
return {
indentation: '',
action: null
};
}
// Use no indent if this is the first non-blank line
for (let priorLineNumber = lineNumber - 1; priorLineNumber > 0; priorLineNumber--) {
if (model.getLineContent(priorLineNumber) !== '') {
break;
}
if (priorLineNumber === 1) {
return {
indentation: '',
action: null
};
}
}
const precedingUnIgnoredLine = getPrecedingValidLine(model, lineNumber, indentRulesSupport);
if (precedingUnIgnoredLine < 0) {
return null;
} else if (precedingUnIgnoredLine < 1) {
return {
indentation: '',
action: null
};
}
const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
if (indentRulesSupport.shouldIncrease(precedingUnIgnoredLineContent) || indentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLineContent)) {
return {
indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
action: IndentAction.Indent,
line: precedingUnIgnoredLine
};
} else if (indentRulesSupport.shouldDecrease(precedingUnIgnoredLineContent)) {
return {
indentation: strings.getLeadingWhitespace(precedingUnIgnoredLineContent),
action: null,
line: precedingUnIgnoredLine
};
} else {
// precedingUnIgnoredLine can not be ignored.
// it doesn't increase indent of following lines
// it doesn't increase just next line
// so current line is not affect by precedingUnIgnoredLine
// and then we should get a correct inheritted indentation from above lines
if (precedingUnIgnoredLine === 1) {
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
action: null,
line: precedingUnIgnoredLine
};
}
const previousLine = precedingUnIgnoredLine - 1;
const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
if (!(previousLineIndentMetadata & (IndentConsts.INCREASE_MASK | IndentConsts.DECREASE_MASK)) &&
(previousLineIndentMetadata & IndentConsts.INDENT_NEXTLINE_MASK)) {
let stopLine = 0;
for (let i = previousLine - 1; i > 0; i--) {
if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
continue;
}
stopLine = i;
break;
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
action: null,
line: stopLine + 1
};
}
if (honorIntentialIndent) {
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
action: null,
line: precedingUnIgnoredLine
};
} else {
// search from precedingUnIgnoredLine until we find one whose indent is not temporary
for (let i = precedingUnIgnoredLine; i > 0; i--) {
const lineContent = model.getLineContent(i);
if (indentRulesSupport.shouldIncrease(lineContent)) {
return {
indentation: strings.getLeadingWhitespace(lineContent),
action: IndentAction.Indent,
line: i
};
} else if (indentRulesSupport.shouldIndentNextLine(lineContent)) {
let stopLine = 0;
for (let j = i - 1; j > 0; j--) {
if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
continue;
}
stopLine = j;
break;
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(stopLine + 1)),
action: null,
line: stopLine + 1
};
} else if (indentRulesSupport.shouldDecrease(lineContent)) {
return {
indentation: strings.getLeadingWhitespace(lineContent),
action: null,
line: i
};
}
}
return {
indentation: strings.getLeadingWhitespace(model.getLineContent(1)),
action: null,
line: 1
};
}
}
}
export function getGoodIndentForLine(
autoIndent: EditorAutoIndentStrategy,
virtualModel: IVirtualModel,
languageId: string,
lineNumber: number,
indentConverter: IIndentConverter,
languageConfigurationService: ILanguageConfigurationService
): string | null {
if (autoIndent < EditorAutoIndentStrategy.Full) {
return null;
}
const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
if (!richEditSupport) {
return null;
}
const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
if (!indentRulesSupport) {
return null;
}
const indent = getInheritIndentForLine(autoIndent, virtualModel, lineNumber, undefined, languageConfigurationService);
const lineContent = virtualModel.getLineContent(lineNumber);
if (indent) {
const inheritLine = indent.line;
if (inheritLine !== undefined) {
// Apply enter action as long as there are only whitespace lines between inherited line and this line.
let shouldApplyEnterRules = true;
for (let inBetweenLine = inheritLine; inBetweenLine < lineNumber - 1; inBetweenLine++) {
if (!/^\s*$/.test(virtualModel.getLineContent(inBetweenLine))) {
shouldApplyEnterRules = false;
break;
}
}
if (shouldApplyEnterRules) {
const enterResult = richEditSupport.onEnter(autoIndent, '', virtualModel.getLineContent(inheritLine), '');
if (enterResult) {
let indentation = strings.getLeadingWhitespace(virtualModel.getLineContent(inheritLine));
if (enterResult.removeText) {
indentation = indentation.substring(0, indentation.length - enterResult.removeText);
}
if (
(enterResult.indentAction === IndentAction.Indent) ||
(enterResult.indentAction === IndentAction.IndentOutdent)
) {
indentation = indentConverter.shiftIndent(indentation);
} else if (enterResult.indentAction === IndentAction.Outdent) {
indentation = indentConverter.unshiftIndent(indentation);
}
if (indentRulesSupport.shouldDecrease(lineContent)) {
indentation = indentConverter.unshiftIndent(indentation);
}
if (enterResult.appendText) {
indentation += enterResult.appendText;
}
return strings.getLeadingWhitespace(indentation);
}
}
}
if (indentRulesSupport.shouldDecrease(lineContent)) {
if (indent.action === IndentAction.Indent) {
return indent.indentation;
} else {
return indentConverter.unshiftIndent(indent.indentation);
}
} else {
if (indent.action === IndentAction.Indent) {
return indentConverter.shiftIndent(indent.indentation);
} else {
return indent.indentation;
}
}
}
return null;
}
export function getIndentForEnter(
autoIndent: EditorAutoIndentStrategy,
model: ITextModel,
range: Range,
indentConverter: IIndentConverter,
languageConfigurationService: ILanguageConfigurationService
): { beforeEnter: string; afterEnter: string } | null {
if (autoIndent < EditorAutoIndentStrategy.Full) {
return null;
}
model.tokenization.forceTokenization(range.startLineNumber);
const lineTokens = model.tokenization.getLineTokens(range.startLineNumber);
const scopedLineTokens = createScopedLineTokens(lineTokens, range.startColumn - 1);
const scopedLineText = scopedLineTokens.getLineContent();
let embeddedLanguage = false;
let beforeEnterText: string;
if (scopedLineTokens.firstCharOffset > 0 && lineTokens.getLanguageId(0) !== scopedLineTokens.languageId) {
// we are in the embeded language content
embeddedLanguage = true; // if embeddedLanguage is true, then we don't touch the indentation of current line
beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
} else {
beforeEnterText = lineTokens.getLineContent().substring(0, range.startColumn - 1);
}
let afterEnterText: string;
if (range.isEmpty()) {
afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
} else {
const endScopedLineTokens = getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).indentRulesSupport;
if (!indentRulesSupport) {
return null;
}
const beforeEnterResult = beforeEnterText;
const beforeEnterIndent = strings.getLeadingWhitespace(beforeEnterText);
const virtualModel: IVirtualModel = {
tokenization: {
getLineTokens: (lineNumber: number) => {
return model.tokenization.getLineTokens(lineNumber);
},
getLanguageId: () => {
return model.getLanguageId();
},
getLanguageIdAtPosition: (lineNumber: number, column: number) => {
return model.getLanguageIdAtPosition(lineNumber, column);
},
},
getLineContent: (lineNumber: number) => {
if (lineNumber === range.startLineNumber) {
return beforeEnterResult;
} else {
return model.getLineContent(lineNumber);
}
}
};
const currentLineIndent = strings.getLeadingWhitespace(lineTokens.getLineContent());
const afterEnterAction = getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1, undefined, languageConfigurationService);
if (!afterEnterAction) {
const beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent;
return {
beforeEnter: beforeEnter,
afterEnter: beforeEnter
};
}
let afterEnterIndent = embeddedLanguage ? currentLineIndent : afterEnterAction.indentation;
if (afterEnterAction.action === IndentAction.Indent) {
afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
}
if (indentRulesSupport.shouldDecrease(afterEnterText)) {
afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
}
return {
beforeEnter: embeddedLanguage ? currentLineIndent : beforeEnterIndent,
afterEnter: afterEnterIndent
};
}
/**
* We should always allow intentional indentation. It means, if users change the indentation of `lineNumber` and the content of
* this line doesn't match decreaseIndentPattern, we should not adjust the indentation.
*/
export function getIndentActionForType(
autoIndent: EditorAutoIndentStrategy,
model: ITextModel,
range: Range,
ch: string,
indentConverter: IIndentConverter,
languageConfigurationService: ILanguageConfigurationService
): string | null {
if (autoIndent < EditorAutoIndentStrategy.Full) {
return null;
}
const scopedLineTokens = getScopedLineTokens(model, range.startLineNumber, range.startColumn);
if (scopedLineTokens.firstCharOffset) {
// this line has mixed languages and indentation rules will not work
return null;
}
const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).indentRulesSupport;
if (!indentRulesSupport) {
return null;
}
const scopedLineText = scopedLineTokens.getLineContent();
const beforeTypeText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
// selection support
let afterTypeText: string;
if (range.isEmpty()) {
afterTypeText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
} else {
const endScopedLineTokens = getScopedLineTokens(model, range.endLineNumber, range.endColumn);
afterTypeText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
}
// If previous content already matches decreaseIndentPattern, it means indentation of this line should already be adjusted
// Users might change the indentation by purpose and we should honor that instead of readjusting.
if (!indentRulesSupport.shouldDecrease(beforeTypeText + afterTypeText) && indentRulesSupport.shouldDecrease(beforeTypeText + ch + afterTypeText)) {
// after typing `ch`, the content matches decreaseIndentPattern, we should adjust the indent to a good manner.
// 1. Get inherited indent action
const r = getInheritIndentForLine(autoIndent, model, range.startLineNumber, false, languageConfigurationService);
if (!r) {
return null;
}
let indentation = r.indentation;
if (r.action !== IndentAction.Indent) {
indentation = indentConverter.unshiftIndent(indentation);
}
return indentation;
}
return null;
}
export function getIndentMetadata(
model: ITextModel,
lineNumber: number,
languageConfigurationService: ILanguageConfigurationService
): number | null {
const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
if (!indentRulesSupport) {
return null;
}
if (lineNumber < 1 || lineNumber > model.getLineCount()) {
return null;
}
return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
}
| src/vs/editor/common/languages/autoIndent.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001773643889464438,
0.000173573091160506,
0.00016695291560608894,
0.00017383726662956178,
0.000001889611439764849
] |
{
"id": 0,
"code_window": [
"\tlet log_broadcast = BroadcastLogSink::new();\n",
"\tlog = log.tee(log_broadcast.clone());\n",
"\tlog::install_global_logger(log.clone()); // re-install so that library logs are captured\n",
"\n",
"\tlet shutdown = match gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tSome(pid) => ShutdownRequest::create_rx([\n",
"\t\t\tShutdownRequest::CtrlC,\n",
"\t\t\tShutdownRequest::ParentProcessKilled(pid),\n",
"\t\t]),\n",
"\t\tNone => ShutdownRequest::create_rx([ShutdownRequest::CtrlC]),\n",
"\t};\n",
"\n",
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "cli/src/commands/tunnels.rs",
"type": "replace",
"edit_start_line_idx": 305
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITerminalLinkDetector, ITerminalSimpleLink, OmitFirstArg } from 'vs/workbench/contrib/terminalContrib/links/browser/links';
import { convertLinkRangeToBuffer, getXtermLineContent } from 'vs/workbench/contrib/terminalContrib/links/browser/terminalLinkHelpers';
import { ITerminalExternalLinkProvider } from 'vs/workbench/contrib/terminal/browser/terminal';
import { IBufferLine, Terminal } from 'xterm';
export class TerminalExternalLinkDetector implements ITerminalLinkDetector {
readonly maxLinkLength = 2000;
constructor(
readonly id: string,
readonly xterm: Terminal,
private readonly _provideLinks: OmitFirstArg<ITerminalExternalLinkProvider['provideLinks']>
) {
}
async detect(lines: IBufferLine[], startLine: number, endLine: number): Promise<ITerminalSimpleLink[]> {
// Get the text representation of the wrapped line
const text = getXtermLineContent(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
if (text === '' || text.length > this.maxLinkLength) {
return [];
}
const externalLinks = await this._provideLinks(text);
if (!externalLinks) {
return [];
}
const result = externalLinks.map(link => {
const bufferRange = convertLinkRangeToBuffer(lines, this.xterm.cols, {
startColumn: link.startIndex + 1,
startLineNumber: 1,
endColumn: link.startIndex + link.length + 1,
endLineNumber: 1
}, startLine);
const matchingText = text.substring(link.startIndex, link.startIndex + link.length) || '';
const l: ITerminalSimpleLink = {
text: matchingText,
label: link.label,
bufferRange,
type: { id: this.id },
activate: link.activate
};
return l;
});
return result;
}
}
| src/vs/workbench/contrib/terminalContrib/links/browser/terminalExternalLinkDetector.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017671496607363224,
0.00017337991448584944,
0.00016956395120359957,
0.00017354288138449192,
0.0000022195808924152516
] |
{
"id": 1,
"code_window": [
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n",
"\tlet server = loop {\n",
"\t\tif shutdown.is_open() {\n",
"\t\t\treturn Ok(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tlet mut vec = vec![\n",
"\t\tShutdownRequest::CtrlC,\n",
"\t\tShutdownRequest::ExeUninstalled(current_exe.to_owned()),\n",
"\t];\n",
"\tif let Some(p) = gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tvec.push(ShutdownRequest::ParentProcessKilled(p));\n",
"\t}\n",
"\tlet shutdown = ShutdownRequest::create_rx(vec);\n",
"\n"
],
"file_path": "cli/src/commands/tunnels.rs",
"type": "add",
"edit_start_line_idx": 320
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use std::{path::Path, time::Duration};
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
pub fn process_at_path_exists(pid: u32, name: &Path) -> bool {
let mut sys = System::new();
let pid = Pid::from_u32(pid);
if !sys.refresh_process(pid) {
return false;
}
let name_str = format!("{}", name.display());
if let Some(process) = sys.process(pid) {
for cmd in process.cmd() {
if cmd.contains(&name_str) {
return true;
}
}
}
false
}
pub fn process_exists(pid: u32) -> bool {
let mut sys = System::new();
sys.refresh_process(Pid::from_u32(pid))
}
pub async fn wait_until_process_exits(pid: Pid, poll_ms: u64) {
let mut s = System::new();
let duration = Duration::from_millis(poll_ms);
while s.refresh_process(pid) {
tokio::time::sleep(duration).await;
}
}
pub fn find_running_process(name: &Path) -> Option<u32> {
let mut sys = System::new();
sys.refresh_processes();
let name_str = format!("{}", name.display());
for (pid, process) in sys.processes() {
for cmd in process.cmd() {
if cmd.contains(&name_str) {
return Some(pid.as_u32());
}
}
}
None
}
| cli/src/util/machine.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017719095922075212,
0.0001707357441773638,
0.00016568989667575806,
0.00016958682681433856,
0.000003919171831512358
] |
{
"id": 1,
"code_window": [
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n",
"\tlet server = loop {\n",
"\t\tif shutdown.is_open() {\n",
"\t\t\treturn Ok(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tlet mut vec = vec![\n",
"\t\tShutdownRequest::CtrlC,\n",
"\t\tShutdownRequest::ExeUninstalled(current_exe.to_owned()),\n",
"\t];\n",
"\tif let Some(p) = gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tvec.push(ShutdownRequest::ParentProcessKilled(p));\n",
"\t}\n",
"\tlet shutdown = ShutdownRequest::create_rx(vec);\n",
"\n"
],
"file_path": "cli/src/commands/tunnels.rs",
"type": "add",
"edit_start_line_idx": 320
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { getEditorFeatures } from 'vs/editor/common/editorFeatures';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions } from 'vs/workbench/common/contributions';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
class EditorFeaturesInstantiator extends Disposable implements IWorkbenchContribution {
private _instantiated = false;
constructor(
@ICodeEditorService codeEditorService: ICodeEditorService,
@IInstantiationService private readonly _instantiationService: IInstantiationService
) {
super();
this._register(codeEditorService.onWillCreateCodeEditor(() => this._instantiate()));
this._register(codeEditorService.onWillCreateDiffEditor(() => this._instantiate()));
if (codeEditorService.listCodeEditors().length > 0 || codeEditorService.listDiffEditors().length > 0) {
this._instantiate();
}
}
private _instantiate(): void {
if (this._instantiated) {
return;
}
this._instantiated = true;
// Instantiate all editor features
const editorFeatures = getEditorFeatures();
for (const feature of editorFeatures) {
try {
const instance = this._instantiationService.createInstance(feature);
if (typeof (<IDisposable>instance).dispose === 'function') {
this._register((<IDisposable>instance));
}
} catch (err) {
onUnexpectedError(err);
}
}
}
}
const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(Extensions.Workbench);
workbenchRegistry.registerWorkbenchContribution(EditorFeaturesInstantiator, LifecyclePhase.Ready);
| src/vs/workbench/contrib/codeEditor/browser/editorFeatures.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017609716451261193,
0.00017330287664663047,
0.0001704950409475714,
0.000172805244801566,
0.000001821919340727618
] |
{
"id": 1,
"code_window": [
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n",
"\tlet server = loop {\n",
"\t\tif shutdown.is_open() {\n",
"\t\t\treturn Ok(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tlet mut vec = vec![\n",
"\t\tShutdownRequest::CtrlC,\n",
"\t\tShutdownRequest::ExeUninstalled(current_exe.to_owned()),\n",
"\t];\n",
"\tif let Some(p) = gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tvec.push(ShutdownRequest::ParentProcessKilled(p));\n",
"\t}\n",
"\tlet shutdown = ShutdownRequest::create_rx(vec);\n",
"\n"
],
"file_path": "cli/src/commands/tunnels.rs",
"type": "add",
"edit_start_line_idx": 320
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookLoggingService } from 'vs/workbench/contrib/notebook/common/notebookLoggingService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
class NotebookKernelDetection extends Disposable implements IWorkbenchContribution {
private _detectionMap = new Map<string, IDisposable>();
private _localDisposableStore = this._register(new DisposableStore());
constructor(
@INotebookKernelService private readonly _notebookKernelService: INotebookKernelService,
@IExtensionService private readonly _extensionService: IExtensionService,
@INotebookLoggingService private readonly _notebookLoggingService: INotebookLoggingService
) {
super();
this._registerListeners();
}
private _registerListeners() {
this._localDisposableStore.clear();
this._localDisposableStore.add(this._extensionService.onWillActivateByEvent(e => {
if (e.event.startsWith('onNotebook:')) {
if (this._extensionService.activationEventIsDone(e.event)) {
return;
}
// parse the event to get the notebook type
const notebookType = e.event.substring('onNotebook:'.length);
if (notebookType === '*') {
// ignore
return;
}
let shouldStartDetection = false;
const extensionStatus = this._extensionService.getExtensionsStatus();
this._extensionService.extensions.forEach(extension => {
if (extensionStatus[extension.identifier.value].activationTimes) {
// already activated
return;
}
if (extension.activationEvents?.includes(e.event)) {
shouldStartDetection = true;
}
});
if (shouldStartDetection && !this._detectionMap.has(notebookType)) {
this._notebookLoggingService.debug('KernelDetection', `start extension activation for ${notebookType}`);
const task = this._notebookKernelService.registerNotebookKernelDetectionTask({
notebookType: notebookType
});
this._detectionMap.set(notebookType, task);
}
}
}));
let timer: any = null;
this._localDisposableStore.add(this._extensionService.onDidChangeExtensionsStatus(() => {
if (timer) {
clearTimeout(timer);
}
// activation state might not be updated yet, postpone to next frame
timer = setTimeout(() => {
const taskToDelete: string[] = [];
for (const [notebookType, task] of this._detectionMap) {
if (this._extensionService.activationEventIsDone(`onNotebook:${notebookType}`)) {
this._notebookLoggingService.debug('KernelDetection', `finish extension activation for ${notebookType}`);
taskToDelete.push(notebookType);
task.dispose();
}
}
taskToDelete.forEach(notebookType => {
this._detectionMap.delete(notebookType);
});
});
}));
this._localDisposableStore.add({
dispose: () => {
if (timer) {
clearTimeout(timer);
}
}
});
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(NotebookKernelDetection, LifecyclePhase.Restored);
| src/vs/workbench/contrib/notebook/browser/contrib/kernelDetection/notebookKernelDetection.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017672641843091697,
0.000172903120983392,
0.00016826868522912264,
0.0001730959484120831,
0.0000026737152438727207
] |
{
"id": 1,
"code_window": [
"\t// Intentionally read before starting the server. If the server updated and\n",
"\t// respawn is requested, the old binary will get renamed, and then\n",
"\t// current_exe will point to the wrong path.\n",
"\tlet current_exe = std::env::current_exe().unwrap();\n",
"\tlet server = loop {\n",
"\t\tif shutdown.is_open() {\n",
"\t\t\treturn Ok(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tlet mut vec = vec![\n",
"\t\tShutdownRequest::CtrlC,\n",
"\t\tShutdownRequest::ExeUninstalled(current_exe.to_owned()),\n",
"\t];\n",
"\tif let Some(p) = gateway_args\n",
"\t\t.parent_process_id\n",
"\t\t.and_then(|p| Pid::from_str(&p).ok())\n",
"\t{\n",
"\t\tvec.push(ShutdownRequest::ParentProcessKilled(p));\n",
"\t}\n",
"\tlet shutdown = ShutdownRequest::create_rx(vec);\n",
"\n"
],
"file_path": "cli/src/commands/tunnels.rs",
"type": "add",
"edit_start_line_idx": 320
} | /*---------------------------------------------------------------------------------------------
* 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 { Event, Emitter } from 'vs/base/common/event';
export interface INotebookFindFiltersChangeEvent {
markupInput?: boolean;
markupPreview?: boolean;
codeInput?: boolean;
codeOutput?: boolean;
}
export class NotebookFindFilters extends Disposable {
private readonly _onDidChange: Emitter<INotebookFindFiltersChangeEvent> = this._register(new Emitter<INotebookFindFiltersChangeEvent>());
readonly onDidChange: Event<INotebookFindFiltersChangeEvent> = this._onDidChange.event;
private _markupInput: boolean = true;
get markupInput(): boolean {
return this._markupInput;
}
set markupInput(value: boolean) {
if (this._markupInput !== value) {
this._markupInput = value;
this._onDidChange.fire({ markupInput: value });
}
}
private _markupPreview: boolean = true;
get markupPreview(): boolean {
return this._markupPreview;
}
set markupPreview(value: boolean) {
if (this._markupPreview !== value) {
this._markupPreview = value;
this._onDidChange.fire({ markupPreview: value });
}
}
private _codeInput: boolean = true;
get codeInput(): boolean {
return this._codeInput;
}
set codeInput(value: boolean) {
if (this._codeInput !== value) {
this._codeInput = value;
this._onDidChange.fire({ codeInput: value });
}
}
private _codeOutput: boolean = true;
get codeOutput(): boolean {
return this._codeOutput;
}
set codeOutput(value: boolean) {
if (this._codeOutput !== value) {
this._codeOutput = value;
this._onDidChange.fire({ codeOutput: value });
}
}
private readonly _initialMarkupInput: boolean;
private readonly _initialMarkupPreview: boolean;
private readonly _initialCodeInput: boolean;
private readonly _initialCodeOutput: boolean;
constructor(
markupInput: boolean,
markupPreview: boolean,
codeInput: boolean,
codeOutput: boolean
) {
super();
this._markupInput = markupInput;
this._markupPreview = markupPreview;
this._codeInput = codeInput;
this._codeOutput = codeOutput;
this._initialMarkupInput = markupInput;
this._initialMarkupPreview = markupPreview;
this._initialCodeInput = codeInput;
this._initialCodeOutput = codeOutput;
}
isModified(): boolean {
return (
this._markupInput !== this._initialMarkupInput
|| this._markupPreview !== this._initialMarkupPreview
|| this._codeInput !== this._initialCodeInput
|| this._codeOutput !== this._initialCodeOutput
);
}
update(v: NotebookFindFilters) {
this._markupInput = v.markupInput;
this._markupPreview = v.markupPreview;
this._codeInput = v.codeInput;
this._codeOutput = v.codeOutput;
}
}
| src/vs/workbench/contrib/notebook/browser/contrib/find/findFilters.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001784246851457283,
0.0001754159020492807,
0.00017211586236953735,
0.00017544665024615824,
0.0000017209315501531819
] |
{
"id": 2,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"use futures::{stream::FuturesUnordered, StreamExt};\n",
"use std::fmt;\n",
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"use std::{fmt, path::PathBuf};\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.3447726368904114,
0.0385611392557621,
0.00016728004266042262,
0.00018080261361319572,
0.10826229304075241
] |
{
"id": 2,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"use futures::{stream::FuturesUnordered, StreamExt};\n",
"use std::fmt;\n",
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"use std::{fmt, path::PathBuf};\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerAccessibilityConfiguration } from 'vs/workbench/contrib/accessibility/browser/accessibilityContribution';
registerAccessibilityConfiguration();
| src/vs/workbench/contrib/accessibility/browser/accessibility.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001683967566350475,
0.0001683967566350475,
0.0001683967566350475,
0.0001683967566350475,
0
] |
{
"id": 2,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"use futures::{stream::FuturesUnordered, StreamExt};\n",
"use std::fmt;\n",
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"use std::{fmt, path::PathBuf};\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { deepStrictEqual, strictEqual } from 'assert';
import { IStringDictionary } from 'vs/base/common/collections';
import { isWindows, OperatingSystem, Platform } from 'vs/base/common/platform';
import { URI as Uri } from 'vs/base/common/uri';
import { addTerminalEnvironmentKeys, createTerminalEnvironment, getCwd, getDefaultShell, getLangEnvVariable, mergeEnvironments, preparePathForShell, shouldSetLangEnvVariable } from 'vs/workbench/contrib/terminal/common/terminalEnvironment';
import { PosixShellType, WindowsShellType } from 'vs/platform/terminal/common/terminal';
suite('Workbench - TerminalEnvironment', () => {
suite('addTerminalEnvironmentKeys', () => {
test('should set expected variables', () => {
const env: { [key: string]: any } = {};
addTerminalEnvironmentKeys(env, '1.2.3', 'en', 'on');
strictEqual(env['TERM_PROGRAM'], 'vscode');
strictEqual(env['TERM_PROGRAM_VERSION'], '1.2.3');
strictEqual(env['COLORTERM'], 'truecolor');
strictEqual(env['LANG'], 'en_US.UTF-8');
});
test('should use language variant for LANG that is provided in locale', () => {
const env: { [key: string]: any } = {};
addTerminalEnvironmentKeys(env, '1.2.3', 'en-au', 'on');
strictEqual(env['LANG'], 'en_AU.UTF-8', 'LANG is equal to the requested locale with UTF-8');
});
test('should fallback to en_US when no locale is provided', () => {
const env2: { [key: string]: any } = { FOO: 'bar' };
addTerminalEnvironmentKeys(env2, '1.2.3', undefined, 'on');
strictEqual(env2['LANG'], 'en_US.UTF-8', 'LANG is equal to en_US.UTF-8 as fallback.'); // More info on issue #14586
});
test('should fallback to en_US when an invalid locale is provided', () => {
const env3 = { LANG: 'replace' };
addTerminalEnvironmentKeys(env3, '1.2.3', undefined, 'on');
strictEqual(env3['LANG'], 'en_US.UTF-8', 'LANG is set to the fallback LANG');
});
test('should override existing LANG', () => {
const env4 = { LANG: 'en_AU.UTF-8' };
addTerminalEnvironmentKeys(env4, '1.2.3', undefined, 'on');
strictEqual(env4['LANG'], 'en_US.UTF-8', 'LANG is equal to the parent environment\'s LANG');
});
});
suite('shouldSetLangEnvVariable', () => {
test('auto', () => {
strictEqual(shouldSetLangEnvVariable({}, 'auto'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US' }, 'auto'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf' }, 'auto'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf8' }, 'auto'), false);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.UTF-8' }, 'auto'), false);
});
test('off', () => {
strictEqual(shouldSetLangEnvVariable({}, 'off'), false);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US' }, 'off'), false);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf' }, 'off'), false);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf8' }, 'off'), false);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.UTF-8' }, 'off'), false);
});
test('on', () => {
strictEqual(shouldSetLangEnvVariable({}, 'on'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US' }, 'on'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf' }, 'on'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf8' }, 'on'), true);
strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.UTF-8' }, 'on'), true);
});
});
suite('getLangEnvVariable', () => {
test('should fallback to en_US when no locale is provided', () => {
strictEqual(getLangEnvVariable(undefined), 'en_US.UTF-8');
strictEqual(getLangEnvVariable(''), 'en_US.UTF-8');
});
test('should fallback to default language variants when variant isn\'t provided', () => {
strictEqual(getLangEnvVariable('af'), 'af_ZA.UTF-8');
strictEqual(getLangEnvVariable('am'), 'am_ET.UTF-8');
strictEqual(getLangEnvVariable('be'), 'be_BY.UTF-8');
strictEqual(getLangEnvVariable('bg'), 'bg_BG.UTF-8');
strictEqual(getLangEnvVariable('ca'), 'ca_ES.UTF-8');
strictEqual(getLangEnvVariable('cs'), 'cs_CZ.UTF-8');
strictEqual(getLangEnvVariable('da'), 'da_DK.UTF-8');
strictEqual(getLangEnvVariable('de'), 'de_DE.UTF-8');
strictEqual(getLangEnvVariable('el'), 'el_GR.UTF-8');
strictEqual(getLangEnvVariable('en'), 'en_US.UTF-8');
strictEqual(getLangEnvVariable('es'), 'es_ES.UTF-8');
strictEqual(getLangEnvVariable('et'), 'et_EE.UTF-8');
strictEqual(getLangEnvVariable('eu'), 'eu_ES.UTF-8');
strictEqual(getLangEnvVariable('fi'), 'fi_FI.UTF-8');
strictEqual(getLangEnvVariable('fr'), 'fr_FR.UTF-8');
strictEqual(getLangEnvVariable('he'), 'he_IL.UTF-8');
strictEqual(getLangEnvVariable('hr'), 'hr_HR.UTF-8');
strictEqual(getLangEnvVariable('hu'), 'hu_HU.UTF-8');
strictEqual(getLangEnvVariable('hy'), 'hy_AM.UTF-8');
strictEqual(getLangEnvVariable('is'), 'is_IS.UTF-8');
strictEqual(getLangEnvVariable('it'), 'it_IT.UTF-8');
strictEqual(getLangEnvVariable('ja'), 'ja_JP.UTF-8');
strictEqual(getLangEnvVariable('kk'), 'kk_KZ.UTF-8');
strictEqual(getLangEnvVariable('ko'), 'ko_KR.UTF-8');
strictEqual(getLangEnvVariable('lt'), 'lt_LT.UTF-8');
strictEqual(getLangEnvVariable('nl'), 'nl_NL.UTF-8');
strictEqual(getLangEnvVariable('no'), 'no_NO.UTF-8');
strictEqual(getLangEnvVariable('pl'), 'pl_PL.UTF-8');
strictEqual(getLangEnvVariable('pt'), 'pt_BR.UTF-8');
strictEqual(getLangEnvVariable('ro'), 'ro_RO.UTF-8');
strictEqual(getLangEnvVariable('ru'), 'ru_RU.UTF-8');
strictEqual(getLangEnvVariable('sk'), 'sk_SK.UTF-8');
strictEqual(getLangEnvVariable('sl'), 'sl_SI.UTF-8');
strictEqual(getLangEnvVariable('sr'), 'sr_YU.UTF-8');
strictEqual(getLangEnvVariable('sv'), 'sv_SE.UTF-8');
strictEqual(getLangEnvVariable('tr'), 'tr_TR.UTF-8');
strictEqual(getLangEnvVariable('uk'), 'uk_UA.UTF-8');
strictEqual(getLangEnvVariable('zh'), 'zh_CN.UTF-8');
});
test('should set language variant based on full locale', () => {
strictEqual(getLangEnvVariable('en-AU'), 'en_AU.UTF-8');
strictEqual(getLangEnvVariable('en-au'), 'en_AU.UTF-8');
strictEqual(getLangEnvVariable('fa-ke'), 'fa_KE.UTF-8');
});
});
suite('mergeEnvironments', () => {
test('should add keys', () => {
const parent = {
a: 'b'
};
const other = {
c: 'd'
};
mergeEnvironments(parent, other);
deepStrictEqual(parent, {
a: 'b',
c: 'd'
});
});
(!isWindows ? test.skip : test)('should add keys ignoring case on Windows', () => {
const parent = {
a: 'b'
};
const other = {
A: 'c'
};
mergeEnvironments(parent, other);
deepStrictEqual(parent, {
a: 'c'
});
});
test('null values should delete keys from the parent env', () => {
const parent = {
a: 'b',
c: 'd'
};
const other: IStringDictionary<string | null> = {
a: null
};
mergeEnvironments(parent, other);
deepStrictEqual(parent, {
c: 'd'
});
});
(!isWindows ? test.skip : test)('null values should delete keys from the parent env ignoring case on Windows', () => {
const parent = {
a: 'b',
c: 'd'
};
const other: IStringDictionary<string | null> = {
A: null
};
mergeEnvironments(parent, other);
deepStrictEqual(parent, {
c: 'd'
});
});
});
suite('getCwd', () => {
// This helper checks the paths in a cross-platform friendly manner
function assertPathsMatch(a: string, b: string): void {
strictEqual(Uri.file(a).fsPath, Uri.file(b).fsPath);
}
test('should default to userHome for an empty workspace', async () => {
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, undefined), '/userHome/');
});
test('should use to the workspace if it exists', async () => {
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/foo'), undefined), '/foo');
});
test('should use an absolute custom cwd as is', async () => {
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, '/foo'), '/foo');
});
test('should normalize a relative custom cwd against the workspace path', async () => {
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/bar'), 'foo'), '/bar/foo');
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/bar'), './foo'), '/bar/foo');
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/bar'), '../foo'), '/foo');
});
test('should fall back for relative a custom cwd that doesn\'t have a workspace', async () => {
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, 'foo'), '/userHome/');
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, './foo'), '/userHome/');
assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, '../foo'), '/userHome/');
});
test('should ignore custom cwd when told to ignore', async () => {
assertPathsMatch(await getCwd({ executable: undefined, args: [], ignoreConfigurationCwd: true }, '/userHome/', undefined, Uri.file('/bar'), '/foo'), '/bar');
});
});
suite('getDefaultShell', () => {
test('should change Sysnative to System32 in non-WoW64 systems', async () => {
const shell = await getDefaultShell(key => {
return ({ 'terminal.integrated.shell.windows': 'C:\\Windows\\Sysnative\\cmd.exe' } as any)[key];
}, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, false, Platform.Windows);
strictEqual(shell, 'C:\\Windows\\System32\\cmd.exe');
});
test('should not change Sysnative to System32 in WoW64 systems', async () => {
const shell = await getDefaultShell(key => {
return ({ 'terminal.integrated.shell.windows': 'C:\\Windows\\Sysnative\\cmd.exe' } as any)[key];
}, 'DEFAULT', true, 'C:\\Windows', undefined, {} as any, false, Platform.Windows);
strictEqual(shell, 'C:\\Windows\\Sysnative\\cmd.exe');
});
test('should use automationShell when specified', async () => {
const shell1 = await getDefaultShell(key => {
return ({
'terminal.integrated.shell.windows': 'shell',
'terminal.integrated.automationShell.windows': undefined
} as any)[key];
}, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, false, Platform.Windows);
strictEqual(shell1, 'shell', 'automationShell was false');
const shell2 = await getDefaultShell(key => {
return ({
'terminal.integrated.shell.windows': 'shell',
'terminal.integrated.automationShell.windows': undefined
} as any)[key];
}, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, true, Platform.Windows);
strictEqual(shell2, 'shell', 'automationShell was true');
const shell3 = await getDefaultShell(key => {
return ({
'terminal.integrated.shell.windows': 'shell',
'terminal.integrated.automationShell.windows': 'automationShell'
} as any)[key];
}, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, true, Platform.Windows);
strictEqual(shell3, 'automationShell', 'automationShell was true and specified in settings');
});
});
suite('preparePathForShell', () => {
const wslPathBackend = {
getWslPath: async (original: string, direction: 'unix-to-win' | 'win-to-unix') => {
if (direction === 'unix-to-win') {
const match = original.match(/^\/mnt\/(?<drive>[a-zA-Z])\/(?<path>.+)$/);
const groups = match?.groups;
if (!groups) {
return original;
}
return `${groups.drive}:\\${groups.path.replace(/\//g, '\\')}`;
}
const match = original.match(/(?<drive>[a-zA-Z]):\\(?<path>.+)/);
const groups = match?.groups;
if (!groups) {
return original;
}
return `/mnt/${groups.drive.toLowerCase()}/${groups.path.replace(/\\/g, '/')}`;
}
};
suite('Windows frontend, Windows backend', () => {
test('Command Prompt', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, true), `c:\\foo\\bar`);
strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, true), `c:\\foo\\bar'baz`);
strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, true), `"c:\\foo\\bar$(echo evil)baz"`);
});
test('PowerShell', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, true), `c:\\foo\\bar`);
strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, true), `& 'c:\\foo\\bar''baz'`);
strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, true), `& 'c:\\foo\\bar$(echo evil)baz'`);
});
test('Git Bash', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, true), `'c:/foo/bar'`);
strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, true), `'c:/foo/bar(echo evil)baz'`);
});
test('WSL', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.Wsl, wslPathBackend, OperatingSystem.Windows, true), '/mnt/c/foo/bar');
});
});
suite('Windows frontend, Linux backend', () => {
test('Bash', async () => {
strictEqual(await preparePathForShell('/foo/bar', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, true), `'/foo/bar'`);
strictEqual(await preparePathForShell('/foo/bar\'baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, true), `'/foo/barbaz'`);
strictEqual(await preparePathForShell('/foo/bar$(echo evil)baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, true), `'/foo/bar(echo evil)baz'`);
});
});
suite('Linux frontend, Windows backend', () => {
test('Command Prompt', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, false), `c:\\foo\\bar`);
strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, false), `c:\\foo\\bar'baz`);
strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, false), `"c:\\foo\\bar$(echo evil)baz"`);
});
test('PowerShell', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, false), `c:\\foo\\bar`);
strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, false), `& 'c:\\foo\\bar''baz'`);
strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, false), `& 'c:\\foo\\bar$(echo evil)baz'`);
});
test('Git Bash', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, false), `'c:/foo/bar'`);
strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, false), `'c:/foo/bar(echo evil)baz'`);
});
test('WSL', async () => {
strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.Wsl, wslPathBackend, OperatingSystem.Windows, false), '/mnt/c/foo/bar');
});
});
suite('Linux frontend, Linux backend', () => {
test('Bash', async () => {
strictEqual(await preparePathForShell('/foo/bar', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, false), `'/foo/bar'`);
strictEqual(await preparePathForShell('/foo/bar\'baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, false), `'/foo/barbaz'`);
strictEqual(await preparePathForShell('/foo/bar$(echo evil)baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, false), `'/foo/bar(echo evil)baz'`);
});
});
});
suite('createTerminalEnvironment', () => {
const commonVariables = {
COLORTERM: 'truecolor',
TERM_PROGRAM: 'vscode'
};
test('should retain variables equal to the empty string', async () => {
deepStrictEqual(
await createTerminalEnvironment({}, undefined, undefined, undefined, 'off', { foo: 'bar', empty: '' }),
{ foo: 'bar', empty: '', ...commonVariables }
);
});
});
});
| src/vs/workbench/contrib/terminal/test/common/terminalEnvironment.test.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017627204942982644,
0.00017275268328376114,
0.00016606536519248039,
0.0001734289398882538,
0.0000025743684091139585
] |
{
"id": 2,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"use futures::{stream::FuturesUnordered, StreamExt};\n",
"use std::fmt;\n",
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"use std::{fmt, path::PathBuf};\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { LengthObj } from 'vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length';
import { DocumentRangeMap, RangeMapping } from 'vs/workbench/contrib/mergeEditor/browser/model/mapping';
suite('merge editor mapping', () => {
ensureNoDisposablesAreLeakedInTestSuite();
suite('DocumentRangeMap', () => {
const documentMap = createDocumentRangeMap([
'1:3',
['0:2', '0:3'],
'1:1',
['1:2', '3:3'],
'0:2',
['0:2', '0:3'],
]);
test('map', () => assert.deepStrictEqual(documentMap.rangeMappings.map(m => m.toString()), [
'[2:4, 2:6) -> [2:4, 2:7)',
'[3:2, 4:3) -> [3:2, 6:4)',
'[4:5, 4:7) -> [6:6, 6:9)'
]));
function f(this: Mocha.Context) {
return documentMap.project(parsePos(this.test!.title)).toString();
}
test('1:1', function () { assert.deepStrictEqual(f.apply(this), '[1:1, 1:1) -> [1:1, 1:1)'); });
test('2:3', function () { assert.deepStrictEqual(f.apply(this), '[2:3, 2:3) -> [2:3, 2:3)'); });
test('2:4', function () { assert.deepStrictEqual(f.apply(this), '[2:4, 2:6) -> [2:4, 2:7)'); });
test('2:5', function () { assert.deepStrictEqual(f.apply(this), '[2:4, 2:6) -> [2:4, 2:7)'); });
test('2:6', function () { assert.deepStrictEqual(f.apply(this), '[2:6, 2:6) -> [2:7, 2:7)'); });
test('2:7', function () { assert.deepStrictEqual(f.apply(this), '[2:7, 2:7) -> [2:8, 2:8)'); });
test('3:1', function () { assert.deepStrictEqual(f.apply(this), '[3:1, 3:1) -> [3:1, 3:1)'); });
test('3:2', function () { assert.deepStrictEqual(f.apply(this), '[3:2, 4:3) -> [3:2, 6:4)'); });
test('4:2', function () { assert.deepStrictEqual(f.apply(this), '[3:2, 4:3) -> [3:2, 6:4)'); });
test('4:3', function () { assert.deepStrictEqual(f.apply(this), '[4:3, 4:3) -> [6:4, 6:4)'); });
test('4:4', function () { assert.deepStrictEqual(f.apply(this), '[4:4, 4:4) -> [6:5, 6:5)'); });
test('4:5', function () { assert.deepStrictEqual(f.apply(this), '[4:5, 4:7) -> [6:6, 6:9)'); });
});
});
function parsePos(str: string): Position {
const [lineCount, columnCount] = str.split(':');
return new Position(parseInt(lineCount, 10), parseInt(columnCount, 10));
}
function parseLengthObj(str: string): LengthObj {
const [lineCount, columnCount] = str.split(':');
return new LengthObj(parseInt(lineCount, 10), parseInt(columnCount, 10));
}
function toPosition(length: LengthObj): Position {
return new Position(length.lineCount + 1, length.columnCount + 1);
}
function createDocumentRangeMap(items: ([string, string] | string)[]) {
const mappings: RangeMapping[] = [];
let lastLen1 = new LengthObj(0, 0);
let lastLen2 = new LengthObj(0, 0);
for (const item of items) {
if (typeof item === 'string') {
const len = parseLengthObj(item);
lastLen1 = lastLen1.add(len);
lastLen2 = lastLen2.add(len);
} else {
const len1 = parseLengthObj(item[0]);
const len2 = parseLengthObj(item[1]);
mappings.push(new RangeMapping(
Range.fromPositions(toPosition(lastLen1), toPosition(lastLen1.add(len1))),
Range.fromPositions(toPosition(lastLen2), toPosition(lastLen2.add(len2))),
));
lastLen1 = lastLen1.add(len1);
lastLen2 = lastLen2.add(len2);
}
}
return new DocumentRangeMap(mappings, lastLen1.lineCount);
}
| src/vs/workbench/contrib/mergeEditor/test/browser/mapping.test.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017541089619044214,
0.0001735950936563313,
0.00016741965373512357,
0.00017486467550043017,
0.0000025419808480364736
] |
{
"id": 3,
"code_window": [
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n",
"\tmachine::wait_until_process_exits,\n",
"\tsync::{new_barrier, Barrier, Receivable},\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmachine::{wait_until_exe_deleted, wait_until_process_exits},\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.9930042624473572,
0.22432905435562134,
0.0001654524530749768,
0.00019830651581287384,
0.3943854570388794
] |
{
"id": 3,
"code_window": [
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n",
"\tmachine::wait_until_process_exits,\n",
"\tsync::{new_barrier, Barrier, Receivable},\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmachine::{wait_until_exe_deleted, wait_until_process_exits},\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/84899
/**
* The contiguous set of modified lines in a diff.
*/
export interface LineChange {
readonly originalStartLineNumber: number;
readonly originalEndLineNumber: number;
readonly modifiedStartLineNumber: number;
readonly modifiedEndLineNumber: number;
}
export namespace commands {
/**
* Registers a diff information command that can be invoked via a keyboard shortcut,
* a menu item, an action, or directly.
*
* Diff information commands are different from ordinary {@link commands.registerCommand commands} as
* they only execute when there is an active diff editor when the command is called, and the diff
* information has been computed. Also, the command handler of an editor command has access to
* the diff information.
*
* @param command A unique identifier for the command.
* @param callback A command handler function with access to the {@link LineChange diff information}.
* @param thisArg The `this` context used when invoking the handler function.
* @return Disposable which unregisters this command on disposal.
*/
export function registerDiffInformationCommand(command: string, callback: (diff: LineChange[], ...args: any[]) => any, thisArg?: any): Disposable;
}
}
| src/vscode-dts/vscode.proposed.diffCommand.d.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0007044345256872475,
0.0003055624838452786,
0.00017078725795727223,
0.00017351406859233975,
0.00023029532167129219
] |
{
"id": 3,
"code_window": [
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n",
"\tmachine::wait_until_process_exits,\n",
"\tsync::{new_barrier, Barrier, Receivable},\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmachine::{wait_until_exe_deleted, wait_until_process_exits},\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 10
} | .vscode/**
typings/**
**/*.ts
**/*.map
.gitignore
tsconfig.json
| extensions/vscode-test-resolver/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001762476604199037,
0.0001762476604199037,
0.0001762476604199037,
0.0001762476604199037,
0
] |
{
"id": 3,
"code_window": [
"use sysinfo::Pid;\n",
"\n",
"use crate::util::{\n",
"\tmachine::wait_until_process_exits,\n",
"\tsync::{new_barrier, Barrier, Receivable},\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tmachine::{wait_until_exe_deleted, wait_until_process_exits},\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Event } from 'vs/base/common/event';
import { EnvironmentVariableScope, IEnvironmentVariableCollection, IMergedEnvironmentVariableCollection } from 'vs/platform/terminal/common/environmentVariable';
import { ITerminalStatus } from 'vs/workbench/contrib/terminal/common/terminal';
export const IEnvironmentVariableService = createDecorator<IEnvironmentVariableService>('environmentVariableService');
/**
* Tracks and persists environment variable collections as defined by extensions.
*/
export interface IEnvironmentVariableService {
readonly _serviceBrand: undefined;
/**
* Gets a single collection constructed by merging all environment variable collections into
* one.
*/
readonly collections: ReadonlyMap<string, IEnvironmentVariableCollection>;
/**
* Gets a single collection constructed by merging all environment variable collections into
* one.
*/
readonly mergedCollection: IMergedEnvironmentVariableCollection;
/**
* An event that is fired when an extension's environment variable collection changes, the event
* provides the new merged collection.
*/
onDidChangeCollections: Event<IMergedEnvironmentVariableCollection>;
/**
* Sets an extension's environment variable collection.
*/
set(extensionIdentifier: string, collection: IEnvironmentVariableCollection): void;
/**
* Deletes an extension's environment variable collection.
*/
delete(extensionIdentifier: string): void;
}
export interface IEnvironmentVariableCollectionWithPersistence extends IEnvironmentVariableCollection {
readonly persistent: boolean;
}
export interface IEnvironmentVariableInfo {
readonly requiresAction: boolean;
getStatus(scope: EnvironmentVariableScope | undefined): ITerminalStatus;
}
| src/vs/workbench/contrib/terminal/common/environmentVariable.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00019379658624529839,
0.0001745015470078215,
0.00016832146502565593,
0.00017140069394372404,
0.000008891539437172469
] |
{
"id": 4,
"code_window": [
"pub enum ShutdownSignal {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tServiceStopped,\n",
"\tRpcShutdownRequested,\n",
"\tRpcRestartRequested,\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled,\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 19
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.9988886713981628,
0.6555297374725342,
0.00017128711624536663,
0.9648916721343994,
0.4635886251926422
] |
{
"id": 4,
"code_window": [
"pub enum ShutdownSignal {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tServiceStopped,\n",
"\tRpcShutdownRequested,\n",
"\tRpcRestartRequested,\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled,\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 19
} | @import "mystyle.css";
@import url("mystyle.css");
@import url("bluish.css") projection, tv;
@base: #f938ab;
.box-shadow(@style, @c) when (iscolor(@c)) {
border-radius: @style @c;
}
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
.box-shadow(@style, rgba(0, 0, 0, @alpha));
}
.box {
color: saturate(@base, 5%);
border-color: lighten(@base, 30%);
div {
.box-shadow((0 0 5px), 30%);
}
}
#header {
h1 {
font-size: 26px;
font-weight: bold;
}
p { font-size: 12px;
a { text-decoration: none;
&:hover { border-width: 1px }
}
}
}
@the-border: 1px;
@base-color: #111;
@red: #842210;
#header {
color: (@base-color * 3);
border-left: @the-border;
border-right: (@the-border * 2);
}
#footer {
color: (@base-color + #003300);
border-color: desaturate(@red, 10%);
}
| extensions/vscode-colorize-tests/test/colorize-fixtures/test.less | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001768338115653023,
0.00017235102131962776,
0.00016793402028270066,
0.00017233588732779026,
0.000003443683226578287
] |
{
"id": 4,
"code_window": [
"pub enum ShutdownSignal {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tServiceStopped,\n",
"\tRpcShutdownRequested,\n",
"\tRpcRestartRequested,\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled,\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 19
} | /*---------------------------------------------------------------------------------------------
* 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/notificationsActions';
import { INotificationViewItem } from 'vs/workbench/common/notifications';
import { localize } from 'vs/nls';
import { Action, IAction } from 'vs/base/common/actions';
import { CLEAR_NOTIFICATION, EXPAND_NOTIFICATION, COLLAPSE_NOTIFICATION, CLEAR_ALL_NOTIFICATIONS, HIDE_NOTIFICATIONS_CENTER, TOGGLE_DO_NOT_DISTURB_MODE } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { Codicon } from 'vs/base/common/codicons';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { ThemeIcon } from 'vs/base/common/themables';
const clearIcon = registerIcon('notifications-clear', Codicon.close, localize('clearIcon', 'Icon for the clear action in notifications.'));
const clearAllIcon = registerIcon('notifications-clear-all', Codicon.clearAll, localize('clearAllIcon', 'Icon for the clear all action in notifications.'));
const hideIcon = registerIcon('notifications-hide', Codicon.chevronDown, localize('hideIcon', 'Icon for the hide action in notifications.'));
const expandIcon = registerIcon('notifications-expand', Codicon.chevronUp, localize('expandIcon', 'Icon for the expand action in notifications.'));
const collapseIcon = registerIcon('notifications-collapse', Codicon.chevronDown, localize('collapseIcon', 'Icon for the collapse action in notifications.'));
const configureIcon = registerIcon('notifications-configure', Codicon.gear, localize('configureIcon', 'Icon for the configure action in notifications.'));
const doNotDisturbIcon = registerIcon('notifications-do-not-disturb', Codicon.bellSlash, localize('doNotDisturbIcon', 'Icon for the mute all action in notifications.'));
export class ClearNotificationAction extends Action {
static readonly ID = CLEAR_NOTIFICATION;
static readonly LABEL = localize('clearNotification', "Clear Notification");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(clearIcon));
}
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(CLEAR_NOTIFICATION, notification);
}
}
export class ClearAllNotificationsAction extends Action {
static readonly ID = CLEAR_ALL_NOTIFICATIONS;
static readonly LABEL = localize('clearNotifications', "Clear All Notifications");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(clearAllIcon));
}
override async run(): Promise<void> {
this.commandService.executeCommand(CLEAR_ALL_NOTIFICATIONS);
}
}
export class ToggleDoNotDisturbAction extends Action {
static readonly ID = TOGGLE_DO_NOT_DISTURB_MODE;
static readonly LABEL = localize('toggleDoNotDisturbMode', "Toggle Do Not Disturb Mode");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(doNotDisturbIcon));
}
override async run(): Promise<void> {
this.commandService.executeCommand(TOGGLE_DO_NOT_DISTURB_MODE);
}
}
export class HideNotificationsCenterAction extends Action {
static readonly ID = HIDE_NOTIFICATIONS_CENTER;
static readonly LABEL = localize('hideNotificationsCenter', "Hide Notifications");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(hideIcon));
}
override async run(): Promise<void> {
this.commandService.executeCommand(HIDE_NOTIFICATIONS_CENTER);
}
}
export class ExpandNotificationAction extends Action {
static readonly ID = EXPAND_NOTIFICATION;
static readonly LABEL = localize('expandNotification', "Expand Notification");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(expandIcon));
}
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(EXPAND_NOTIFICATION, notification);
}
}
export class CollapseNotificationAction extends Action {
static readonly ID = COLLAPSE_NOTIFICATION;
static readonly LABEL = localize('collapseNotification', "Collapse Notification");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(collapseIcon));
}
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(COLLAPSE_NOTIFICATION, notification);
}
}
export class ConfigureNotificationAction extends Action {
static readonly ID = 'workbench.action.configureNotification';
static readonly LABEL = localize('configureNotification', "Configure Notification");
constructor(
id: string,
label: string,
readonly configurationActions: readonly IAction[]
) {
super(id, label, ThemeIcon.asClassName(configureIcon));
}
}
export class CopyNotificationMessageAction extends Action {
static readonly ID = 'workbench.action.copyNotificationMessage';
static readonly LABEL = localize('copyNotification', "Copy Text");
constructor(
id: string,
label: string,
@IClipboardService private readonly clipboardService: IClipboardService
) {
super(id, label);
}
override run(notification: INotificationViewItem): Promise<void> {
return this.clipboardService.writeText(notification.message.raw);
}
}
| src/vs/workbench/browser/parts/notifications/notificationsActions.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017529337492305785,
0.00017004722030833364,
0.00016753976524341851,
0.00016951722500380129,
0.0000019867586615873734
] |
{
"id": 4,
"code_window": [
"pub enum ShutdownSignal {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tServiceStopped,\n",
"\tRpcShutdownRequested,\n",
"\tRpcRestartRequested,\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled,\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 19
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.profile-view-tree-container .customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .actions {
display: inherit;
}
.monaco-workbench .pane > .pane-body > .profile-view-message-container {
display: flex;
padding: 13px 20px 0px 20px;
box-sizing: border-box;
}
.monaco-workbench .pane > .pane-body > .profile-view-message-container p {
margin-block-start: 0em;
margin-block-end: 0em;
}
.monaco-workbench .pane > .pane-body > .profile-view-message-container a {
color: var(--vscode-textLink-foreground)
}
.monaco-workbench .pane > .pane-body > .profile-view-message-container a:hover {
text-decoration: underline;
color: var(--vscode-textLink-activeForeground)
}
.monaco-workbench .pane > .pane-body > .profile-view-message-container a:active {
color: var(--vscode-textLink-activeForeground)
}
.monaco-workbench .pane > .pane-body > .profile-view-message-container.hide {
display: none;
}
.monaco-workbench .pane > .pane-body > .profile-view-buttons-container {
display: flex;
flex-direction: column;
padding: 13px 20px;
box-sizing: border-box;
}
.monaco-workbench .pane > .pane-body > .profile-view-buttons-container > .monaco-button,
.monaco-workbench .pane > .pane-body > .profile-view-buttons-container > .monaco-button-dropdown {
margin-block-start: 13px;
margin-inline-start: 0px;
margin-inline-end: 0px;
max-width: 260px;
margin-left: auto;
margin-right: auto;
}
.monaco-workbench .pane > .pane-body > .profile-view-buttons-container > .monaco-button-dropdown {
width: 100%;
}
.monaco-workbench .pane > .pane-body > .profile-view-buttons-container > .monaco-button-dropdown > .monaco-dropdown-button {
display: flex;
align-items: center;
padding: 0 4px;
}
| src/vs/workbench/services/userDataProfile/browser/media/userDataProfileView.css | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001741287560435012,
0.00016898127796594054,
0.00016636143845971674,
0.00016821318422444165,
0.0000026067268663609866
] |
{
"id": 5,
"code_window": [
"\t\tmatch self {\n",
"\t\t\tShutdownSignal::CtrlC => write!(f, \"Ctrl-C received\"),\n",
"\t\t\tShutdownSignal::ParentProcessKilled(p) => {\n",
"\t\t\t\twrite!(f, \"Parent process {} no longer exists\", p)\n",
"\t\t\t}\n",
"\t\t\tShutdownSignal::ServiceStopped => write!(f, \"Service stopped\"),\n",
"\t\t\tShutdownSignal::RpcShutdownRequested => write!(f, \"RPC client requested shutdown\"),\n",
"\t\t\tShutdownSignal::RpcRestartRequested => {\n",
"\t\t\t\twrite!(f, \"RPC client requested a tunnel restart\")\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownSignal::ExeUninstalled => {\n",
"\t\t\t\twrite!(f, \"Executable no longer exists\")\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 31
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.9912188649177551,
0.19459712505340576,
0.0001736509002512321,
0.0016476480523124337,
0.3459164798259735
] |
{
"id": 5,
"code_window": [
"\t\tmatch self {\n",
"\t\t\tShutdownSignal::CtrlC => write!(f, \"Ctrl-C received\"),\n",
"\t\t\tShutdownSignal::ParentProcessKilled(p) => {\n",
"\t\t\t\twrite!(f, \"Parent process {} no longer exists\", p)\n",
"\t\t\t}\n",
"\t\t\tShutdownSignal::ServiceStopped => write!(f, \"Service stopped\"),\n",
"\t\t\tShutdownSignal::RpcShutdownRequested => write!(f, \"RPC client requested shutdown\"),\n",
"\t\t\tShutdownSignal::RpcRestartRequested => {\n",
"\t\t\t\twrite!(f, \"RPC client requested a tunnel restart\")\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownSignal::ExeUninstalled => {\n",
"\t\t\t\twrite!(f, \"Executable no longer exists\")\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 31
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "vscode-logfile-highlighter",
"repositoryUrl": "https://github.com/emilast/vscode-logfile-highlighter",
"commitHash": "8acba9307254d1887ac770057767698c82d926c6"
}
},
"license": "MIT",
"version": "2.15.0"
}
],
"version": 1
} | extensions/log/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017315868171863258,
0.0001729699142742902,
0.00017278116138186306,
0.0001729699142742902,
1.8876016838476062e-7
] |
{
"id": 5,
"code_window": [
"\t\tmatch self {\n",
"\t\t\tShutdownSignal::CtrlC => write!(f, \"Ctrl-C received\"),\n",
"\t\t\tShutdownSignal::ParentProcessKilled(p) => {\n",
"\t\t\t\twrite!(f, \"Parent process {} no longer exists\", p)\n",
"\t\t\t}\n",
"\t\t\tShutdownSignal::ServiceStopped => write!(f, \"Service stopped\"),\n",
"\t\t\tShutdownSignal::RpcShutdownRequested => write!(f, \"RPC client requested shutdown\"),\n",
"\t\t\tShutdownSignal::RpcRestartRequested => {\n",
"\t\t\t\twrite!(f, \"RPC client requested a tunnel restart\")\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownSignal::ExeUninstalled => {\n",
"\t\t\t\twrite!(f, \"Executable no longer exists\")\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 31
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ExtensionContext } from 'vscode';
import { registerAPICommands } from './api/api1';
import { GitBaseExtensionImpl } from './api/extension';
import { Model } from './model';
export function activate(context: ExtensionContext): GitBaseExtensionImpl {
const apiImpl = new GitBaseExtensionImpl(new Model());
context.subscriptions.push(registerAPICommands(apiImpl));
return apiImpl;
}
| extensions/git-base/src/extension.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017546328308526427,
0.00017427722923457623,
0.00017309116083197296,
0.00017427722923457623,
0.0000011860611266456544
] |
{
"id": 5,
"code_window": [
"\t\tmatch self {\n",
"\t\t\tShutdownSignal::CtrlC => write!(f, \"Ctrl-C received\"),\n",
"\t\t\tShutdownSignal::ParentProcessKilled(p) => {\n",
"\t\t\t\twrite!(f, \"Parent process {} no longer exists\", p)\n",
"\t\t\t}\n",
"\t\t\tShutdownSignal::ServiceStopped => write!(f, \"Service stopped\"),\n",
"\t\t\tShutdownSignal::RpcShutdownRequested => write!(f, \"RPC client requested shutdown\"),\n",
"\t\t\tShutdownSignal::RpcRestartRequested => {\n",
"\t\t\t\twrite!(f, \"RPC client requested a tunnel restart\")\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownSignal::ExeUninstalled => {\n",
"\t\t\t\twrite!(f, \"Executable no longer exists\")\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 31
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
| extensions/xml/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017321249470114708,
0.00017321249470114708,
0.00017321249470114708,
0.00017321249470114708,
0
] |
{
"id": 6,
"code_window": [
"}\n",
"\n",
"pub enum ShutdownRequest {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tDerived(Box<dyn Receivable<ShutdownSignal> + Send>),\n",
"}\n",
"\n",
"impl ShutdownRequest {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled(PathBuf),\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.9992511868476868,
0.5532985329627991,
0.00017114263027906418,
0.9797284007072449,
0.49095696210861206
] |
{
"id": 6,
"code_window": [
"}\n",
"\n",
"pub enum ShutdownRequest {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tDerived(Box<dyn Receivable<ShutdownSignal> + Send>),\n",
"}\n",
"\n",
"impl ShutdownRequest {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled(PathBuf),\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { IListStyles, IStyleController } from 'vs/base/browser/ui/list/listWidget';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { isMacintosh } from 'vs/base/common/platform';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { TrackedRangeStickiness } from 'vs/editor/common/model';
import { PrefixSumComputer } from 'vs/editor/common/model/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { CursorAtBoundary, ICellViewModel, CellEditState, CellFocusMode, ICellOutputViewModel, CellRevealType, CellRevealSyncType, CellRevealRangeType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellViewModel, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModelImpl';
import { diff, NOTEBOOK_EDITOR_CURSOR_BOUNDARY, CellKind, SelectionStateType } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { ICellRange, cellRangesToIndexes, reduceCellRanges, cellRangesEqual } from 'vs/workbench/contrib/notebook/common/notebookRange';
import { NOTEBOOK_CELL_LIST_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { clamp } from 'vs/base/common/numbers';
import { ISplice } from 'vs/base/common/sequence';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { BaseCellRenderTemplate, INotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
import { MarkupCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markupCellViewModel';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IListViewOptions, IListView } from 'vs/base/browser/ui/list/listView';
import { NotebookCellListView } from 'vs/workbench/contrib/notebook/browser/view/notebookCellListView';
const enum CellEditorRevealType {
Line,
Range
}
const enum CellRevealPosition {
Top,
Center,
Bottom,
NearTop
}
function getVisibleCells(cells: CellViewModel[], hiddenRanges: ICellRange[]) {
if (!hiddenRanges.length) {
return cells;
}
let start = 0;
let hiddenRangeIndex = 0;
const result: CellViewModel[] = [];
while (start < cells.length && hiddenRangeIndex < hiddenRanges.length) {
if (start < hiddenRanges[hiddenRangeIndex].start) {
result.push(...cells.slice(start, hiddenRanges[hiddenRangeIndex].start));
}
start = hiddenRanges[hiddenRangeIndex].end + 1;
hiddenRangeIndex++;
}
if (start < cells.length) {
result.push(...cells.slice(start));
}
return result;
}
export const NOTEBOOK_WEBVIEW_BOUNDARY = 5000;
function validateWebviewBoundary(element: HTMLElement) {
const webviewTop = 0 - (parseInt(element.style.top, 10) || 0);
return webviewTop >= 0 && webviewTop <= NOTEBOOK_WEBVIEW_BOUNDARY * 2;
}
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable, IStyleController, INotebookCellList {
protected override readonly view!: NotebookCellListView<CellViewModel>;
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
get scrollableElement(): HTMLElement {
return this.view.scrollableElementDomNode;
}
private _previousFocusedElements: readonly CellViewModel[] = [];
private readonly _localDisposableStore = new DisposableStore();
private readonly _viewModelStore = new DisposableStore();
private styleElement?: HTMLStyleElement;
private readonly _onDidRemoveOutputs = this._localDisposableStore.add(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private readonly _onDidHideOutputs = this._localDisposableStore.add(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidHideOutputs = this._onDidHideOutputs.event;
private readonly _onDidRemoveCellsFromView = this._localDisposableStore.add(new Emitter<readonly ICellViewModel[]>());
readonly onDidRemoveCellsFromView = this._onDidRemoveCellsFromView.event;
private _viewModel: NotebookViewModel | null = null;
get viewModel(): NotebookViewModel | null {
return this._viewModel;
}
private _hiddenRangeIds: string[] = [];
private hiddenRangesPrefixSum: PrefixSumComputer | null = null;
private readonly _onDidChangeVisibleRanges = this._localDisposableStore.add(new Emitter<void>());
onDidChangeVisibleRanges: Event<void> = this._onDidChangeVisibleRanges.event;
private _visibleRanges: ICellRange[] = [];
get visibleRanges() {
return this._visibleRanges;
}
set visibleRanges(ranges: ICellRange[]) {
if (cellRangesEqual(this._visibleRanges, ranges)) {
return;
}
this._visibleRanges = ranges;
this._onDidChangeVisibleRanges.fire();
}
private _isDisposed = false;
get isDisposed() {
return this._isDisposed;
}
private _isInLayout: boolean = false;
private readonly _viewContext: ViewContext;
private _webviewElement: FastDomNode<HTMLElement> | null = null;
get webviewElement() {
return this._webviewElement;
}
get inRenderingTransaction() {
return this.view.inRenderingTransaction;
}
constructor(
private listUser: string,
container: HTMLElement,
viewContext: ViewContext,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, BaseCellRenderTemplate>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IConfigurationService configurationService: IConfigurationService,
@IInstantiationService instantiationService: IInstantiationService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService);
NOTEBOOK_CELL_LIST_FOCUSED.bindTo(this.contextKeyService).set(true);
this._viewContext = viewContext;
this._previousFocusedElements = this.getFocusedElements();
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
this._previousFocusedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousFocusedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
const cursorSelectionListener = this._localDisposableStore.add(new MutableDisposable());
const textEditorAttachListener = this._localDisposableStore.add(new MutableDisposable());
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionListener.value = focusedElement.onDidChangeState((e) => {
if (e.selectionChanged) {
recomputeContext(focusedElement);
}
});
textEditorAttachListener.value = focusedElement.onDidChangeEditorAttachState(() => {
if (focusedElement.editorAttached) {
recomputeContext(focusedElement);
}
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
this._localDisposableStore.add(this.view.onMouseDblClick(() => {
const focus = this.getFocusedElements()[0];
if (focus && focus.cellKind === CellKind.Markup && !focus.isInputCollapsed && !this._viewModel?.options.isReadOnly) {
// scroll the cell into view if out of viewport
const focusedCellIndex = this._getViewIndexUpperBound(focus);
if (focusedCellIndex >= 0) {
this._revealInViewWithMinimalScrolling(focusedCellIndex);
}
focus.updateEditState(CellEditState.Editing, 'dbclick');
focus.focusMode = CellFocusMode.Editor;
}
}));
// update visibleRanges
const updateVisibleRanges = () => {
if (!this.view.length) {
return;
}
const top = this.getViewScrollTop();
const bottom = this.getViewScrollBottom();
if (top >= bottom) {
return;
}
const topViewIndex = clamp(this.view.indexAt(top), 0, this.view.length - 1);
const topElement = this.view.element(topViewIndex);
const topModelIndex = this._viewModel!.getCellIndex(topElement);
const bottomViewIndex = clamp(this.view.indexAt(bottom), 0, this.view.length - 1);
const bottomElement = this.view.element(bottomViewIndex);
const bottomModelIndex = this._viewModel!.getCellIndex(bottomElement);
if (bottomModelIndex - topModelIndex === bottomViewIndex - topViewIndex) {
this.visibleRanges = [{ start: topModelIndex, end: bottomModelIndex + 1 }];
} else {
this.visibleRanges = this._getVisibleRangesFromIndex(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex);
}
};
this._localDisposableStore.add(this.view.onDidChangeContentHeight(() => {
if (this._isInLayout) {
DOM.scheduleAtNextAnimationFrame(() => {
updateVisibleRanges();
});
}
updateVisibleRanges();
}));
this._localDisposableStore.add(this.view.onDidScroll(() => {
if (this._isInLayout) {
DOM.scheduleAtNextAnimationFrame(() => {
updateVisibleRanges();
});
}
updateVisibleRanges();
}));
}
protected override createListView(container: HTMLElement, virtualDelegate: IListVirtualDelegate<CellViewModel>, renderers: IListRenderer<any, any>[], viewOptions: IListViewOptions<CellViewModel>): IListView<CellViewModel> {
return new NotebookCellListView(container, virtualDelegate, renderers, viewOptions);
}
attachWebview(element: HTMLElement) {
element.style.top = `-${NOTEBOOK_WEBVIEW_BOUNDARY}px`;
this.rowsContainer.insertAdjacentElement('afterbegin', element);
this._webviewElement = new FastDomNode<HTMLElement>(element);
}
elementAt(position: number): ICellViewModel | undefined {
if (!this.view.length) {
return undefined;
}
const idx = this.view.indexAt(position);
const clamped = clamp(idx, 0, this.view.length - 1);
return this.element(clamped);
}
elementHeight(element: ICellViewModel): number {
const index = this._getViewIndexUpperBound(element);
if (index === undefined || index < 0 || index >= this.length) {
this._getViewIndexUpperBound(element);
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementHeight(index);
}
detachViewModel() {
this._viewModelStore.clear();
this._viewModel = null;
this.hiddenRangesPrefixSum = null;
}
attachViewModel(model: NotebookViewModel) {
this._viewModel = model;
this._viewModelStore.add(model.onDidChangeViewCells((e) => {
if (this._isDisposed) {
return;
}
const currentRanges = this._hiddenRangeIds.map(id => this._viewModel!.getTrackedRange(id)).filter(range => range !== null) as ICellRange[];
const newVisibleViewCells: CellViewModel[] = getVisibleCells(this._viewModel!.viewCells as CellViewModel[], currentRanges);
const oldVisibleViewCells: CellViewModel[] = [];
const oldViewCellMapping = new Set<string>();
for (let i = 0; i < this.length; i++) {
oldVisibleViewCells.push(this.element(i));
oldViewCellMapping.add(this.element(i).uri.toString());
}
const viewDiffs = diff<CellViewModel>(oldVisibleViewCells, newVisibleViewCells, a => {
return oldViewCellMapping.has(a.uri.toString());
});
if (e.synchronous) {
this._updateElementsInWebview(viewDiffs);
} else {
this._viewModelStore.add(DOM.scheduleAtNextAnimationFrame(() => {
if (this._isDisposed) {
return;
}
this._updateElementsInWebview(viewDiffs);
}));
}
}));
this._viewModelStore.add(model.onDidChangeSelection((e) => {
if (e === 'view') {
return;
}
// convert model selections to view selections
const viewSelections = cellRangesToIndexes(model.getSelections()).map(index => model.cellAt(index)).filter(cell => !!cell).map(cell => this._getViewIndexUpperBound(cell!));
this.setSelection(viewSelections, undefined, true);
const primary = cellRangesToIndexes([model.getFocus()]).map(index => model.cellAt(index)).filter(cell => !!cell).map(cell => this._getViewIndexUpperBound(cell!));
if (primary.length) {
this.setFocus(primary, undefined, true);
}
}));
const hiddenRanges = model.getHiddenRanges();
this.setHiddenAreas(hiddenRanges, false);
const newRanges = reduceCellRanges(hiddenRanges);
const viewCells = model.viewCells.slice(0) as CellViewModel[];
newRanges.reverse().forEach(range => {
const removedCells = viewCells.splice(range.start, range.end - range.start + 1);
this._onDidRemoveCellsFromView.fire(removedCells);
});
this.splice2(0, 0, viewCells);
}
private _updateElementsInWebview(viewDiffs: ISplice<CellViewModel>[]) {
viewDiffs.reverse().forEach((diff) => {
const hiddenOutputs: ICellOutputViewModel[] = [];
const deletedOutputs: ICellOutputViewModel[] = [];
const removedMarkdownCells: ICellViewModel[] = [];
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
const cell = this.element(i);
if (cell.cellKind === CellKind.Code) {
if (this._viewModel!.hasCell(cell)) {
hiddenOutputs.push(...cell?.outputsViewModels);
} else {
deletedOutputs.push(...cell?.outputsViewModels);
}
} else {
removedMarkdownCells.push(cell);
}
}
this.splice2(diff.start, diff.deleteCount, diff.toInsert);
this._onDidHideOutputs.fire(hiddenOutputs);
this._onDidRemoveOutputs.fire(deletedOutputs);
this._onDidRemoveCellsFromView.fire(removedMarkdownCells);
});
}
clear() {
super.splice(0, this.length);
}
setHiddenAreas(_ranges: ICellRange[], triggerViewUpdate: boolean): boolean {
if (!this._viewModel) {
return false;
}
const newRanges = reduceCellRanges(_ranges);
// delete old tracking ranges
const oldRanges = this._hiddenRangeIds.map(id => this._viewModel!.getTrackedRange(id)).filter(range => range !== null) as ICellRange[];
if (newRanges.length === oldRanges.length) {
let hasDifference = false;
for (let i = 0; i < newRanges.length; i++) {
if (!(newRanges[i].start === oldRanges[i].start && newRanges[i].end === oldRanges[i].end)) {
hasDifference = true;
break;
}
}
if (!hasDifference) {
// they call 'setHiddenAreas' for a reason, even if the ranges are still the same, it's possible that the hiddenRangeSum is not update to date
this._updateHiddenRangePrefixSum(newRanges);
return false;
}
}
this._hiddenRangeIds.forEach(id => this._viewModel!.setTrackedRange(id, null, TrackedRangeStickiness.GrowsOnlyWhenTypingAfter));
const hiddenAreaIds = newRanges.map(range => this._viewModel!.setTrackedRange(null, range, TrackedRangeStickiness.GrowsOnlyWhenTypingAfter)).filter(id => id !== null) as string[];
this._hiddenRangeIds = hiddenAreaIds;
// set hidden ranges prefix sum
this._updateHiddenRangePrefixSum(newRanges);
if (triggerViewUpdate) {
this.updateHiddenAreasInView(oldRanges, newRanges);
}
return true;
}
private _updateHiddenRangePrefixSum(newRanges: ICellRange[]) {
let start = 0;
let index = 0;
const ret: number[] = [];
while (index < newRanges.length) {
for (let j = start; j < newRanges[index].start - 1; j++) {
ret.push(1);
}
ret.push(newRanges[index].end - newRanges[index].start + 1 + 1);
start = newRanges[index].end + 1;
index++;
}
for (let i = start; i < this._viewModel!.length; i++) {
ret.push(1);
}
const values = new Uint32Array(ret.length);
for (let i = 0; i < ret.length; i++) {
values[i] = ret[i];
}
this.hiddenRangesPrefixSum = new PrefixSumComputer(values);
}
/**
* oldRanges and newRanges are all reduced and sorted.
*/
updateHiddenAreasInView(oldRanges: ICellRange[], newRanges: ICellRange[]) {
const oldViewCellEntries: CellViewModel[] = getVisibleCells(this._viewModel!.viewCells as CellViewModel[], oldRanges);
const oldViewCellMapping = new Set<string>();
oldViewCellEntries.forEach(cell => {
oldViewCellMapping.add(cell.uri.toString());
});
const newViewCellEntries: CellViewModel[] = getVisibleCells(this._viewModel!.viewCells as CellViewModel[], newRanges);
const viewDiffs = diff<CellViewModel>(oldViewCellEntries, newViewCellEntries, a => {
return oldViewCellMapping.has(a.uri.toString());
});
this._updateElementsInWebview(viewDiffs);
}
splice2(start: number, deleteCount: number, elements: readonly CellViewModel[] = []): void {
// we need to convert start and delete count based on hidden ranges
if (start < 0 || start > this.view.length) {
return;
}
const focusInside = DOM.isAncestor(document.activeElement, this.rowsContainer);
super.splice(start, deleteCount, elements);
if (focusInside) {
this.domFocus();
}
const selectionsLeft = [];
this.getSelectedElements().forEach(el => {
if (this._viewModel!.hasCell(el)) {
selectionsLeft.push(el.handle);
}
});
if (!selectionsLeft.length && this._viewModel!.viewCells.length) {
// after splice, the selected cells are deleted
this._viewModel!.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 0, end: 1 }, selections: [{ start: 0, end: 1 }] });
}
}
getModelIndex(cell: CellViewModel): number | undefined {
const viewIndex = this.indexOf(cell);
return this.getModelIndex2(viewIndex);
}
getModelIndex2(viewIndex: number): number | undefined {
if (!this.hiddenRangesPrefixSum) {
return viewIndex;
}
const modelIndex = this.hiddenRangesPrefixSum.getPrefixSum(viewIndex - 1);
return modelIndex;
}
getViewIndex(cell: ICellViewModel) {
const modelIndex = this._viewModel!.getCellIndex(cell);
return this.getViewIndex2(modelIndex);
}
getViewIndex2(modelIndex: number): number | undefined {
if (!this.hiddenRangesPrefixSum) {
return modelIndex;
}
const viewIndexInfo = this.hiddenRangesPrefixSum.getIndexOf(modelIndex);
if (viewIndexInfo.remainder !== 0) {
if (modelIndex >= this.hiddenRangesPrefixSum.getTotalSum()) {
// it's already after the last hidden range
return modelIndex - (this.hiddenRangesPrefixSum.getTotalSum() - this.hiddenRangesPrefixSum.getCount());
}
return undefined;
} else {
return viewIndexInfo.index;
}
}
private _getVisibleRangesFromIndex(topViewIndex: number, topModelIndex: number, bottomViewIndex: number, bottomModelIndex: number) {
const stack: number[] = [];
const ranges: ICellRange[] = [];
// there are hidden ranges
let index = topViewIndex;
let modelIndex = topModelIndex;
while (index <= bottomViewIndex) {
const accu = this.hiddenRangesPrefixSum!.getPrefixSum(index);
if (accu === modelIndex + 1) {
// no hidden area after it
if (stack.length) {
if (stack[stack.length - 1] === modelIndex - 1) {
ranges.push({ start: stack[stack.length - 1], end: modelIndex + 1 });
} else {
ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] + 1 });
}
}
stack.push(modelIndex);
index++;
modelIndex++;
} else {
// there are hidden ranges after it
if (stack.length) {
if (stack[stack.length - 1] === modelIndex - 1) {
ranges.push({ start: stack[stack.length - 1], end: modelIndex + 1 });
} else {
ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] + 1 });
}
}
stack.push(modelIndex);
index++;
modelIndex = accu;
}
}
if (stack.length) {
ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] + 1 });
}
return reduceCellRanges(ranges);
}
getVisibleRangesPlusViewportAboveAndBelow() {
if (this.view.length <= 0) {
return [];
}
const top = Math.max(this.getViewScrollTop() - this.renderHeight, 0);
const topViewIndex = this.view.indexAt(top);
const topElement = this.view.element(topViewIndex);
const topModelIndex = this._viewModel!.getCellIndex(topElement);
const bottom = clamp(this.getViewScrollBottom() + this.renderHeight, 0, this.scrollHeight);
const bottomViewIndex = clamp(this.view.indexAt(bottom), 0, this.view.length - 1);
const bottomElement = this.view.element(bottomViewIndex);
const bottomModelIndex = this._viewModel!.getCellIndex(bottomElement);
if (bottomModelIndex - topModelIndex === bottomViewIndex - topViewIndex) {
return [{ start: topModelIndex, end: bottomModelIndex }];
} else {
return this._getVisibleRangesFromIndex(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex);
}
}
private _getViewIndexUpperBound(cell: ICellViewModel): number {
if (!this._viewModel) {
return -1;
}
const modelIndex = this._viewModel.getCellIndex(cell);
if (modelIndex === -1) {
return -1;
}
if (!this.hiddenRangesPrefixSum) {
return modelIndex;
}
const viewIndexInfo = this.hiddenRangesPrefixSum.getIndexOf(modelIndex);
if (viewIndexInfo.remainder !== 0) {
if (modelIndex >= this.hiddenRangesPrefixSum.getTotalSum()) {
return modelIndex - (this.hiddenRangesPrefixSum.getTotalSum() - this.hiddenRangesPrefixSum.getCount());
}
}
return viewIndexInfo.index;
}
private _getViewIndexUpperBound2(modelIndex: number) {
if (!this.hiddenRangesPrefixSum) {
return modelIndex;
}
const viewIndexInfo = this.hiddenRangesPrefixSum.getIndexOf(modelIndex);
if (viewIndexInfo.remainder !== 0) {
if (modelIndex >= this.hiddenRangesPrefixSum.getTotalSum()) {
return modelIndex - (this.hiddenRangesPrefixSum.getTotalSum() - this.hiddenRangesPrefixSum.getCount());
}
}
return viewIndexInfo.index;
}
focusElement(cell: ICellViewModel) {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0 && this._viewModel) {
// update view model first, which will update both `focus` and `selection` in a single transaction
const focusedElementHandle = this.element(index).handle;
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: focusedElementHandle,
selections: [focusedElementHandle]
}, 'view');
// update the view as previous model update will not trigger event
this.setFocus([index], undefined, false);
}
}
selectElements(elements: ICellViewModel[]) {
const indices = elements.map(cell => this._getViewIndexUpperBound(cell)).filter(index => index >= 0);
this.setSelection(indices);
}
override setFocus(indexes: number[], browserEvent?: UIEvent, ignoreTextModelUpdate?: boolean): void {
if (ignoreTextModelUpdate) {
super.setFocus(indexes, browserEvent);
return;
}
if (!indexes.length) {
if (this._viewModel) {
if (this.length) {
// Don't allow clearing focus, #121129
return;
}
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: null,
selections: []
}, 'view');
}
} else {
if (this._viewModel) {
const focusedElementHandle = this.element(indexes[0]).handle;
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: focusedElementHandle,
selections: this.getSelection().map(selection => this.element(selection).handle)
}, 'view');
}
}
super.setFocus(indexes, browserEvent);
}
override setSelection(indexes: number[], browserEvent?: UIEvent | undefined, ignoreTextModelUpdate?: boolean) {
if (ignoreTextModelUpdate) {
super.setSelection(indexes, browserEvent);
return;
}
if (!indexes.length) {
if (this._viewModel) {
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: this.getFocusedElements()[0]?.handle ?? null,
selections: []
}, 'view');
}
} else {
if (this._viewModel) {
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: this.getFocusedElements()[0]?.handle ?? null,
selections: indexes.map(index => this.element(index)).map(cell => cell.handle)
}, 'view');
}
}
super.setSelection(indexes, browserEvent);
}
/**
* The range will be revealed with as little scrolling as possible.
*/
revealCellsInView(range: ICellRange) {
const startIndex = this._getViewIndexUpperBound2(range.start);
if (startIndex < 0) {
return;
}
const endIndex = this._getViewIndexUpperBound2(range.end - 1);
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(startIndex);
if (elementTop >= scrollTop
&& elementTop < wrapperBottom) {
// start element is visible
// check end
const endElementTop = this.view.elementTop(endIndex);
const endElementHeight = this.view.elementHeight(endIndex);
if (endElementTop + endElementHeight <= wrapperBottom) {
// fully visible
return;
}
if (endElementTop >= wrapperBottom) {
return this._revealInternal(endIndex, false, CellRevealPosition.Bottom);
}
if (endElementTop < wrapperBottom) {
// end element partially visible
if (endElementTop + endElementHeight - wrapperBottom < elementTop - scrollTop) {
// there is enough space to just scroll up a little bit to make the end element visible
return this.view.setScrollTop(scrollTop + endElementTop + endElementHeight - wrapperBottom);
} else {
// don't even try it
return this._revealInternal(startIndex, false, CellRevealPosition.Top);
}
}
}
this._revealInViewWithMinimalScrolling(startIndex);
}
private _revealInViewWithMinimalScrolling(viewIndex: number) {
const firstIndex = this.view.firstVisibleIndex;
if (viewIndex <= firstIndex) {
this._revealInternal(viewIndex, true, CellRevealPosition.Top);
} else {
this._revealInternal(viewIndex, true, CellRevealPosition.Bottom);
}
}
scrollToBottom() {
const scrollHeight = this.view.scrollHeight;
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const topInsertToolbarHeight = this._viewContext.notebookOptions.computeTopInsertToolbarHeight(this.viewModel?.viewType);
this.view.setScrollTop(scrollHeight - (wrapperBottom - scrollTop) - topInsertToolbarHeight);
}
//#region Reveal Cell synchronously
revealCell(cell: ICellViewModel, revealType: CellRevealSyncType) {
const index = this._getViewIndexUpperBound(cell);
if (index < 0) {
return;
}
switch (revealType) {
case CellRevealSyncType.Top:
this._revealInternal(index, false, CellRevealPosition.Top);
break;
case CellRevealSyncType.Center:
this._revealInternal(index, false, CellRevealPosition.Center);
break;
case CellRevealSyncType.CenterIfOutsideViewport:
this._revealInternal(index, true, CellRevealPosition.Center);
break;
case CellRevealSyncType.Default:
this._revealInViewWithMinimalScrolling(index);
break;
}
}
private _revealInternal(viewIndex: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
if (viewIndex >= this.view.length) {
return;
}
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(viewIndex);
const elementBottom = this.view.elementHeight(viewIndex) + elementTop;
if (ignoreIfInsideViewport
&& elementTop >= scrollTop
&& elementBottom < wrapperBottom) {
if (revealPosition === CellRevealPosition.Center
&& elementBottom > wrapperBottom
&& elementTop > (scrollTop + wrapperBottom) / 2) {
// the element is partially visible and it's below the center of the viewport
} else {
return;
}
}
switch (revealPosition) {
case CellRevealPosition.Top:
this.view.setScrollTop(elementTop);
this.view.setScrollTop(this.view.elementTop(viewIndex));
break;
case CellRevealPosition.Center:
case CellRevealPosition.NearTop:
{
// reveal the cell top in the viewport center initially
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// cell rendered already, we now have a more accurate cell height
const newElementTop = this.view.elementTop(viewIndex);
const newElementHeight = this.view.elementHeight(viewIndex);
const renderHeight = this.getViewScrollBottom() - this.getViewScrollTop();
if (newElementHeight >= renderHeight) {
// cell is larger than viewport, reveal top
this.view.setScrollTop(newElementTop);
} else if (revealPosition === CellRevealPosition.Center) {
this.view.setScrollTop(newElementTop + (newElementHeight / 2) - (renderHeight / 2));
} else if (revealPosition === CellRevealPosition.NearTop) {
this.view.setScrollTop(newElementTop - (renderHeight / 5));
}
}
break;
case CellRevealPosition.Bottom:
this.view.setScrollTop(this.scrollTop + (elementBottom - wrapperBottom));
this.view.setScrollTop(this.scrollTop + (this.view.elementTop(viewIndex) + this.view.elementHeight(viewIndex) - this.getViewScrollBottom()));
break;
default:
break;
}
}
//#endregion
//#region Reveal Cell asynchronously
async revealCellAsync(cell: ICellViewModel, revealType: CellRevealType) {
const viewIndex = this._getViewIndexUpperBound(cell);
if (viewIndex < 0) {
return;
}
const revealPosition = revealType === CellRevealType.NearTopIfOutsideViewport ? CellRevealPosition.NearTop : CellRevealPosition.Center;
this._revealInternal(viewIndex, true, revealPosition);
// wait for the editor to be created only if the cell is in editing mode (meaning it has an editor and will focus the editor)
if (cell.getEditState() === CellEditState.Editing && !cell.editorAttached) {
return getEditorAttachedPromise(cell);
}
return;
}
//#endregion
//#region Reveal Cell Editor Range asynchronously
async revealCellRangeAsync(cell: ICellViewModel, range: Selection | Range, revealType: CellRevealRangeType): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index < 0) {
return;
}
switch (revealType) {
case CellRevealRangeType.Default:
return this._revealRangeInternalAsync(index, range, CellEditorRevealType.Range);
case CellRevealRangeType.Center:
return this._revealRangeInCenterInternalAsync(index, range, CellEditorRevealType.Range);
case CellRevealRangeType.CenterIfOutsideViewport:
return this._revealRangeInCenterIfOutsideViewportInternalAsync(index, range, CellEditorRevealType.Range);
}
}
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private async _revealRangeInternalAsync(viewIndex: number, range: Selection | Range, revealType: CellEditorRevealType): Promise<void> {
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(viewIndex);
const element = this.view.element(viewIndex);
if (element.editorAttached) {
this._revealRangeCommon(viewIndex, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(viewIndex);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise<void>((resolve, reject) => {
element.onDidChangeEditorAttachState(() => {
element.editorAttached ? resolve() : reject();
});
});
return editorAttachedPromise.then(() => {
this._revealRangeCommon(viewIndex, range, revealType, true, upwards);
});
}
}
private async _revealRangeInCenterInternalAsync(viewIndex: number, range: Selection | Range, revealType: CellEditorRevealType): Promise<void> {
const reveal = (viewIndex: number, range: Range, revealType: CellEditorRevealType) => {
const element = this.view.element(viewIndex);
const positionOffset = element.getPositionScrollTopOffset(range);
const positionOffsetInView = this.view.elementTop(viewIndex) + positionOffset;
this.view.setScrollTop(positionOffsetInView - this.view.renderHeight / 2);
if (revealType === CellEditorRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(viewIndex);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(viewIndex);
if (!element.editorAttached) {
return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range, revealType));
} else {
reveal(viewIndex, range, revealType);
}
}
private async _revealRangeInCenterIfOutsideViewportInternalAsync(viewIndex: number, range: Selection | Range, revealType: CellEditorRevealType): Promise<void> {
const reveal = (viewIndex: number, range: Range, revealType: CellEditorRevealType) => {
const element = this.view.element(viewIndex);
const positionOffset = element.getPositionScrollTopOffset(range);
const positionOffsetInView = this.view.elementTop(viewIndex) + positionOffset;
this.view.setScrollTop(positionOffsetInView - this.view.renderHeight / 2);
if (revealType === CellEditorRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(viewIndex);
const viewItemOffset = elementTop;
const element = this.view.element(viewIndex);
const positionOffset = viewItemOffset + element.getPositionScrollTopOffset(range);
if (positionOffset < scrollTop || positionOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(positionOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const newPositionOffset = this.view.elementTop(viewIndex) + element.getPositionScrollTopOffset(range);
this.view.setScrollTop(newPositionOffset - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range, revealType));
}
}
}
private _revealRangeCommon(viewIndex: number, range: Selection | Range, revealType: CellEditorRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(viewIndex);
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const positionOffset = element.getPositionScrollTopOffset(range);
const elementOriginalHeight = this.view.elementHeight(viewIndex);
if (positionOffset >= elementOriginalHeight) {
// we are revealing a range that is beyond current element height
// if we don't update the element height now, and directly `setTop` to reveal the range
// the element might be scrolled out of view
// next frame, when we update the element height, the element will never be scrolled back into view
const newTotalHeight = element.layoutInfo.totalHeight;
this.updateElementHeight(viewIndex, newTotalHeight);
}
const elementTop = this.view.elementTop(viewIndex);
const positionTop = elementTop + positionOffset;
// TODO@rebornix 30 ---> line height * 1.5
if (positionTop < scrollTop) {
this.view.setScrollTop(positionTop - 30);
} else if (positionTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + positionTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + positionTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(positionTop - 30);
}
}
if (revealType === CellEditorRevealType.Range) {
element.revealRangeInCenter(range);
}
}
//#endregion
//#region Reveal Cell offset
async revealCellOffsetInCenterAsync(cell: ICellViewModel, offset: number): Promise<void> {
const viewIndex = this._getViewIndexUpperBound(cell);
if (viewIndex >= 0) {
const element = this.view.element(viewIndex);
const elementTop = this.view.elementTop(viewIndex);
if (element instanceof MarkupCellViewModel) {
return this._revealInCenterIfOutsideViewport(viewIndex);
} else {
const rangeOffset = element.layoutInfo.outputContainerOffset + Math.min(offset, element.layoutInfo.outputTotalHeight);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(elementTop + rangeOffset - this.view.renderHeight / 2);
}
}
}
private _revealInCenterIfOutsideViewport(viewIndex: number) {
this._revealInternal(viewIndex, true, CellRevealPosition.Center);
}
//#endregion
domElementOfElement(element: ICellViewModel): HTMLElement | null {
const index = this._getViewIndexUpperBound(element);
if (index >= 0) {
return this.view.domElement(index);
}
return null;
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTopOfElement(element: ICellViewModel): number {
const index = this._getViewIndexUpperBound(element);
if (index === undefined || index < 0 || index >= this.length) {
this._getViewIndexUpperBound(element);
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.delegateScrollFromMouseWheelEvent(browserEvent);
}
delegateVerticalScrollbarPointerDown(browserEvent: PointerEvent) {
this.view.delegateVerticalScrollbarPointerDown(browserEvent);
}
private isElementAboveViewport(index: number) {
const elementTop = this.view.elementTop(index);
const elementBottom = elementTop + this.view.elementHeight(index);
return elementBottom < this.scrollTop;
}
updateElementHeight2(element: ICellViewModel, size: number, anchorElementIndex: number | null = null): void {
const index = this._getViewIndexUpperBound(element);
if (index === undefined || index < 0 || index >= this.length) {
return;
}
if (this.isElementAboveViewport(index)) {
// update element above viewport
const oldHeight = this.elementHeight(element);
const delta = oldHeight - size;
if (this._webviewElement) {
Event.once(this.view.onWillScroll)(() => {
const webviewTop = parseInt(this._webviewElement!.domNode.style.top, 10);
if (validateWebviewBoundary(this._webviewElement!.domNode)) {
this._webviewElement!.setTop(webviewTop - delta);
} else {
// When the webview top boundary is below the list view scrollable element top boundary, then we can't insert a markdown cell at the top
// or when its bottom boundary is above the list view bottom boundary, then we can't insert a markdown cell at the end
// thus we have to revert the webview element position to initial state `-NOTEBOOK_WEBVIEW_BOUNDARY`.
// this will trigger one visual flicker (as we need to update element offsets in the webview)
// but as long as NOTEBOOK_WEBVIEW_BOUNDARY is large enough, it will happen less often
this._webviewElement!.setTop(-NOTEBOOK_WEBVIEW_BOUNDARY);
}
});
}
this.view.updateElementHeight(index, size, anchorElementIndex);
return;
}
if (anchorElementIndex !== null) {
return this.view.updateElementHeight(index, size, anchorElementIndex);
}
const focused = this.getFocus();
if (!focused.length) {
return this.view.updateElementHeight(index, size, null);
}
const focus = focused[0];
if (focus <= index) {
return this.view.updateElementHeight(index, size, focus);
}
// the `element` is in the viewport, it's very often that the height update is triggerred by user interaction (collapse, run cell)
// then we should make sure that the `element`'s visual view position doesn't change.
if (this.view.elementTop(index) >= this.view.getScrollTop()) {
return this.view.updateElementHeight(index, size, index);
}
this.view.updateElementHeight(index, size, focus);
}
// override
override domFocus() {
const focused = this.getFocusedElements()[0];
const focusedDomElement = focused && this.domElementOfElement(focused);
if (document.activeElement && focusedDomElement && focusedDomElement.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
focusContainer() {
super.domFocus();
}
getViewScrollTop() {
return this.view.getScrollTop();
}
getViewScrollBottom() {
const topInsertToolbarHeight = this._viewContext.notebookOptions.computeTopInsertToolbarHeight(this.viewModel?.viewType);
return this.getViewScrollTop() + this.view.renderHeight - topInsertToolbarHeight;
}
setCellEditorSelection(cell: ICellViewModel, range: Range) {
const element = cell as CellViewModel;
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
override style(styles: IListStyles) {
const selectorSuffix = this.view.domId;
if (!this.styleElement) {
this.styleElement = DOM.createStyleSheet(this.view.domNode);
}
const suffix = selectorSuffix && `.${selectorSuffix}`;
const content: string[] = [];
if (styles.listBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows { background: ${styles.listBackground}; }`);
}
if (styles.listFocusBackground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listFocusForeground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
}
if (styles.listActiveSelectionBackground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listActiveSelectionForeground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
}
if (styles.listFocusAndSelectionBackground) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
`);
}
if (styles.listFocusAndSelectionForeground) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
`);
}
if (styles.listInactiveFocusBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`);
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`);
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionForeground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
}
if (styles.listHoverBackground) {
content.push(`.monaco-list${suffix}:not(.drop-target) > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
}
if (styles.listHoverForeground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`);
}
if (styles.listSelectionOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
}
if (styles.listFocusOutline) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
`);
}
if (styles.listInactiveFocusOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
}
if (styles.listHoverOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
}
if (styles.listDropBackground) {
content.push(`
.monaco-list${suffix}.drop-target,
.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows.drop-target,
.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; }
`);
}
const newStyles = content.join('\n');
if (newStyles !== this.styleElement.textContent) {
this.styleElement.textContent = newStyles;
}
}
getRenderHeight() {
return this.view.renderHeight;
}
getScrollHeight() {
return this.view.scrollHeight;
}
override layout(height?: number, width?: number): void {
this._isInLayout = true;
super.layout(height, width);
if (this.renderHeight === 0) {
this.view.domNode.style.visibility = 'hidden';
} else {
this.view.domNode.style.visibility = 'initial';
}
this._isInLayout = false;
}
override dispose() {
this._isDisposed = true;
this._viewModelStore.dispose();
this._localDisposableStore.dispose();
super.dispose();
// un-ref
this._previousFocusedElements = [];
this._viewModel = null;
this._hiddenRangeIds = [];
this.hiddenRangesPrefixSum = null;
this._visibleRanges = [];
}
}
export class ListViewInfoAccessor extends Disposable {
constructor(
readonly list: INotebookCellList
) {
super();
}
getViewIndex(cell: ICellViewModel): number {
return this.list.getViewIndex(cell) ?? -1;
}
getViewHeight(cell: ICellViewModel): number {
if (!this.list.viewModel) {
return -1;
}
return this.list.elementHeight(cell);
}
getCellRangeFromViewRange(startIndex: number, endIndex: number): ICellRange | undefined {
if (!this.list.viewModel) {
return undefined;
}
const modelIndex = this.list.getModelIndex2(startIndex);
if (modelIndex === undefined) {
throw new Error(`startIndex ${startIndex} out of boundary`);
}
if (endIndex >= this.list.length) {
// it's the end
const endModelIndex = this.list.viewModel.length;
return { start: modelIndex, end: endModelIndex };
} else {
const endModelIndex = this.list.getModelIndex2(endIndex);
if (endModelIndex === undefined) {
throw new Error(`endIndex ${endIndex} out of boundary`);
}
return { start: modelIndex, end: endModelIndex };
}
}
getCellsFromViewRange(startIndex: number, endIndex: number): ReadonlyArray<ICellViewModel> {
if (!this.list.viewModel) {
return [];
}
const range = this.getCellRangeFromViewRange(startIndex, endIndex);
if (!range) {
return [];
}
return this.list.viewModel.getCellsInRange(range);
}
getCellsInRange(range?: ICellRange): ReadonlyArray<ICellViewModel> {
return this.list.viewModel?.getCellsInRange(range) ?? [];
}
getVisibleRangesPlusViewportAboveAndBelow(): ICellRange[] {
return this.list?.getVisibleRangesPlusViewportAboveAndBelow() ?? [];
}
}
function getEditorAttachedPromise(element: ICellViewModel) {
return new Promise<void>((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(() => element.editorAttached ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00019950738351326436,
0.00017000679508782923,
0.00016504860832355917,
0.00016980574582703412,
0.000003384295041541918
] |
{
"id": 6,
"code_window": [
"}\n",
"\n",
"pub enum ShutdownRequest {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tDerived(Box<dyn Receivable<ShutdownSignal> + Send>),\n",
"}\n",
"\n",
"impl ShutdownRequest {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled(PathBuf),\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 43
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
| extensions/python/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00016995567420963198,
0.00016995567420963198,
0.00016995567420963198,
0.00016995567420963198,
0
] |
{
"id": 6,
"code_window": [
"}\n",
"\n",
"pub enum ShutdownRequest {\n",
"\tCtrlC,\n",
"\tParentProcessKilled(Pid),\n",
"\tDerived(Box<dyn Receivable<ShutdownSignal> + Send>),\n",
"}\n",
"\n",
"impl ShutdownRequest {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tExeUninstalled(PathBuf),\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 43
} | /*---------------------------------------------------------------------------------------------
* 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 { toResource } from 'vs/base/test/common/utils';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { workbenchInstantiationService, TestServiceAccessor, registerTestFileEditor, createEditorPart, TestTextFileEditor } from 'vs/workbench/test/browser/workbenchTestServices';
import { IResolvedTextFileEditorModel } from 'vs/workbench/services/textfile/common/textfiles';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { EditorService } from 'vs/workbench/services/editor/browser/editorService';
import { EditorPaneSelectionChangeReason, EditorPaneSelectionCompareResult, IEditorPaneSelectionChangeEvent, isEditorPaneWithSelection } from 'vs/workbench/common/editor';
import { DeferredPromise } from 'vs/base/common/async';
import { TextEditorPaneSelection } from 'vs/workbench/browser/parts/editor/textEditor';
import { Selection } from 'vs/editor/common/core/selection';
import { IEditorOptions } from 'vs/platform/editor/common/editor';
suite('TextEditorPane', () => {
const disposables = new DisposableStore();
setup(() => {
disposables.add(registerTestFileEditor());
});
teardown(() => {
disposables.clear();
});
async function createServices(): Promise<TestServiceAccessor> {
const instantiationService = workbenchInstantiationService(undefined, disposables);
const part = await createEditorPart(instantiationService, disposables);
instantiationService.stub(IEditorGroupsService, part);
const editorService = instantiationService.createInstance(EditorService);
instantiationService.stub(IEditorService, editorService);
return instantiationService.createInstance(TestServiceAccessor);
}
test('editor pane selection', async function () {
const accessor = await createServices();
const resource = toResource.call(this, '/path/index.txt');
let pane = (await accessor.editorService.openEditor({ resource }) as TestTextFileEditor);
assert.ok(pane && isEditorPaneWithSelection(pane));
const onDidFireSelectionEventOfEditType = new DeferredPromise<IEditorPaneSelectionChangeEvent>();
pane.onDidChangeSelection(e => {
if (e.reason === EditorPaneSelectionChangeReason.EDIT) {
onDidFireSelectionEventOfEditType.complete(e);
}
});
// Changing model reports selection change
// of EDIT kind
const model = await accessor.textFileService.files.resolve(resource) as IResolvedTextFileEditorModel;
model.textEditorModel.setValue('Hello World');
const event = await onDidFireSelectionEventOfEditType.p;
assert.strictEqual(event.reason, EditorPaneSelectionChangeReason.EDIT);
// getSelection() works and can be restored
//
// Note: this is a bit bogus because in tests our code editors have
// no view and no cursor can be set as such. So the selection
// will always report for the first line and column.
pane.setSelection(new Selection(1, 1, 1, 1), EditorPaneSelectionChangeReason.USER);
const selection = pane.getSelection();
assert.ok(selection);
await pane.group?.closeAllEditors();
const options = selection.restore({});
pane = (await accessor.editorService.openEditor({ resource, options }) as TestTextFileEditor);
assert.ok(pane && isEditorPaneWithSelection(pane));
const newSelection = pane.getSelection();
assert.ok(newSelection);
assert.strictEqual(newSelection.compare(selection), EditorPaneSelectionCompareResult.IDENTICAL);
});
test('TextEditorPaneSelection', function () {
const sel1 = new TextEditorPaneSelection(new Selection(1, 1, 2, 2));
const sel2 = new TextEditorPaneSelection(new Selection(5, 5, 6, 6));
const sel3 = new TextEditorPaneSelection(new Selection(50, 50, 60, 60));
const sel4 = { compare: () => { throw new Error(); }, restore: (options: IEditorOptions) => options };
assert.strictEqual(sel1.compare(sel1), EditorPaneSelectionCompareResult.IDENTICAL);
assert.strictEqual(sel1.compare(sel2), EditorPaneSelectionCompareResult.SIMILAR);
assert.strictEqual(sel1.compare(sel3), EditorPaneSelectionCompareResult.DIFFERENT);
assert.strictEqual(sel1.compare(sel4), EditorPaneSelectionCompareResult.DIFFERENT);
});
});
| src/vs/workbench/test/browser/parts/editor/textEditorPane.test.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017500578542239964,
0.00017243735783267766,
0.00016957332263700664,
0.00017246970674023032,
0.0000019314172732265433
] |
{
"id": 7,
"code_window": [
"\t\t\tShutdownRequest::ParentProcessKilled(pid) => {\n",
"\t\t\t\twait_until_process_exits(pid, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ParentProcessKilled(pid))\n",
"\t\t\t}\n",
"\t\t\tShutdownRequest::Derived(mut rx) => rx.recv_msg().await,\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownRequest::ExeUninstalled(exe_path) => {\n",
"\t\t\t\twait_until_exe_deleted(&exe_path, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ExeUninstalled)\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.9974126219749451,
0.11349502205848694,
0.0001747759961290285,
0.002641144208610058,
0.31252437829971313
] |
{
"id": 7,
"code_window": [
"\t\t\tShutdownRequest::ParentProcessKilled(pid) => {\n",
"\t\t\t\twait_until_process_exits(pid, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ParentProcessKilled(pid))\n",
"\t\t\t}\n",
"\t\t\tShutdownRequest::Derived(mut rx) => rx.recv_msg().await,\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownRequest::ExeUninstalled(exe_path) => {\n",
"\t\t\t\twait_until_exe_deleted(&exe_path, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ExeUninstalled)\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { assertIsDefined } from 'vs/base/common/types';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProgressIndicator } from 'vs/platform/progress/common/progress';
import { PaneCompositeDescriptor } from 'vs/workbench/browser/panecomposite';
import { ActivitybarPart } from 'vs/workbench/browser/parts/activitybar/activitybarPart';
import { AuxiliaryBarPart } from 'vs/workbench/browser/parts/auxiliarybar/auxiliaryBarPart';
import { PanelPart } from 'vs/workbench/browser/parts/panel/panelPart';
import { SidebarPart } from 'vs/workbench/browser/parts/sidebar/sidebarPart';
import { IPaneComposite } from 'vs/workbench/common/panecomposite';
import { ViewContainerLocation, ViewContainerLocations } from 'vs/workbench/common/views';
import { IBadge } from 'vs/workbench/services/activity/common/activity';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { IView } from 'vs/base/browser/ui/grid/grid';
export interface IPaneCompositePart extends IView {
readonly onDidPaneCompositeOpen: Event<IPaneComposite>;
readonly onDidPaneCompositeClose: Event<IPaneComposite>;
/**
* Opens a viewlet with the given identifier and pass keyboard focus to it if specified.
*/
openPaneComposite(id: string | undefined, focus?: boolean): Promise<IPaneComposite | undefined>;
/**
* Returns the current active viewlet if any.
*/
getActivePaneComposite(): IPaneComposite | undefined;
/**
* Returns the viewlet by id.
*/
getPaneComposite(id: string): PaneCompositeDescriptor | undefined;
/**
* Returns all enabled viewlets
*/
getPaneComposites(): PaneCompositeDescriptor[];
/**
* Returns the progress indicator for the side bar.
*/
getProgressIndicator(id: string): IProgressIndicator | undefined;
/**
* Hide the active viewlet.
*/
hideActivePaneComposite(): void;
/**
* Return the last active viewlet id.
*/
getLastActivePaneCompositeId(): string;
}
export interface IPaneCompositeSelectorPart {
/**
* Returns id of pinned view containers following the visual order.
*/
getPinnedPaneCompositeIds(): string[];
/**
* Returns id of visible view containers following the visual order.
*/
getVisiblePaneCompositeIds(): string[];
/**
* Show an activity in a viewlet.
*/
showActivity(id: string, badge: IBadge, clazz?: string, priority?: number): IDisposable;
}
export class PaneCompositeParts extends Disposable implements IPaneCompositePartService {
declare readonly _serviceBrand: undefined;
readonly onDidPaneCompositeOpen: Event<{ composite: IPaneComposite; viewContainerLocation: ViewContainerLocation }>;
readonly onDidPaneCompositeClose: Event<{ composite: IPaneComposite; viewContainerLocation: ViewContainerLocation }>;
private readonly paneCompositeParts = new Map<ViewContainerLocation, IPaneCompositePart>();
private readonly paneCompositeSelectorParts = new Map<ViewContainerLocation, IPaneCompositeSelectorPart>();
constructor(@IInstantiationService instantiationService: IInstantiationService) {
super();
const panelPart = instantiationService.createInstance(PanelPart);
const sideBarPart = instantiationService.createInstance(SidebarPart);
const auxiliaryBarPart = instantiationService.createInstance(AuxiliaryBarPart);
const activityBarPart = instantiationService.createInstance(ActivitybarPart, sideBarPart);
this.paneCompositeParts.set(ViewContainerLocation.Panel, panelPart);
this.paneCompositeParts.set(ViewContainerLocation.Sidebar, sideBarPart);
this.paneCompositeParts.set(ViewContainerLocation.AuxiliaryBar, auxiliaryBarPart);
this.paneCompositeSelectorParts.set(ViewContainerLocation.Panel, panelPart);
this.paneCompositeSelectorParts.set(ViewContainerLocation.Sidebar, activityBarPart);
this.paneCompositeSelectorParts.set(ViewContainerLocation.AuxiliaryBar, auxiliaryBarPart);
const eventDisposables = this._register(new DisposableStore());
this.onDidPaneCompositeOpen = Event.any(...ViewContainerLocations.map(loc => Event.map(this.paneCompositeParts.get(loc)!.onDidPaneCompositeOpen, composite => { return { composite, viewContainerLocation: loc }; }, eventDisposables)));
this.onDidPaneCompositeClose = Event.any(...ViewContainerLocations.map(loc => Event.map(this.paneCompositeParts.get(loc)!.onDidPaneCompositeClose, composite => { return { composite, viewContainerLocation: loc }; }, eventDisposables)));
}
openPaneComposite(id: string | undefined, viewContainerLocation: ViewContainerLocation, focus?: boolean): Promise<IPaneComposite | undefined> {
return this.getPartByLocation(viewContainerLocation).openPaneComposite(id, focus);
}
getActivePaneComposite(viewContainerLocation: ViewContainerLocation): IPaneComposite | undefined {
return this.getPartByLocation(viewContainerLocation).getActivePaneComposite();
}
getPaneComposite(id: string, viewContainerLocation: ViewContainerLocation): PaneCompositeDescriptor | undefined {
return this.getPartByLocation(viewContainerLocation).getPaneComposite(id);
}
getPaneComposites(viewContainerLocation: ViewContainerLocation): PaneCompositeDescriptor[] {
return this.getPartByLocation(viewContainerLocation).getPaneComposites();
}
getPinnedPaneCompositeIds(viewContainerLocation: ViewContainerLocation): string[] {
return this.getSelectorPartByLocation(viewContainerLocation).getPinnedPaneCompositeIds();
}
getVisiblePaneCompositeIds(viewContainerLocation: ViewContainerLocation): string[] {
return this.getSelectorPartByLocation(viewContainerLocation).getVisiblePaneCompositeIds();
}
getProgressIndicator(id: string, viewContainerLocation: ViewContainerLocation): IProgressIndicator | undefined {
return this.getPartByLocation(viewContainerLocation).getProgressIndicator(id);
}
hideActivePaneComposite(viewContainerLocation: ViewContainerLocation): void {
this.getPartByLocation(viewContainerLocation).hideActivePaneComposite();
}
getLastActivePaneCompositeId(viewContainerLocation: ViewContainerLocation): string {
return this.getPartByLocation(viewContainerLocation).getLastActivePaneCompositeId();
}
showActivity(id: string, viewContainerLocation: ViewContainerLocation, badge: IBadge, clazz?: string, priority?: number): IDisposable {
return this.getSelectorPartByLocation(viewContainerLocation).showActivity(id, badge, clazz, priority);
}
private getPartByLocation(viewContainerLocation: ViewContainerLocation): IPaneCompositePart {
return assertIsDefined(this.paneCompositeParts.get(viewContainerLocation));
}
private getSelectorPartByLocation(viewContainerLocation: ViewContainerLocation): IPaneCompositeSelectorPart {
return assertIsDefined(this.paneCompositeSelectorParts.get(viewContainerLocation));
}
}
registerSingleton(IPaneCompositePartService, PaneCompositeParts, InstantiationType.Delayed);
| src/vs/workbench/browser/parts/paneCompositePart.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00018096560961566865,
0.00017324101645499468,
0.0001651836937526241,
0.00017395666509401053,
0.000004514539796218742
] |
{
"id": 7,
"code_window": [
"\t\t\tShutdownRequest::ParentProcessKilled(pid) => {\n",
"\t\t\t\twait_until_process_exits(pid, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ParentProcessKilled(pid))\n",
"\t\t\t}\n",
"\t\t\tShutdownRequest::Derived(mut rx) => rx.recv_msg().await,\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownRequest::ExeUninstalled(exe_path) => {\n",
"\t\t\t\twait_until_exe_deleted(&exe_path, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ExeUninstalled)\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { GestureEvent } from 'vs/base/browser/touch';
import { Emitter, Event as BaseEvent } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
export type EventHandler = HTMLElement | HTMLDocument | Window;
export interface IDomEvent {
<K extends keyof HTMLElementEventMap>(element: EventHandler, type: K, useCapture?: boolean): BaseEvent<HTMLElementEventMap[K]>;
(element: EventHandler, type: string, useCapture?: boolean): BaseEvent<unknown>;
}
export interface DOMEventMap extends HTMLElementEventMap, DocumentEventMap, WindowEventMap {
'-monaco-gesturetap': GestureEvent;
'-monaco-gesturechange': GestureEvent;
'-monaco-gesturestart': GestureEvent;
'-monaco-gesturesend': GestureEvent;
'-monaco-gesturecontextmenu': GestureEvent;
'compositionstart': CompositionEvent;
'compositionupdate': CompositionEvent;
'compositionend': CompositionEvent;
}
export class DomEmitter<K extends keyof DOMEventMap> implements IDisposable {
private emitter: Emitter<DOMEventMap[K]>;
get event(): BaseEvent<DOMEventMap[K]> {
return this.emitter.event;
}
constructor(element: Window & typeof globalThis, type: WindowEventMap, useCapture?: boolean);
constructor(element: Document, type: DocumentEventMap, useCapture?: boolean);
constructor(element: EventHandler, type: K, useCapture?: boolean);
constructor(element: EventHandler, type: K, useCapture?: boolean) {
const fn = (e: Event) => this.emitter.fire(e as DOMEventMap[K]);
this.emitter = new Emitter({
onWillAddFirstListener: () => element.addEventListener(type, fn, useCapture),
onDidRemoveLastListener: () => element.removeEventListener(type, fn, useCapture)
});
}
dispose(): void {
this.emitter.dispose();
}
}
| src/vs/base/browser/event.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001801647013053298,
0.00017508761084172875,
0.00017067250155378133,
0.0001760074810590595,
0.0000033776077543734573
] |
{
"id": 7,
"code_window": [
"\t\t\tShutdownRequest::ParentProcessKilled(pid) => {\n",
"\t\t\t\twait_until_process_exits(pid, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ParentProcessKilled(pid))\n",
"\t\t\t}\n",
"\t\t\tShutdownRequest::Derived(mut rx) => rx.recv_msg().await,\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tShutdownRequest::ExeUninstalled(exe_path) => {\n",
"\t\t\t\twait_until_exe_deleted(&exe_path, 2000).await;\n",
"\t\t\t\tSome(ShutdownSignal::ExeUninstalled)\n",
"\t\t\t}\n"
],
"file_path": "cli/src/tunnels/shutdown_signal.rs",
"type": "add",
"edit_start_line_idx": 58
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
Connection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind, NotificationType, Disposable, TextDocumentIdentifier, Range, FormattingOptions, TextEdit, Diagnostic
} from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, TextDocument, Position } from 'vscode-css-languageservice';
import { getLanguageModelCache } from './languageModelCache';
import { runSafeAsync } from './utils/runner';
import { DiagnosticsSupport, registerDiagnosticsPullSupport, registerDiagnosticsPushSupport } from './utils/validation';
import { getDocumentContext } from './utils/documentContext';
import { fetchDataProviders } from './customData';
import { RequestService, getRequestService } from './requests';
namespace CustomDataChangedNotification {
export const type: NotificationType<string[]> = new NotificationType('css/customDataChanged');
}
export interface Settings {
css: LanguageSettings;
less: LanguageSettings;
scss: LanguageSettings;
}
export interface RuntimeEnvironment {
readonly file?: RequestService;
readonly http?: RequestService;
readonly timer: {
setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable;
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable;
};
}
export function startServer(connection: Connection, runtime: RuntimeEnvironment) {
// Create a text document manager.
const documents = new TextDocuments(TextDocument);
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
documents.onDidClose(e => {
stylesheets.onDocumentRemoved(e.document);
});
connection.onShutdown(() => {
stylesheets.dispose();
});
let scopedSettingsSupport = false;
let foldingRangeLimit = Number.MAX_VALUE;
let workspaceFolders: WorkspaceFolder[];
let formatterMaxNumberOfEdits = Number.MAX_VALUE;
let dataProvidersReady: Promise<any> = Promise.resolve();
let diagnosticsSupport: DiagnosticsSupport | undefined;
const languageServices: { [id: string]: LanguageService } = {};
const notReady = () => Promise.reject('Not Ready');
let requestService: RequestService = { getContent: notReady, stat: notReady, readDirectory: notReady };
// After the server has started the client sends an initialize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilities.
connection.onInitialize((params: InitializeParams): InitializeResult => {
const initializationOptions = params.initializationOptions as any || {};
workspaceFolders = (<any>params).workspaceFolders;
if (!Array.isArray(workspaceFolders)) {
workspaceFolders = [];
if (params.rootPath) {
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString(true) });
}
}
requestService = getRequestService(initializationOptions?.handledSchemas || ['file'], connection, runtime);
function getClientCapability<T>(name: string, def: T) {
const keys = name.split('.');
let c: any = params.capabilities;
for (let i = 0; c && i < keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
return def;
}
c = c[keys[i]];
}
return c;
}
const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
formatterMaxNumberOfEdits = initializationOptions?.customCapabilities?.rangeFormatting?.editLimit || Number.MAX_VALUE;
languageServices.css = getCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
languageServices.scss = getSCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
languageServices.less = getLESSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
const supportsDiagnosticPull = getClientCapability('textDocument.diagnostic', undefined);
if (supportsDiagnosticPull === undefined) {
diagnosticsSupport = registerDiagnosticsPushSupport(documents, connection, runtime, validateTextDocument);
} else {
diagnosticsSupport = registerDiagnosticsPullSupport(documents, connection, runtime, validateTextDocument);
}
const capabilities: ServerCapabilities = {
textDocumentSync: TextDocumentSyncKind.Incremental,
completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-', ':'] } : undefined,
hoverProvider: true,
documentSymbolProvider: true,
referencesProvider: true,
definitionProvider: true,
documentHighlightProvider: true,
documentLinkProvider: {
resolveProvider: false
},
codeActionProvider: true,
renameProvider: true,
colorProvider: {},
foldingRangeProvider: true,
selectionRangeProvider: true,
diagnosticProvider: {
documentSelector: null,
interFileDependencies: false,
workspaceDiagnostics: false
},
documentRangeFormattingProvider: initializationOptions?.provideFormatter === true,
documentFormattingProvider: initializationOptions?.provideFormatter === true,
};
return { capabilities };
});
function getLanguageService(document: TextDocument) {
let service = languageServices[document.languageId];
if (!service) {
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
service = languageServices['css'];
}
return service;
}
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
// remove document settings on close
documents.onDidClose(e => {
delete documentSettings[e.document.uri];
});
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
if (scopedSettingsSupport) {
let promise = documentSettings[textDocument.uri];
if (!promise) {
const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0] as LanguageSettings | undefined);
documentSettings[textDocument.uri] = promise;
}
return promise;
}
return Promise.resolve(undefined);
}
// The settings have changed. Is send on server activation as well.
connection.onDidChangeConfiguration(change => {
updateConfiguration(change.settings as any);
});
function updateConfiguration(settings: any) {
for (const languageId in languageServices) {
languageServices[languageId].configure(settings[languageId]);
}
// reset all document settings
documentSettings = {};
diagnosticsSupport?.requestRefresh();
}
async function validateTextDocument(textDocument: TextDocument): Promise<Diagnostic[]> {
const settingsPromise = getDocumentSettings(textDocument);
const [settings] = await Promise.all([settingsPromise, dataProvidersReady]);
const stylesheet = stylesheets.get(textDocument);
return getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
}
function updateDataProviders(dataPaths: string[]) {
dataProvidersReady = fetchDataProviders(dataPaths, requestService).then(customDataProviders => {
for (const lang in languageServices) {
languageServices[lang].setDataProviders(true, customDataProviders);
}
});
}
connection.onCompletion((textDocumentPosition, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (document) {
const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]);
const styleSheet = stylesheets.get(document);
const documentContext = getDocumentContext(document.uri, workspaceFolders);
return getLanguageService(document).doComplete2(document, textDocumentPosition.position, styleSheet, documentContext, settings?.completion);
}
return null;
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onHover((textDocumentPosition, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(textDocumentPosition.textDocument.uri);
if (document) {
const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]);
const styleSheet = stylesheets.get(document);
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet, settings?.hover);
}
return null;
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token);
});
connection.onDocumentSymbol((documentSymbolParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentSymbolParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentSymbols2(document, stylesheet);
}
return [];
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
});
connection.onDefinition((documentDefinitionParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentDefinitionParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet);
}
return null;
}, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token);
});
connection.onDocumentHighlight((documentHighlightParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentHighlightParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet);
}
return [];
}, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token);
});
connection.onDocumentLinks(async (documentLinkParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(documentLinkParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const documentContext = getDocumentContext(document.uri, workspaceFolders);
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext);
}
return [];
}, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token);
});
connection.onReferences((referenceParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(referenceParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
}
return [];
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token);
});
connection.onCodeAction((codeActionParams, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(codeActionParams.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
}
return [];
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token);
});
connection.onDocumentColor((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).findDocumentColors(document, stylesheet);
}
return [];
}, [], `Error while computing document colors for ${params.textDocument.uri}`, token);
});
connection.onColorPresentation((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
}
return [];
}, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
});
connection.onRenameRequest((renameParameters, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(renameParameters.textDocument.uri);
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
}
return null;
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token);
});
connection.onFoldingRanges((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
if (document) {
await dataProvidersReady;
return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
}
return null;
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
});
connection.onSelectionRanges((params, token) => {
return runSafeAsync(runtime, async () => {
const document = documents.get(params.textDocument.uri);
const positions: Position[] = params.positions;
if (document) {
await dataProvidersReady;
const stylesheet = stylesheets.get(document);
return getLanguageService(document).getSelectionRanges(document, positions, stylesheet);
}
return [];
}, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
});
async function onFormat(textDocument: TextDocumentIdentifier, range: Range | undefined, options: FormattingOptions): Promise<TextEdit[]> {
const document = documents.get(textDocument.uri);
if (document) {
const edits = getLanguageService(document).format(document, range ?? getFullRange(document), options);
if (edits.length > formatterMaxNumberOfEdits) {
const newText = TextDocument.applyEdits(document, edits);
return [TextEdit.replace(getFullRange(document), newText)];
}
return edits;
}
return [];
}
connection.onDocumentRangeFormatting((formatParams, token) => {
return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, formatParams.range, formatParams.options), [], `Error while formatting range for ${formatParams.textDocument.uri}`, token);
});
connection.onDocumentFormatting((formatParams, token) => {
return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, undefined, formatParams.options), [], `Error while formatting ${formatParams.textDocument.uri}`, token);
});
connection.onNotification(CustomDataChangedNotification.type, updateDataProviders);
// Listen on the connection
connection.listen();
}
function getFullRange(document: TextDocument): Range {
return Range.create(Position.create(0, 0), document.positionAt(document.getText().length));
}
| extensions/css-language-features/server/src/cssServer.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0001778933365130797,
0.00017453367763664573,
0.00016647267329972237,
0.00017521817062515765,
0.0000022916030957276234
] |
{
"id": 8,
"code_window": [
"\t\t}\n",
"\t}\n",
"\tNone\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"pub async fn wait_until_exe_deleted(current_exe: &Path, poll_ms: u64) {\n",
"\tlet duration = Duration::from_millis(poll_ms);\n",
"\twhile current_exe.exists() {\n",
"\t\ttokio::time::sleep(duration).await;\n",
"\t}\n",
"}"
],
"file_path": "cli/src/util/machine.rs",
"type": "add",
"edit_start_line_idx": 54
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use futures::{stream::FuturesUnordered, StreamExt};
use std::fmt;
use sysinfo::Pid;
use crate::util::{
machine::wait_until_process_exits,
sync::{new_barrier, Barrier, Receivable},
};
/// Describes the signal to manully stop the server
#[derive(Copy, Clone)]
pub enum ShutdownSignal {
CtrlC,
ParentProcessKilled(Pid),
ServiceStopped,
RpcShutdownRequested,
RpcRestartRequested,
}
impl fmt::Display for ShutdownSignal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ShutdownSignal::CtrlC => write!(f, "Ctrl-C received"),
ShutdownSignal::ParentProcessKilled(p) => {
write!(f, "Parent process {} no longer exists", p)
}
ShutdownSignal::ServiceStopped => write!(f, "Service stopped"),
ShutdownSignal::RpcShutdownRequested => write!(f, "RPC client requested shutdown"),
ShutdownSignal::RpcRestartRequested => {
write!(f, "RPC client requested a tunnel restart")
}
}
}
}
pub enum ShutdownRequest {
CtrlC,
ParentProcessKilled(Pid),
Derived(Box<dyn Receivable<ShutdownSignal> + Send>),
}
impl ShutdownRequest {
async fn wait(self) -> Option<ShutdownSignal> {
match self {
ShutdownRequest::CtrlC => {
let ctrl_c = tokio::signal::ctrl_c();
ctrl_c.await.ok();
Some(ShutdownSignal::CtrlC)
}
ShutdownRequest::ParentProcessKilled(pid) => {
wait_until_process_exits(pid, 2000).await;
Some(ShutdownSignal::ParentProcessKilled(pid))
}
ShutdownRequest::Derived(mut rx) => rx.recv_msg().await,
}
}
/// Creates a receiver channel sent to once any of the signals are received.
/// Note: does not handle ServiceStopped
pub fn create_rx(
signals: impl IntoIterator<Item = ShutdownRequest>,
) -> Barrier<ShutdownSignal> {
let (barrier, opener) = new_barrier();
let futures = signals
.into_iter()
.map(|s| s.wait())
.collect::<FuturesUnordered<_>>();
tokio::spawn(async move {
if let Some(s) = futures.filter_map(futures::future::ready).next().await {
opener.open(s);
}
});
barrier
}
}
| cli/src/tunnels/shutdown_signal.rs | 1 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0002218969602836296,
0.00017778080655261874,
0.00016730125935282558,
0.00017133481742348522,
0.00001641053313505836
] |
{
"id": 8,
"code_window": [
"\t\t}\n",
"\t}\n",
"\tNone\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"pub async fn wait_until_exe_deleted(current_exe: &Path, poll_ms: u64) {\n",
"\tlet duration = Duration::from_millis(poll_ms);\n",
"\twhile current_exe.exists() {\n",
"\t\ttokio::time::sleep(duration).await;\n",
"\t}\n",
"}"
],
"file_path": "cli/src/util/machine.rs",
"type": "add",
"edit_start_line_idx": 54
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Command, Disposable, Event, EventEmitter, SourceControlActionButton, Uri, workspace, l10n } from 'vscode';
import { Branch, RefType, Status } from './api/git';
import { OperationKind } from './operation';
import { CommitCommandsCenter } from './postCommitCommands';
import { Repository } from './repository';
import { dispose } from './util';
interface ActionButtonState {
readonly HEAD: Branch | undefined;
readonly isCheckoutInProgress: boolean;
readonly isCommitInProgress: boolean;
readonly isMergeInProgress: boolean;
readonly isRebaseInProgress: boolean;
readonly isSyncInProgress: boolean;
readonly repositoryHasChangesToCommit: boolean;
}
export class ActionButtonCommand {
private _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> { return this._onDidChange.event; }
private _state: ActionButtonState;
private get state() { return this._state; }
private set state(state: ActionButtonState) {
if (JSON.stringify(this._state) !== JSON.stringify(state)) {
this._state = state;
this._onDidChange.fire();
}
}
private disposables: Disposable[] = [];
constructor(
readonly repository: Repository,
readonly postCommitCommandCenter: CommitCommandsCenter) {
this._state = {
HEAD: undefined,
isCheckoutInProgress: false,
isCommitInProgress: false,
isMergeInProgress: false,
isRebaseInProgress: false,
isSyncInProgress: false,
repositoryHasChangesToCommit: false
};
repository.onDidRunGitStatus(this.onDidRunGitStatus, this, this.disposables);
repository.onDidChangeOperations(this.onDidChangeOperations, this, this.disposables);
this.disposables.push(repository.onDidChangeBranchProtection(() => this._onDidChange.fire()));
this.disposables.push(postCommitCommandCenter.onDidChange(() => this._onDidChange.fire()));
const root = Uri.file(repository.root);
this.disposables.push(workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('git.enableSmartCommit', root) ||
e.affectsConfiguration('git.smartCommitChanges', root) ||
e.affectsConfiguration('git.suggestSmartCommit', root)) {
this.onDidChangeSmartCommitSettings();
}
if (e.affectsConfiguration('git.branchProtectionPrompt', root) ||
e.affectsConfiguration('git.postCommitCommand', root) ||
e.affectsConfiguration('git.rememberPostCommitCommand', root) ||
e.affectsConfiguration('git.showActionButton', root)) {
this._onDidChange.fire();
}
}));
}
get button(): SourceControlActionButton | undefined {
if (!this.state.HEAD) { return undefined; }
let actionButton: SourceControlActionButton | undefined;
if (this.state.repositoryHasChangesToCommit) {
// Commit Changes (enabled)
actionButton = this.getCommitActionButton();
}
// Commit Changes (enabled) -> Publish Branch -> Sync Changes -> Commit Changes (disabled)
return actionButton ?? this.getPublishBranchActionButton() ?? this.getSyncChangesActionButton() ?? this.getCommitActionButton();
}
private getCommitActionButton(): SourceControlActionButton | undefined {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const showActionButton = config.get<{ commit: boolean }>('showActionButton', { commit: true });
// The button is disabled
if (!showActionButton.commit) { return undefined; }
const primaryCommand = this.getCommitActionButtonPrimaryCommand();
return {
command: primaryCommand,
secondaryCommands: this.getCommitActionButtonSecondaryCommands(),
enabled: (this.state.repositoryHasChangesToCommit || this.state.isRebaseInProgress) && !this.state.isCommitInProgress && !this.state.isMergeInProgress
};
}
private getCommitActionButtonPrimaryCommand(): Command {
// Rebase Continue
if (this.state.isRebaseInProgress) {
return {
command: 'git.commit',
title: l10n.t('{0} Continue', '$(check)'),
tooltip: this.state.isCommitInProgress ? l10n.t('Continuing Rebase...') : l10n.t('Continue Rebase'),
arguments: [this.repository.sourceControl, '']
};
}
// Commit
return this.postCommitCommandCenter.getPrimaryCommand();
}
private getCommitActionButtonSecondaryCommands(): Command[][] {
// Rebase Continue
if (this.state.isRebaseInProgress) {
return [];
}
// Commit
const commandGroups: Command[][] = [];
for (const commands of this.postCommitCommandCenter.getSecondaryCommands()) {
commandGroups.push(commands.map(c => {
return { command: 'git.commit', title: c.title, tooltip: c.tooltip, arguments: c.arguments };
}));
}
return commandGroups;
}
private getPublishBranchActionButton(): SourceControlActionButton | undefined {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const showActionButton = config.get<{ publish: boolean }>('showActionButton', { publish: true });
// Not a branch (tag, detached), branch does have an upstream, commit/merge/rebase is in progress, or the button is disabled
if (this.state.HEAD?.type === RefType.Tag || !this.state.HEAD?.name || this.state.HEAD?.upstream || this.state.isCommitInProgress || this.state.isMergeInProgress || this.state.isRebaseInProgress || !showActionButton.publish) { return undefined; }
// Button icon
const icon = this.state.isSyncInProgress ? '$(sync~spin)' : '$(cloud-upload)';
return {
command: {
command: 'git.publish',
title: l10n.t({ message: '{0} Publish Branch', args: [icon], comment: ['{Locked="Branch"}', 'Do not translate "Branch" as it is a git term'] }),
tooltip: this.state.isSyncInProgress ?
(this.state.HEAD?.name ?
l10n.t({ message: 'Publishing Branch "{0}"...', args: [this.state.HEAD.name], comment: ['{Locked="Branch"}', 'Do not translate "Branch" as it is a git term'] }) :
l10n.t({ message: 'Publishing Branch...', comment: ['{Locked="Branch"}', 'Do not translate "Branch" as it is a git term'] })) :
(this.repository.HEAD?.name ?
l10n.t({ message: 'Publish Branch "{0}"', args: [this.state.HEAD?.name], comment: ['{Locked="Branch"}', 'Do not translate "Branch" as it is a git term'] }) :
l10n.t({ message: 'Publish Branch', comment: ['{Locked="Branch"}', 'Do not translate "Branch" as it is a git term'] })),
arguments: [this.repository.sourceControl],
},
enabled: !this.state.isCheckoutInProgress && !this.state.isSyncInProgress
};
}
private getSyncChangesActionButton(): SourceControlActionButton | undefined {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const showActionButton = config.get<{ sync: boolean }>('showActionButton', { sync: true });
const branchIsAheadOrBehind = (this.state.HEAD?.behind ?? 0) > 0 || (this.state.HEAD?.ahead ?? 0) > 0;
// Branch does not have an upstream, branch is not ahead/behind the remote branch, commit/merge/rebase is in progress, or the button is disabled
if (!this.state.HEAD?.upstream || !branchIsAheadOrBehind || this.state.isCommitInProgress || this.state.isMergeInProgress || this.state.isRebaseInProgress || !showActionButton.sync) { return undefined; }
const ahead = this.state.HEAD.ahead ? ` ${this.state.HEAD.ahead}$(arrow-up)` : '';
const behind = this.state.HEAD.behind ? ` ${this.state.HEAD.behind}$(arrow-down)` : '';
const icon = this.state.isSyncInProgress ? '$(sync~spin)' : '$(sync)';
return {
command: {
command: 'git.sync',
title: l10n.t('{0} Sync Changes{1}{2}', icon, behind, ahead),
tooltip: this.state.isSyncInProgress ?
l10n.t('Synchronizing Changes...')
: this.repository.syncTooltip,
arguments: [this.repository.sourceControl],
},
description: `${icon}${behind}${ahead}`,
enabled: !this.state.isCheckoutInProgress && !this.state.isSyncInProgress
};
}
private onDidChangeOperations(): void {
const isCheckoutInProgress
= this.repository.operations.isRunning(OperationKind.Checkout) ||
this.repository.operations.isRunning(OperationKind.CheckoutTracking);
const isCommitInProgress =
this.repository.operations.isRunning(OperationKind.Commit) ||
this.repository.operations.isRunning(OperationKind.PostCommitCommand) ||
this.repository.operations.isRunning(OperationKind.RebaseContinue);
const isSyncInProgress =
this.repository.operations.isRunning(OperationKind.Sync) ||
this.repository.operations.isRunning(OperationKind.Push) ||
this.repository.operations.isRunning(OperationKind.Pull);
this.state = { ...this.state, isCheckoutInProgress, isCommitInProgress, isSyncInProgress };
}
private onDidChangeSmartCommitSettings(): void {
this.state = {
...this.state,
repositoryHasChangesToCommit: this.repositoryHasChangesToCommit()
};
}
private onDidRunGitStatus(): void {
this.state = {
...this.state,
HEAD: this.repository.HEAD,
isMergeInProgress: this.repository.mergeGroup.resourceStates.length !== 0,
isRebaseInProgress: !!this.repository.rebaseCommit,
repositoryHasChangesToCommit: this.repositoryHasChangesToCommit()
};
}
private repositoryHasChangesToCommit(): boolean {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const enableSmartCommit = config.get<boolean>('enableSmartCommit') === true;
const suggestSmartCommit = config.get<boolean>('suggestSmartCommit') === true;
const smartCommitChanges = config.get<'all' | 'tracked'>('smartCommitChanges', 'all');
const resources = [...this.repository.indexGroup.resourceStates];
if (
// Smart commit enabled (all)
(enableSmartCommit && smartCommitChanges === 'all') ||
// Smart commit disabled, smart suggestion enabled
(!enableSmartCommit && suggestSmartCommit)
) {
resources.push(...this.repository.workingTreeGroup.resourceStates);
}
// Smart commit enabled (tracked only)
if (enableSmartCommit && smartCommitChanges === 'tracked') {
resources.push(...this.repository.workingTreeGroup.resourceStates.filter(r => r.type !== Status.UNTRACKED));
}
return resources.length !== 0;
}
dispose(): void {
this.disposables = dispose(this.disposables);
}
}
| extensions/git/src/actionButton.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00029407264082692564,
0.00017585520981810987,
0.00016558787319809198,
0.00016732783115003258,
0.00002517977191018872
] |
{
"id": 8,
"code_window": [
"\t\t}\n",
"\t}\n",
"\tNone\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"pub async fn wait_until_exe_deleted(current_exe: &Path, poll_ms: u64) {\n",
"\tlet duration = Duration::from_millis(poll_ms);\n",
"\twhile current_exe.exists() {\n",
"\t\ttokio::time::sleep(duration).await;\n",
"\t}\n",
"}"
],
"file_path": "cli/src/util/machine.rs",
"type": "add",
"edit_start_line_idx": 54
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { Barrier, Promises } from 'vs/base/common/async';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IUserDataInitializer } from 'vs/workbench/services/userData/browser/userDataInit';
import { IProfileResourceInitializer, IUserDataProfileService, IUserDataProfileTemplate, ProfileResourceType } from 'vs/workbench/services/userDataProfile/common/userDataProfile';
import { SettingsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/settingsResource';
import { GlobalStateResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/globalStateResource';
import { KeybindingsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/keybindingsResource';
import { TasksResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/tasksResource';
import { SnippetsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/snippetsResource';
import { ExtensionsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/extensionsResource';
import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService';
import { isString } from 'vs/base/common/types';
import { IRequestService, asJson } from 'vs/platform/request/common/request';
import { CancellationToken } from 'vs/base/common/cancellation';
import { URI } from 'vs/base/common/uri';
export class UserDataProfileInitializer implements IUserDataInitializer {
_serviceBrand: any;
private readonly initialized: ProfileResourceType[] = [];
private readonly initializationFinished = new Barrier();
constructor(
@IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService,
@IFileService private readonly fileService: IFileService,
@IUserDataProfileService private readonly userDataProfileService: IUserDataProfileService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IRequestService private readonly requestService: IRequestService,
) {
}
async whenInitializationFinished(): Promise<void> {
await this.initializationFinished.wait();
}
async requiresInitialization(): Promise<boolean> {
if (!this.environmentService.options?.profile?.contents) {
return false;
}
if (!this.storageService.isNew(StorageScope.PROFILE)) {
return false;
}
return true;
}
async initializeRequiredResources(): Promise<void> {
this.logService.trace(`UserDataProfileInitializer#initializeRequiredResources`);
const promises = [];
const profileTemplate = await this.getProfileTemplate();
if (profileTemplate?.settings) {
promises.push(this.initialize(new SettingsResourceInitializer(this.userDataProfileService, this.fileService, this.logService), profileTemplate.settings, ProfileResourceType.Settings));
}
if (profileTemplate?.globalState) {
promises.push(this.initialize(new GlobalStateResourceInitializer(this.storageService), profileTemplate.globalState, ProfileResourceType.GlobalState));
}
await Promise.all(promises);
}
async initializeOtherResources(instantiationService: IInstantiationService): Promise<void> {
try {
this.logService.trace(`UserDataProfileInitializer#initializeOtherResources`);
const promises = [];
const profileTemplate = await this.getProfileTemplate();
if (profileTemplate?.keybindings) {
promises.push(this.initialize(new KeybindingsResourceInitializer(this.userDataProfileService, this.fileService, this.logService), profileTemplate.keybindings, ProfileResourceType.Keybindings));
}
if (profileTemplate?.tasks) {
promises.push(this.initialize(new TasksResourceInitializer(this.userDataProfileService, this.fileService, this.logService), profileTemplate.tasks, ProfileResourceType.Tasks));
}
if (profileTemplate?.snippets) {
promises.push(this.initialize(new SnippetsResourceInitializer(this.userDataProfileService, this.fileService, this.uriIdentityService), profileTemplate.snippets, ProfileResourceType.Snippets));
}
promises.push(this.initializeInstalledExtensions(instantiationService));
await Promises.settled(promises);
} finally {
this.initializationFinished.open();
}
}
private initializeInstalledExtensionsPromise: Promise<void> | undefined;
async initializeInstalledExtensions(instantiationService: IInstantiationService): Promise<void> {
if (!this.initializeInstalledExtensionsPromise) {
const profileTemplate = await this.getProfileTemplate();
if (profileTemplate?.extensions) {
this.initializeInstalledExtensionsPromise = this.initialize(instantiationService.createInstance(ExtensionsResourceInitializer), profileTemplate.extensions, ProfileResourceType.Extensions);
} else {
this.initializeInstalledExtensionsPromise = Promise.resolve();
}
}
return this.initializeInstalledExtensionsPromise;
}
private profileTemplatePromise: Promise<IUserDataProfileTemplate | null> | undefined;
private getProfileTemplate(): Promise<IUserDataProfileTemplate | null> {
if (!this.profileTemplatePromise) {
this.profileTemplatePromise = this.doGetProfileTemplate();
}
return this.profileTemplatePromise;
}
private async doGetProfileTemplate(): Promise<IUserDataProfileTemplate | null> {
if (!this.environmentService.options?.profile?.contents) {
return null;
}
if (isString(this.environmentService.options.profile.contents)) {
try {
return JSON.parse(this.environmentService.options.profile.contents);
} catch (error) {
this.logService.error(error);
return null;
}
}
try {
const url = URI.revive(this.environmentService.options.profile.contents).toString(true);
const context = await this.requestService.request({ type: 'GET', url }, CancellationToken.None);
if (context.res.statusCode === 200) {
return await asJson(context);
} else {
this.logService.warn(`UserDataProfileInitializer: Failed to get profile from URL: ${url}. Status code: ${context.res.statusCode}.`);
}
} catch (error) {
this.logService.error(error);
}
return null;
}
private async initialize(initializer: IProfileResourceInitializer, content: string, profileResource: ProfileResourceType): Promise<void> {
try {
if (this.initialized.includes(profileResource)) {
this.logService.info(`UserDataProfileInitializer: ${profileResource} initialized already.`);
return;
}
this.initialized.push(profileResource);
this.logService.trace(`UserDataProfileInitializer: Initializing ${profileResource}`);
await initializer.initialize(content);
this.logService.info(`UserDataProfileInitializer: Initialized ${profileResource}`);
} catch (error) {
this.logService.info(`UserDataProfileInitializer: Error while initializing ${profileResource}`);
this.logService.error(error);
}
}
}
| src/vs/workbench/services/userDataProfile/browser/userDataProfileInit.ts | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.0007175283972173929,
0.00021113775437697768,
0.00016588068683631718,
0.0001685347524471581,
0.0001350140810245648
] |
{
"id": 8,
"code_window": [
"\t\t}\n",
"\t}\n",
"\tNone\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"pub async fn wait_until_exe_deleted(current_exe: &Path, poll_ms: u64) {\n",
"\tlet duration = Duration::from_millis(poll_ms);\n",
"\twhile current_exe.exists() {\n",
"\t\ttokio::time::sleep(duration).await;\n",
"\t}\n",
"}"
],
"file_path": "cli/src/util/machine.rs",
"type": "add",
"edit_start_line_idx": 54
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
| extensions/groovy/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/0c85b95c485d856a6676fec7e11ed92985729989 | [
0.00017191821825690567,
0.00017191821825690567,
0.00017191821825690567,
0.00017191821825690567,
0
] |
{
"id": 0,
"code_window": [
"import {\n",
" BOUND_TEXT_PADDING,\n",
" ROUNDNESS,\n",
" TEXT_ALIGN,\n",
" VERTICAL_ALIGN,\n",
"} from \"../constants\";\n",
"import { getNonDeletedElements, isTextElement, newElement } from \"../element\";\n",
"import { mutateElement } from \"../element/mutateElement\";\n",
"import {\n",
" computeContainerDimensionForBoundText,\n",
" getBoundTextElement,\n"
],
"labels": [
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BOUND_TEXT_PADDING, ROUNDNESS, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 0
} | import ReactDOM from "react-dom";
import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys";
import {
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react";
import { FONT_FAMILY } from "../constants";
import {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
} from "./types";
import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const tab = " ";
const mouse = new Pointer("mouse");
describe("textWysiwyg", () => {
describe("start text editing", () => {
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
});
it("should prefer editing selected text element (non-bindable container present)", async () => {
const line = API.createElement({
type: "line",
width: 100,
height: 0,
points: [
[0, 0],
[100, 0],
],
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: line.width / 2 - textSize / 2,
y: -textSize / 2,
width: textSize,
height: textSize,
});
h.elements = [text, line];
API.setSelectedElements([text]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
expect(
(h.state.editingElement as ExcalidrawTextElement).containerId,
).toBe(null);
});
it("should prefer editing selected text element (bindable container present)", async () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([boundText2]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText2.id);
});
it("should not create bound text on ENTER if text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
mutateElement(container, {
boundElements: [{ type: "text", id: text.id }],
});
h.elements = [container, text];
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
});
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText.id);
});
it("should edit text under cursor when clicked with text tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("text");
mouse.clickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
it("should edit text under cursor when double-clicked with selection tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("selection");
mouse.doubleClickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
});
describe("Test container-unbound text", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text");
mouse.clickOn(textElement);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "|Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
// cursor: " |Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(4);
expect(textarea.selectionEnd).toEqual(4);
});
it("should add a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "Line#1\nLin|e#2"
textarea.selectionStart = 10;
textarea.selectionEnd = 10;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
// cursor: "Line#1\n Lin|e#2"
expect(textarea.selectionStart).toEqual(14);
expect(textarea.selectionEnd).toEqual(14);
});
it("should add a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2\nLine#3";
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
textarea.selectionStart = 2;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(6);
expect(textarea.selectionEnd).toEqual(17);
});
it("should remove a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
textarea.value = `${tab}Line#1\nLine#2`;
// cursor: "| Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "|Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(0);
expect(textarea.selectionEnd).toEqual(0);
});
it("should remove a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Lin|e#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "Line#1\nLin|e#2"
expect(textarea.selectionStart).toEqual(11);
expect(textarea.selectionEnd).toEqual(11);
});
it("should remove a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
textarea.selectionStart = 6;
textarea.selectionEnd = 17;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(2);
expect(textarea.selectionEnd).toEqual(9);
});
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n | Line#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
// cursor: "Line#1\n|Line#2"
expect(textarea.selectionStart).toEqual(7);
// expect(textarea.selectionEnd).toEqual(7);
});
it("should remove partial tabs", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Line#|2"
textarea.value = `Line#1\n Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should remove nothing", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Li|ne#2"
textarea.value = `Line#1\nLine#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should resize text via shortcuts while in wysiwyg", () => {
textarea.value = "abc def";
const origFontSize = textElement.fontSize;
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_RIGHT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize * 1.1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_LEFT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize);
});
it("zooming via keyboard should zoom canvas", () => {
expect(h.state.zoom.value).toBe(1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.MINUS,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_SUBTRACT,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.8);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_ADD,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.EQUAL,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(1);
});
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
});
describe("Test container-bound text", () => {
let rectangle: any;
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
rectangle = UI.createElement("rectangle", {
x: 10,
y: 20,
width: 90,
height: 75,
});
});
it("should bind text to container when double clicked inside filled container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "red",
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "transparent",
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
expect(h.elements.length).toBe(3);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when clicked on container and enter pressed", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on container stroke", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
strokeWidth: 4,
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 2, rectangle.y + 2);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("shouldn't bind to non-text-bindable containers", async () => {
const freedraw = API.createElement({
type: "freedraw",
width: 100,
height: 0,
});
h.elements = [freedraw];
UI.clickTool("text");
mouse.clickAt(
freedraw.x + freedraw.width / 2,
freedraw.y + freedraw.height / 2,
);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
editor.dispatchEvent(new Event("input"));
expect(freedraw.boundElements).toBe(null);
expect(h.elements[1].type).toBe("text");
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = [];
const element = UI.createElement(type, {
width: 100,
height: 50,
});
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
});
it("should'nt bind text to container when not double clicked on center", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
// clicking somewhere on top left
mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toBe(null);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
UI.clickTool("text");
mouse.clickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle(/code/i));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
//undo
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Virgil);
//redo
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
});
it("should wrap text and vertcially center align once text submitted", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(25);
expect(text.height).toBe(48);
expect(text.width).toBe(60);
// Edit and text by removing second line and it should
// still vertically align correctly
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello");
expect(text.height).toBe(24);
expect(text.width).toBe(50);
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(30);
});
it("should unbind bound text when unbind action from context menu is triggered", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.reset();
UI.clickTool("selection");
mouse.clickAt(10, 20);
mouse.down();
mouse.up();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
null,
);
});
it("shouldn't bind to container if container has bound text", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
// Bind first text
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should respect text alignment when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
85,
5,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
375,
-539,
]
`);
});
it("should always bind to selected container and insert it in correct position", async () => {
const rectangle2 = UI.createElement("rectangle", {
x: 5,
y: 10,
width: 120,
height: 100,
});
API.setSelectedElements([rectangle]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(3);
expect(h.elements[1].type).toBe("text");
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle2.boundElements).toBeNull();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should scale font size correctly when resizing using shift", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(rectangle.width).toBe(90);
expect(rectangle.height).toBe(75);
expect(textElement.fontSize).toBe(20);
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 50], {
shift: true,
});
expect(rectangle.width).toBe(200);
expect(rectangle.height).toBe(166.66666666666669);
expect(textElement.fontSize).toBe(47.5);
});
it("should bind text correctly when container duplicated with alt-drag", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(h.elements.length).toBe(2);
mouse.select(rectangle);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle.x + 10, rectangle.y + 10);
mouse.up(rectangle.x + 10, rectangle.y + 10);
});
expect(h.elements.length).toBe(4);
const duplicatedRectangle = h.elements[0];
const duplicatedText = h
.elements[1] as ExcalidrawTextElementWithContainer;
const originalRect = h.elements[2];
const originalText = h.elements[3] as ExcalidrawTextElementWithContainer;
expect(originalRect.boundElements).toStrictEqual([
{ id: originalText.id, type: "text" },
]);
expect(originalText.containerId).toBe(originalRect.id);
expect(duplicatedRectangle.boundElements).toStrictEqual([
{ id: duplicatedText.id, type: "text" },
]);
expect(duplicatedText.containerId).toBe(duplicatedRectangle.id);
});
it("undo should work", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
const originalRectX = rectangle.x;
const originalRectY = rectangle.y;
const originalTextX = text.x;
const originalTextY = text.y;
mouse.select(rectangle);
mouse.downAt(rectangle.x, rectangle.y);
mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-35);
expect(text.x).toBe(85);
expect(text.y).toBe(-30);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(rectangle.x).toBe(originalRectX);
expect(rectangle.y).toBe(originalRectY);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.x).toBe(originalTextX);
expect(text.y).toBe(originalTextY);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should not allow bound text with only whitespaces", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: " " } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([]);
expect(h.elements[1].isDeleted).toBe(true);
});
it("should restore original container height and clear cache once text is unbind", async () => {
const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, {
target: { value: "Online whiteboard collaboration made easy" },
});
editor.blur();
expect(rectangle.height).toBe(178);
mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
expect(rectangle.height).toBe(originalRectHeight);
});
it("should reset the container height cache when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.height).toBe(156);
// cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156);
});
it("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
fireEvent.click(screen.getByTitle(/Very large/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
96.39999999999999,
);
});
describe("should align correctly", () => {
let editor: HTMLTextAreaElement;
beforeEach(async () => {
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
});
it("when top left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
25,
]
`);
});
it("when top center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
25,
]
`);
});
it("when top right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
25,
]
`);
});
it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
45.5,
]
`);
});
it("when center center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
45.5,
]
`);
});
it("when center right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
45.5,
]
`);
});
it("when bottom left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
});
it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
66,
]
`);
});
it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
66,
]
`);
});
});
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
expect(h.elements[1].width).toBe(600);
expect(h.elements[1].height).toBe(24);
expect((h.elements[1] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 34,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect((h.elements[2] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
});
});
});
| src/element/textWysiwyg.test.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.014910642057657242,
0.0003490587987471372,
0.00016434051212854683,
0.00017275150457862765,
0.0012782992562279105
] |
{
"id": 0,
"code_window": [
"import {\n",
" BOUND_TEXT_PADDING,\n",
" ROUNDNESS,\n",
" TEXT_ALIGN,\n",
" VERTICAL_ALIGN,\n",
"} from \"../constants\";\n",
"import { getNonDeletedElements, isTextElement, newElement } from \"../element\";\n",
"import { mutateElement } from \"../element/mutateElement\";\n",
"import {\n",
" computeContainerDimensionForBoundText,\n",
" getBoundTextElement,\n"
],
"labels": [
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BOUND_TEXT_PADDING, ROUNDNESS, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 0
} | import React from "react";
import { getCommonBounds } from "../element/bounds";
import { NonDeletedExcalidrawElement } from "../element/types";
import { t } from "../i18n";
import { getTargetElements } from "../scene";
import { AppState, ExcalidrawProps } from "../types";
import { CloseIcon } from "./icons";
import { Island } from "./Island";
import "./Stats.scss";
export const Stats = (props: {
appState: AppState;
setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[];
onClose: () => void;
renderCustomStats: ExcalidrawProps["renderCustomStats"];
}) => {
const boundingBox = getCommonBounds(props.elements);
const selectedElements = getTargetElements(props.elements, props.appState);
const selectedBoundingBox = getCommonBounds(selectedElements);
return (
<div className="Stats">
<Island padding={2}>
<div className="close" onClick={props.onClose}>
{CloseIcon}
</div>
<h3>{t("stats.title")}</h3>
<table>
<tbody>
<tr>
<th colSpan={2}>{t("stats.scene")}</th>
</tr>
<tr>
<td>{t("stats.elements")}</td>
<td>{props.elements.length}</td>
</tr>
<tr>
<td>{t("stats.width")}</td>
<td>{Math.round(boundingBox[2]) - Math.round(boundingBox[0])}</td>
</tr>
<tr>
<td>{t("stats.height")}</td>
<td>{Math.round(boundingBox[3]) - Math.round(boundingBox[1])}</td>
</tr>
{selectedElements.length === 1 && (
<tr>
<th colSpan={2}>{t("stats.element")}</th>
</tr>
)}
{selectedElements.length > 1 && (
<>
<tr>
<th colSpan={2}>{t("stats.selected")}</th>
</tr>
<tr>
<td>{t("stats.elements")}</td>
<td>{selectedElements.length}</td>
</tr>
</>
)}
{selectedElements.length > 0 && (
<>
<tr>
<td>{"x"}</td>
<td>{Math.round(selectedBoundingBox[0])}</td>
</tr>
<tr>
<td>{"y"}</td>
<td>{Math.round(selectedBoundingBox[1])}</td>
</tr>
<tr>
<td>{t("stats.width")}</td>
<td>
{Math.round(
selectedBoundingBox[2] - selectedBoundingBox[0],
)}
</td>
</tr>
<tr>
<td>{t("stats.height")}</td>
<td>
{Math.round(
selectedBoundingBox[3] - selectedBoundingBox[1],
)}
</td>
</tr>
</>
)}
{selectedElements.length === 1 && (
<tr>
<td>{t("stats.angle")}</td>
<td>
{`${Math.round(
(selectedElements[0].angle * 180) / Math.PI,
)}°`}
</td>
</tr>
)}
{props.renderCustomStats?.(props.elements, props.appState)}
</tbody>
</table>
</Island>
</div>
);
};
| src/components/Stats.tsx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0005657713045366108,
0.00022335896210279316,
0.0001708156050881371,
0.00017381606448907405,
0.00011729038669727743
] |
{
"id": 0,
"code_window": [
"import {\n",
" BOUND_TEXT_PADDING,\n",
" ROUNDNESS,\n",
" TEXT_ALIGN,\n",
" VERTICAL_ALIGN,\n",
"} from \"../constants\";\n",
"import { getNonDeletedElements, isTextElement, newElement } from \"../element\";\n",
"import { mutateElement } from \"../element/mutateElement\";\n",
"import {\n",
" computeContainerDimensionForBoundText,\n",
" getBoundTextElement,\n"
],
"labels": [
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BOUND_TEXT_PADDING, ROUNDNESS, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 0
} | <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 97 77">
<!-- svg-source:excalidraw -->
<!-- payload-type:application/vnd.excalidraw+json --><!-- payload-start -->ewogICJ0eXBlIjogImV4Y2FsaWRyYXciLAogICJ2ZXJzaW9uIjogMiwKICAic291cmNlIjogImh0dHBzOi8vZXhjYWxpZHJhdy5jb20iLAogICJlbGVtZW50cyI6IFsKICAgIHsKICAgICAgImlkIjogInRabVFwa0cyQlZ2SzNxT01icHVXeiIsCiAgICAgICJ0eXBlIjogInRleHQiLAogICAgICAieCI6IDg2MS4xMTExMTExMTExMTExLAogICAgICAieSI6IDM1Ni4zMzMzMzMzMzMzMzMzLAogICAgICAid2lkdGgiOiA3NywKICAgICAgImhlaWdodCI6IDU3LAogICAgICAiYW5nbGUiOiAwLAogICAgICAic3Ryb2tlQ29sb3IiOiAiIzAwMDAwMCIsCiAgICAgICJiYWNrZ3JvdW5kQ29sb3IiOiAiIzg2OGU5NiIsCiAgICAgICJmaWxsU3R5bGUiOiAiY3Jvc3MtaGF0Y2giLAogICAgICAic3Ryb2tlV2lkdGgiOiAyLAogICAgICAic3Ryb2tlU3R5bGUiOiAic29saWQiLAogICAgICAicm91Z2huZXNzIjogMSwKICAgICAgIm9wYWNpdHkiOiAxMDAsCiAgICAgICJncm91cElkcyI6IFtdLAogICAgICAic3Ryb2tlU2hhcnBuZXNzIjogInJvdW5kIiwKICAgICAgInNlZWQiOiA0NzYzNjM3OTMsCiAgICAgICJ2ZXJzaW9uIjogMjMsCiAgICAgICJ2ZXJzaW9uTm9uY2UiOiA1OTc0MzUxMzUsCiAgICAgICJpc0RlbGV0ZWQiOiBmYWxzZSwKICAgICAgImJvdW5kRWxlbWVudElkcyI6IG51bGwsCiAgICAgICJ0ZXh0IjogInRlc3QiLAogICAgICAiZm9udFNpemUiOiAzNiwKICAgICAgImZvbnRGYW1pbHkiOiAxLAogICAgICAidGV4dEFsaWduIjogImxlZnQiLAogICAgICAidmVydGljYWxBbGlnbiI6ICJ0b3AiLAogICAgICAiYmFzZWxpbmUiOiA0MQogICAgfQogIF0sCiAgImFwcFN0YXRlIjogewogICAgInZpZXdCYWNrZ3JvdW5kQ29sb3IiOiAiI2ZmZmZmZiIsCiAgICAiZ3JpZFNpemUiOiBudWxsCiAgfQp9<!-- payload-end -->
<defs>
<style>
@font-face {
font-family: "Virgil";
src: url("https://excalidraw.com/Virgil.woff2");
}
@font-face {
font-family: "Cascadia";
src: url("https://excalidraw.com/Cascadia.woff2");
}
</style>
</defs>
<rect x="0" y="0" width="97" height="77" fill="#ffffff"></rect><g transform="translate(10 10) rotate(0 38.5 28.5)"><text x="0" y="41" font-family="Virgil, Segoe UI Emoji" font-size="36px" fill="#000000" text-anchor="start" style="white-space: pre;" direction="ltr">test</text></g></svg>
| src/tests/fixtures/test_embedded_v1.svg | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017488417506683618,
0.00016965677787084132,
0.00016442938067484647,
0.00016965677787084132,
0.000005227397195994854
] |
{
"id": 0,
"code_window": [
"import {\n",
" BOUND_TEXT_PADDING,\n",
" ROUNDNESS,\n",
" TEXT_ALIGN,\n",
" VERTICAL_ALIGN,\n",
"} from \"../constants\";\n",
"import { getNonDeletedElements, isTextElement, newElement } from \"../element\";\n",
"import { mutateElement } from \"../element/mutateElement\";\n",
"import {\n",
" computeContainerDimensionForBoundText,\n",
" getBoundTextElement,\n"
],
"labels": [
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BOUND_TEXT_PADDING, ROUNDNESS, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 0
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`exportToSvg with default arguments 1`] = `
<svg
height="120"
version="1.1"
viewBox="0 0 120 120"
width="120"
xmlns="http://www.w3.org/2000/svg"
>
<!-- svg-source:excalidraw -->
<defs>
<style
class="style-fonts"
>
@font-face {
font-family: "Virgil";
src: url("https://excalidraw.com/Virgil.woff2");
}
@font-face {
font-family: "Cascadia";
src: url("https://excalidraw.com/Cascadia.woff2");
}
</style>
</defs>
<g
stroke-linecap="round"
transform="translate(10 10) rotate(0 50 50)"
>
<path
d="M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M1.31 55.08 C15.31 40.32, 29.59 22.37, 41.3 9.81 M2.95 54.67 C16.06 38.64, 28.38 26.08, 41.31 11.16 M5.17 55.28 C18.64 40.54, 34.59 23.3, 53.31 1.2 M6.19 55.83 C19.7 40.85, 33.94 25.36, 52.84 2.99 M8.12 57.33 C28.32 38.18, 46.32 16.69, 57.78 5.54 M9.05 59.26 C25.33 39.84, 41.83 20.42, 56.36 4.41 M12.23 63.33 C23.99 47.5, 34.76 34.04, 58.25 7.72 M12.1 62.42 C25.64 45.74, 39.58 29.47, 59.39 6.7 M14.29 65.31 C33.6 44.37, 51.89 21.73, 61.4 11.6 M14.95 64.35 C25.42 51.41, 36.81 39.88, 61.57 11.19 M17.44 69.69 C30.26 56.06, 39.46 44.26, 65.11 14.18 M17.51 68.63 C34.43 47.57, 51.04 27.25, 64.33 13.82 M21.98 70.02 C37.96 53.4, 51.32 32.51, 66.76 17.85 M20.5 70.41 C29.55 59.82, 39.04 48.82, 66.82 15.79 M21.73 71.26 C33.76 59.36, 45.61 49.75, 69.47 19.91 M23.35 73.09 C39.91 53.14, 58.94 32.17, 69.77 19.39 M26.91 74.54 C41.56 60.59, 55.7 44.03, 72.29 22.07 M26.74 75.44 C39.06 62.99, 49.89 47.62, 73.34 21.9 M27.68 77.61 C45.49 62.49, 58.86 43.36, 74.53 26.67 M29.77 78.46 C46.48 58.69, 65.8 38.46, 75.03 24.23 M29.82 83.37 C45.64 68.39, 59.09 52.88, 78 26.2 M31.24 82.29 C42.16 70.24, 50.48 58.61, 77.54 28.77 M33.5 84.64 C46.6 69.19, 61.43 52.15, 81.17 32.8 M34.1 85.27 C44.17 73.12, 52.8 63.6, 80.62 31.25 M37.69 88.37 C54.96 70.16, 71.4 49.55, 82.89 35.26 M37.41 86.61 C46.27 76.03, 56.22 65.63, 84.34 34.18 M38.98 88.4 C54.78 76.48, 66.88 59.43, 87.83 36.78 M40.83 89.54 C52.97 74.67, 64.21 61.17, 86.21 36.91 M43.18 94 C60.91 72.19, 77.04 51.45, 90.21 39.94 M43.86 92.11 C52.94 82.13, 62.98 68.89, 90.51 39.02 M44.93 94.32 C62.61 77.05, 76.42 59.94, 91.95 44.23 M45.02 96.15 C61.2 76.98, 78.3 58.77, 92.03 42.23 M50.55 99.15 C60.63 81.82, 75.04 67.37, 96.9 43.53 M48.39 98.32 C65.04 78.28, 81.92 59.44, 94.04 46.22 M50.38 99.19 C69.54 81.19, 85.85 58.94, 99.21 46.38 M51.53 100.79 C62.45 87.27, 73.41 74.93, 98.13 47.3"
fill="none"
stroke="#15aabf"
stroke-width="0.5"
/>
<path
d="M50.55 -1.01 C62.82 12.44, 78.03 26.68, 100.3 51.7 M50.44 0.46 C69.95 19.26, 89.63 39.73, 99.86 51.76 M98.12 50.21 C82.92 71.13, 65.15 88.19, 49.66 98.72 M99.37 50.68 C88.57 62.94, 74.79 76.37, 50.44 100 M52.55 99.9 C35.86 87.61, 23.16 74.12, 0.75 52.33 M51.67 99.75 C32.82 83.31, 13.73 65.72, 0.11 50.74 M-1.95 52.94 C13.84 37.62, 25.27 26.82, 50.8 2 M0.66 50.92 C16.45 35.71, 32.61 18.7, 51.59 0.01"
fill="none"
stroke="#000000"
stroke-width="1"
/>
</g>
<g
stroke-linecap="round"
transform="translate(10 10) rotate(0 50 50)"
>
<path
d="M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M5.51 34 C13.17 23.26, 20.2 13.31, 28.19 8.96 M5.48 33.35 C12.13 25.41, 19.79 15.96, 26.45 7.6 M5.56 37.62 C16.59 25.63, 28.15 12.22, 38.46 2.39 M5.11 40.5 C16.67 26.96, 28.16 13.15, 36.64 1.59 M4.66 45.59 C13.25 35.02, 21.41 28.15, 39.56 4.69 M4.57 46.97 C11.96 37.32, 20.9 26.56, 40.44 3.42 M5.51 50.51 C13.89 43.35, 21.63 34.54, 46.26 4.75 M4.27 51.77 C16.66 37.46, 28.38 22.96, 44.97 4.33 M0.17 60.65 C18.76 40.92, 37.97 17.6, 49.71 5.16 M0.46 61.18 C19.32 40.86, 37.47 20.77, 50.84 4.21 M2.75 65.39 C21.01 45.29, 37.92 25.46, 57.52 4.43 M3.54 66.52 C18.04 48.78, 32.49 30.26, 55.79 4.21 M4.72 71.04 C27.28 44.43, 49.83 20.12, 62.05 5.19 M4.98 68.42 C25.81 45.48, 47.44 20.41, 60.72 5.33 M5.52 72.07 C22.65 55.25, 37.54 35.66, 64.61 5.49 M7.57 72.36 C23.86 52.77, 40.82 32.55, 67.4 4.05 M9.59 78.6 C21.66 63, 36.06 48.95, 71.76 7.03 M10.08 76.55 C27.55 55.62, 45.62 35.85, 70.49 7 M12.56 81.85 C25.42 62.46, 40.04 46.55, 72.17 9.63 M11.06 79.79 C28.06 60.16, 44.33 40.26, 73.94 7.75 M13.55 82.49 C28.83 65.98, 48.28 43.76, 76.92 11.53 M14.8 84.16 C33.23 60.15, 53.34 38.08, 77.01 9.5 M18.1 87.31 C40.08 56.47, 62.85 30.47, 80.4 12.36 M15.8 86.08 C37.59 61.7, 60.84 34.46, 80.7 12.46 M19 88.26 C40.74 67.47, 58.92 43.28, 83.23 13.91 M19.34 89.69 C44.04 60.94, 70.07 31.37, 84.33 14.92 M24.66 90.68 C46.24 63.97, 68.7 37.2, 88.49 16.36 M23.39 91.54 C41.48 71.33, 57.27 52.46, 87.46 15.92 M26.62 93.33 C42.62 75.25, 55.76 56.91, 91.37 20.55 M25.78 92.9 C44.69 72.7, 64.26 51.51, 91.05 19.89 M29.13 94.58 C54.77 68.16, 76.36 39.34, 89.98 24.69 M29.39 94.36 C49.44 73.98, 66.44 53.75, 91.98 23.72 M33.42 96.74 C47.73 82.49, 62.82 64.22, 92.32 25.67 M34.06 96.57 C55.92 72.5, 76.96 48.57, 93.62 28.4 M36.63 98.74 C60.32 74.26, 79.82 54.48, 97.25 30.51 M37.14 99.24 C54.89 79.32, 74.61 58.8, 96.4 30.94 M40.66 99.17 C55.88 83.45, 65.33 69.82, 99.98 34.12 M41.95 98.58 C59.45 80.37, 76.18 63.41, 98.97 34.44 M49.2 99.75 C62.61 81.39, 76.76 66.6, 99.71 40.34 M48.46 99.18 C68.17 76.49, 88.85 52.13, 101.44 39.52 M53.89 98.89 C65.67 88.12, 73.58 74.8, 99.93 45.65 M53.06 97.85 C64.12 87.68, 74.24 77.45, 101.28 44.38 M58.61 99.36 C71.02 84.02, 84.02 72.64, 100.47 49.9 M58.48 99.78 C74.3 82.44, 89.18 65.6, 101.07 49.98 M64.37 99.36 C78.85 81.75, 90.01 65.78, 99.33 56.12 M62.3 99.9 C77.88 84.17, 91.11 66.99, 99.88 56.12 M72.13 92.65 C79.7 86.54, 88.47 76.42, 98.79 63.47 M73.38 93.43 C80.92 86.16, 85.53 79.8, 99.02 64.85"
fill="none"
stroke="#15aabf"
stroke-width="0.5"
/>
<path
d="M38.1 1.46 C45.72 -1.06, 55.49 -0.08, 63.58 2.19 C71.68 4.46, 80.88 9.29, 86.67 15.09 C92.46 20.89, 96.33 29.02, 98.32 36.99 C100.32 44.97, 101 54.87, 98.62 62.96 C96.24 71.05, 90.17 79.66, 84.03 85.55 C77.89 91.43, 69.57 96.06, 61.79 98.28 C54 100.51, 45.12 100.97, 37.32 98.91 C29.52 96.84, 21.11 92.03, 14.99 85.89 C8.88 79.75, 2.75 70.16, 0.63 62.05 C-1.48 53.94, -0.22 45.19, 2.3 37.23 C4.82 29.28, 9.28 20.51, 15.77 14.3 C22.25 8.1, 36.21 2.25, 41.23 0.02 C46.25 -2.21, 45.49 0.09, 45.88 0.91 M40.94 1.53 C48.29 -0.28, 59.04 0.38, 66.96 3.27 C74.89 6.16, 83.12 12.22, 88.48 18.88 C93.85 25.53, 97.82 35.15, 99.18 43.21 C100.54 51.28, 99.41 59.58, 96.65 67.29 C93.89 74.99, 88.87 84.03, 82.63 89.47 C76.39 94.91, 67.44 98.55, 59.2 99.93 C50.97 101.3, 41.25 100.52, 33.2 97.7 C25.15 94.87, 16.16 89.68, 10.9 82.99 C5.64 76.3, 2.84 65.86, 1.64 57.57 C0.45 49.28, 0.99 40.72, 3.74 33.24 C6.5 25.76, 11.77 18.2, 18.18 12.7 C24.59 7.2, 38.36 1.99, 42.22 0.24 C46.09 -1.5, 41.49 1.56, 41.37 2.2"
fill="none"
stroke="#000000"
stroke-width="1"
/>
</g>
</svg>
`;
exports[`exportToSvg with elements that have a link 1`] = `
"
<!-- svg-source:excalidraw -->
<defs>
<style class=\\"style-fonts\\">
@font-face {
font-family: \\"Virgil\\";
src: url(\\"https://excalidraw.com/Virgil.woff2\\");
}
@font-face {
font-family: \\"Cascadia\\";
src: url(\\"https://excalidraw.com/Cascadia.woff2\\");
}
</style>
</defs>
<a href=\\"excalidraw.com\\"><g stroke-linecap=\\"round\\" transform=\\"translate(10 10) rotate(0 107 107)\\"><path d=\\"M0 0 C0 0, 0 0, 0 0 M0 0 C0 0, 0 0, 0 0 M-0.81 6.83 C1.42 4.82, 3.76 1.52, 5.21 0.19 M-0.15 6.66 C1.8 4.06, 3.47 2.78, 5.22 0.73 M-0.29 10.96 C2.44 8.61, 6.86 4.4, 10.93 -0.91 M0.52 11.4 C3.45 8.64, 6.67 5.66, 10.55 0.52 M-0.73 16.51 C7.35 10.86, 13.5 3, 17.44 0.95 M0.2 18.45 C5.73 11.79, 11.18 5.08, 16.02 -0.18 M0.75 25.53 C5.82 17, 10.04 11.07, 20.53 0.11 M0.63 24.62 C6.15 16.7, 12.35 9.33, 21.67 -0.92 M-0.46 31.29 C10.67 19.56, 20.95 6.14, 26.3 0.97 M0.19 30.33 C6.15 22.94, 12.8 16.86, 26.48 0.56 M0.06 38.68 C9.21 29.05, 14.84 21.35, 32.64 0.53 M0.13 37.62 C11.7 22.94, 22.8 8.94, 31.86 0.17 M1.97 42.03 C14.26 29.52, 23.97 12.83, 36.26 1.93 M0.5 42.42 C7.49 34.15, 14.87 25.57, 36.32 -0.12 M-1.55 47.05 C9.52 36.22, 20.47 27.66, 42.25 0.23 M0.07 48.87 C15.17 30.66, 32.72 11.39, 42.55 -0.3 M1 53.34 C15.85 39.16, 30.2 22.36, 47.03 0.12 M0.83 54.24 C13.32 41.61, 24.32 26.03, 48.09 -0.05 M-1.51 60.18 C18.44 42.68, 33.89 21.16, 51.91 1.7 M0.58 61.04 C19.82 38.42, 41.63 15.34, 52.4 -0.74 M-2 68.97 C17.08 50.31, 33.78 31.07, 58 -1.79 M-0.57 67.89 C12.79 53.01, 23.57 38.56, 57.54 0.78 M-0.94 73.26 C17.3 51.99, 37.15 29.16, 63.79 1.79 M-0.34 73.88 C13.12 57.81, 25.23 44.29, 63.24 0.24 M-0.02 80.75 C25.47 53.17, 50.04 23.22, 68.13 1.24 M-0.31 79 C13.15 62.83, 27.89 46.91, 69.58 0.16 M-1.36 83.81 C22.43 62.66, 42.64 36.29, 75.7 -0.26 M0.49 84.94 C20.19 61.39, 38.84 39.35, 74.08 -0.14 M-0.44 93.19 C29.84 56.59, 58.57 21.34, 80.05 0.63 M0.23 91.29 C16.75 73.26, 34.07 51.65, 80.34 -0.29 M-1.32 96.52 C29.7 64.08, 56.68 31.83, 85.06 1.15 M-1.23 98.35 C28.8 63.78, 59.61 29.8, 85.15 -0.85 M1.68 104.37 C24.69 72.49, 52 43.21, 91.99 -1.81 M-0.48 103.54 C31.96 64.64, 64.99 27.22, 89.13 0.87 M-1.77 108.18 C36.54 67.37, 72.5 22.54, 96.92 -1.99 M-0.63 109.78 C22.47 82.36, 45.16 56.53, 95.84 -1.07 M-1.12 114.79 C38.49 70.57, 74.74 30, 101.81 -1.93 M1.19 116.33 C38.03 73.29, 76.06 29.97, 100.42 0.88 M2 120.2 C36.47 78.86, 73.59 37.62, 107.95 0.68 M0.39 120.97 C29.7 88.16, 58.99 53.35, 106.73 -0.13 M-1.32 128.06 C41.12 75.45, 86.81 26, 110.99 -1.18 M-0.57 128.82 C35.82 86.5, 72.74 44.1, 111.91 0.79 M-1.02 135.64 C43.91 82.98, 87.98 32.05, 117.79 -1.37 M-0.27 134.74 C26.27 106.76, 50.22 76.9, 116.93 1.16 M-1.8 139.9 C35.21 104.38, 65.53 62.78, 120.66 1.37 M-0.43 139.71 C38.55 95.61, 78.01 50.56, 122.46 -0.53 M1.76 147.91 C29.11 117.4, 55.37 85.99, 127.68 1.48 M0.53 145.69 C46.44 94.62, 91.7 39.92, 126.74 -0.41 M0.17 150.85 C33.17 115.83, 61.4 80.26, 131.64 0.9 M0.15 151.84 C53.25 90.23, 106.14 30.74, 132.16 -0.36 M-1.84 157.7 C37.59 114.01, 76.78 70.61, 136.63 -0.45 M0.35 158.99 C30.36 122.85, 60.89 88, 137.61 0.03 M-0.23 166.11 C29.43 128.1, 58.73 93.84, 143.89 -0.53 M-0.32 164.8 C28.62 130.08, 57.48 96.97, 144 -0.28 M0.58 169.48 C50.77 111.65, 102.4 55.59, 147.57 0.38 M0.18 171.37 C41.33 123.45, 81.86 77.61, 148.81 0.27 M-0.43 175.5 C42.41 129.13, 83.17 82.4, 153.98 0.49 M-0.38 176.58 C56.14 112.56, 110.58 48.82, 153.05 0 M0.7 184.05 C39.63 137.27, 77.83 89.07, 159.24 -1.15 M-0.04 183.65 C61.15 113.46, 120.25 43.45, 159.1 0.14 M0.78 189.08 C63.86 116.64, 126.59 42.93, 165.06 -0.83 M-0.1 189.24 C43.16 138.18, 87.83 86.83, 164.16 0.56 M1.24 193.84 C36.84 154.67, 72.19 113.57, 170.32 -1.11 M-0.39 194.15 C64.21 119.86, 128.3 45.54, 169.93 0.91 M-0.29 202.73 C49.19 146.43, 96.87 92.17, 176.44 -0.47 M0.13 200.67 C52.92 138.41, 108.19 74.96, 174.6 -0.26 M1.16 206.55 C59.57 139.38, 118.88 71.01, 179.33 -0.46 M-0.07 207.43 C53.03 145.16, 107.35 82.74, 180.4 0.42 M0.22 213.68 C60.95 141.62, 123.88 71.22, 187.21 0.77 M0.6 214.05 C46.1 157.63, 93.55 102.73, 185.97 0.53 M1.26 216.37 C45.53 168.31, 87.98 118.47, 190.76 -1.23 M3.04 216.09 C67.52 139.61, 132.76 63.4, 190.6 -0.35 M7.95 217.48 C67.06 150.79, 124.44 83.38, 196.32 1.03 M7.93 216.35 C53.89 161.92, 100.46 109.21, 196.09 -0.51 M12.62 217.33 C58.21 163, 105.7 107.92, 202.43 -0.59 M13.54 216.66 C71.71 147.52, 130.4 81.02, 201.49 0.82 M18.27 217.27 C66.39 160.5, 115.21 104.07, 208.36 0.27 M18.01 215.72 C58.01 168.33, 99.25 121.93, 206.76 -0.82 M24.9 216.54 C74.66 158.72, 125.24 98.12, 212.06 0.05 M23.39 216.76 C89.76 140.49, 156.61 64.23, 211.91 -0.02 M28.87 215.01 C94.99 140.87, 162.5 64.39, 216.64 2.5 M28.76 215.55 C79.01 159.87, 128.27 103.38, 215.68 1.25 M32.95 216.11 C83.19 160.31, 131.85 106.05, 216.52 8.63 M33.94 217.11 C75.45 168.61, 117.47 121.55, 216.54 8.14 M39.78 217.56 C92.26 159.75, 140.57 102.37, 215.58 12.68 M40.11 216.11 C90.9 157.88, 140.49 99.7, 215.33 14 M43.47 216.97 C104.46 148.92, 163.67 79.54, 215.48 18.1 M44.41 216.74 C89.24 164.57, 133.58 113.45, 215.55 19.53 M50.78 215.1 C93.5 164.92, 139.86 112.9, 214.41 26.53 M49.78 215.99 C110.29 149.66, 168.81 81.69, 215.73 26.76 M57.12 215.58 C107.36 155.81, 157.92 97.78, 215.19 31.92 M54.97 216.03 C113.66 149.14, 173.56 80.85, 215.38 32.06 M61.3 215.31 C95.1 175.75, 132.1 134.8, 216.98 38.89 M61.19 216.77 C109.52 160.05, 158.35 103.94, 216.2 38.35 M67.47 216.77 C115.11 158.21, 167.71 97.2, 216.63 45.21 M66.77 216.96 C102.08 174.52, 137.46 133.67, 215.1 44.3 M70.35 215.08 C103.39 179.45, 138.17 141.98, 216.94 49.42 M72.29 216.59 C103.33 179.45, 132.1 146.13, 215.3 50.78 M77.48 217.53 C112.79 176.25, 148.92 136.21, 214.87 56.96 M76.92 216.34 C126.01 159.84, 176.06 104.61, 216.09 56.89 M83.65 216.59 C109.9 184.76, 137.67 151.42, 216.82 64.24 M81.86 216.8 C115.56 177.43, 148.43 139.03, 215.35 63.31 M86.45 216.6 C117.96 179.57, 150.68 145.05, 215.64 67.24 M86.76 215.76 C133.59 164.04, 179.87 111.6, 216.32 67.66 M92.5 217.18 C130.08 175.3, 164.37 136.62, 217.67 75.31 M93.31 216.93 C121.12 183.96, 149.71 151.9, 216.67 74.37 M97.31 214.67 C122.26 188.24, 148.41 160.47, 217.8 78.71 M97.27 217.16 C133.41 175.31, 167.83 132.89, 216.35 79.87 M102.05 215.76 C128.77 182.73, 159.47 152.36, 217.64 85.73 M103.92 216.03 C140.06 172.81, 177.77 130.15, 216.44 86.54 M108.77 215.29 C145.82 169.8, 184.54 127.33, 214.48 93.3 M108.6 216.14 C152.4 169.17, 193.64 120.21, 215.53 93.61 M113.85 217.99 C138.74 189.67, 160.26 165.2, 215.6 100.97 M113.85 215.19 C144.51 180.53, 176.69 143.07, 215.68 99.56 M119.06 216.26 C139.68 192.15, 161.93 164.32, 216.54 104.97 M120.04 216.13 C141.97 189.71, 164.98 164.4, 216.3 104.47 M124.31 216.62 C147.59 192.15, 170.4 161.51, 217.92 112.68 M123.84 216.01 C151.85 183.74, 178.95 152.19, 216.63 110.91 M130.04 217.74 C153.81 189.32, 176.55 163.35, 216.49 116.35 M130.09 216.38 C146.84 196.06, 166.21 175.33, 216.35 118.08 M135.41 216.47 C160.47 188.02, 182.14 159.88, 213.93 123.66 M135.78 217.64 C155.48 194.76, 172.71 172.66, 216.06 124.66 M139.2 218.28 C157.86 195.92, 177.77 173.69, 215.14 127.67 M140.43 215.93 C161.4 191.88, 182.03 169.94, 215.2 129.17 M146.79 215.06 C162.71 194.09, 180.79 177.42, 214.55 136.84 M144.79 217.28 C160.2 199.12, 174.78 183.05, 215.91 136.41 M151.66 214.81 C171.28 196.29, 187.11 175.48, 216.92 141.52 M151.91 215.67 C176.44 188.45, 199.88 160.32, 215.56 142.26 M154.38 215.47 C172.69 198.01, 192.07 175.16, 216.36 147.74 M155.82 217.21 C174.84 196.04, 193.76 174.8, 215.32 147.85 M160.14 214.61 C179.82 197.41, 195.96 177.17, 217.2 155.66 M162.6 216.26 C174.04 201, 186.86 187.65, 214.67 154.44 M165.72 215.2 C184.79 196.83, 203.71 176.89, 216.23 161.56 M167.04 217.53 C178.06 204.41, 186.16 194.48, 215.28 159.73 M173.01 215.35 C189.21 198.76, 204.39 179.52, 216.99 167.92 M171.74 216.2 C188.55 197.71, 202.6 180.81, 214.93 166.35 M176 218.1 C188.62 206.57, 198.94 193.03, 214.63 173.83 M177.77 216.11 C190.55 201.92, 202.86 186.55, 215.97 172.6 M182.26 217.09 C193.97 201.5, 207.69 185.56, 214.91 176.8 M183.75 215.8 C191.36 207.78, 198.34 197.48, 215.95 178.7 M187.99 218.4 C199.34 205.7, 207.8 191.99, 215.03 183.22 M188.53 216.69 C197.17 205.82, 204.83 195.35, 216.1 185.58 M195.49 214.23 C197.72 209.17, 202.2 205.99, 217.9 190.4 M194.25 215.18 C202.02 207.92, 209.16 198.59, 215.2 191.28 M200.15 216.71 C206.55 209.28, 212.55 200.97, 214.47 196.53 M199.03 216.79 C205.41 210.03, 212.23 201.38, 215.53 197.34 M203.99 215.64 C207.37 213.36, 210.04 206.68, 216.48 203.13 M204.08 216.24 C207 212.46, 211.61 208.42, 215.41 201.74 M209.93 216.23 C210.58 213.66, 212.88 213.24, 215.79 209.03 M209.77 216.09 C211.32 214.48, 213.4 211.72, 215.64 208.76\\" stroke=\\"#15aabf\\" stroke-width=\\"0.5\\" fill=\\"none\\"></path><path d=\\"M-0.39 -0.88 C55.46 -0.97, 113.94 -0.3, 214.26 0.61 M-0.49 0.4 C84.22 -0.65, 169.11 -0.38, 213.87 0.66 M212.35 -0.69 C216.14 81.33, 216.66 160.36, 212.82 212.88 M213.44 -0.28 C214.34 52.63, 212.93 106.93, 213.51 214 M215.36 213.92 C153.36 215.01, 94.72 215.24, 0.66 215.17 M214.59 213.78 C136.22 216.39, 57.75 216.64, 0.1 213.77 M-1.71 215.7 C0.69 160.6, -0.19 109.87, -0.18 1.75 M0.58 213.93 C-0.62 147.47, -0.5 79.36, 0.52 0\\" stroke=\\"#000000\\" stroke-width=\\"1\\" fill=\\"none\\"></path></g></a>"
`;
exports[`exportToSvg with exportEmbedScene 1`] = `
"
<!-- svg-source:excalidraw -->
<!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1SsW7CMFx1MDAxMN35iihdkUjSQChcdTAwMWItVVWpalx1MDAwN1x1MDAwNqRWXHUwMDFkTHxJrFx1MDAxONvEXHUwMDBlXHUwMDEwIf69tlx1MDAwM3GJXHUwMDE4O9aDpXt+7+58945cdTAwMDPP81UjwJ95Plx1MDAxY1JEXHSu0N5cdTAwMWZcdTAwMWF8XHUwMDA3lSSc6afIxpLXVWqZhVJiNlx1MDAxYVGuXHUwMDA1XHUwMDA1l6rlXHUwMDAzhVxyMCU140vHnne0t34h2Kh2q2r7Mc9KwnC0TTfJ22L+8mmllnTQnDiMu7gxhe+TLt5cdTAwMTOsXG6NhUHQYVx1MDAwNZC8UD1cdTAwMTCxnJo2XHUwMDFkXCJVxUt44pRXppG7wFx1MDAxZVd6jdIyr3jNsOOEY4TWmeNkhNKlamg7XHUwMDAwlFx1MDAxNnVcdTAwMDV+r8Lq0mJcdTAwMGbvdJLrXHUwMDAxO5UumVx1MDAxN1xmpLzScIFSoprer0x/4lx1MDAxNdvpfv/OwPA5XHUwMDAzqyl1hVx1MDAwMbDNXHUwMDEwh5Nx8lx1MDAxMEy7XHUwMDE3t9YwXG766DtndsVhOJ1cdTAwMDZBXHUwMDFjJZOOQeRCb1jZtFx1MDAxOaJcdTAwMTLc+ExcdTAwMTPPbvtXjdRcdTAwMDKjVuR+SFx0K/s8babyRu6LOTFBXHUwMDFizrBv8dPw31///vpTf1x1MDAwMaVESDj7S992XHUwMDA2Plx1MDAxMmKpdH5Nad3m71xi7Fx1MDAxZm/sM7PH6K07zT7BNHs8XHJOP7VXYMUifQ==<!-- payload-end -->
<defs>
<style class=\\"style-fonts\\">
@font-face {
font-family: \\"Virgil\\";
src: url(\\"https://excalidraw.com/Virgil.woff2\\");
}
@font-face {
font-family: \\"Cascadia\\";
src: url(\\"https://excalidraw.com/Cascadia.woff2\\");
}
</style>
</defs>
<g stroke-linecap=\\"round\\" transform=\\"translate(10 10) rotate(0 50 50)\\"><path d=\\"M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M1.31 55.08 C15.31 40.32, 29.59 22.37, 41.3 9.81 M2.95 54.67 C16.06 38.64, 28.38 26.08, 41.31 11.16 M5.17 55.28 C18.64 40.54, 34.59 23.3, 53.31 1.2 M6.19 55.83 C19.7 40.85, 33.94 25.36, 52.84 2.99 M8.12 57.33 C28.32 38.18, 46.32 16.69, 57.78 5.54 M9.05 59.26 C25.33 39.84, 41.83 20.42, 56.36 4.41 M12.23 63.33 C23.99 47.5, 34.76 34.04, 58.25 7.72 M12.1 62.42 C25.64 45.74, 39.58 29.47, 59.39 6.7 M14.29 65.31 C33.6 44.37, 51.89 21.73, 61.4 11.6 M14.95 64.35 C25.42 51.41, 36.81 39.88, 61.57 11.19 M17.44 69.69 C30.26 56.06, 39.46 44.26, 65.11 14.18 M17.51 68.63 C34.43 47.57, 51.04 27.25, 64.33 13.82 M21.98 70.02 C37.96 53.4, 51.32 32.51, 66.76 17.85 M20.5 70.41 C29.55 59.82, 39.04 48.82, 66.82 15.79 M21.73 71.26 C33.76 59.36, 45.61 49.75, 69.47 19.91 M23.35 73.09 C39.91 53.14, 58.94 32.17, 69.77 19.39 M26.91 74.54 C41.56 60.59, 55.7 44.03, 72.29 22.07 M26.74 75.44 C39.06 62.99, 49.89 47.62, 73.34 21.9 M27.68 77.61 C45.49 62.49, 58.86 43.36, 74.53 26.67 M29.77 78.46 C46.48 58.69, 65.8 38.46, 75.03 24.23 M29.82 83.37 C45.64 68.39, 59.09 52.88, 78 26.2 M31.24 82.29 C42.16 70.24, 50.48 58.61, 77.54 28.77 M33.5 84.64 C46.6 69.19, 61.43 52.15, 81.17 32.8 M34.1 85.27 C44.17 73.12, 52.8 63.6, 80.62 31.25 M37.69 88.37 C54.96 70.16, 71.4 49.55, 82.89 35.26 M37.41 86.61 C46.27 76.03, 56.22 65.63, 84.34 34.18 M38.98 88.4 C54.78 76.48, 66.88 59.43, 87.83 36.78 M40.83 89.54 C52.97 74.67, 64.21 61.17, 86.21 36.91 M43.18 94 C60.91 72.19, 77.04 51.45, 90.21 39.94 M43.86 92.11 C52.94 82.13, 62.98 68.89, 90.51 39.02 M44.93 94.32 C62.61 77.05, 76.42 59.94, 91.95 44.23 M45.02 96.15 C61.2 76.98, 78.3 58.77, 92.03 42.23 M50.55 99.15 C60.63 81.82, 75.04 67.37, 96.9 43.53 M48.39 98.32 C65.04 78.28, 81.92 59.44, 94.04 46.22 M50.38 99.19 C69.54 81.19, 85.85 58.94, 99.21 46.38 M51.53 100.79 C62.45 87.27, 73.41 74.93, 98.13 47.3\\" stroke=\\"#15aabf\\" stroke-width=\\"0.5\\" fill=\\"none\\"></path><path d=\\"M50.55 -1.01 C62.82 12.44, 78.03 26.68, 100.3 51.7 M50.44 0.46 C69.95 19.26, 89.63 39.73, 99.86 51.76 M98.12 50.21 C82.92 71.13, 65.15 88.19, 49.66 98.72 M99.37 50.68 C88.57 62.94, 74.79 76.37, 50.44 100 M52.55 99.9 C35.86 87.61, 23.16 74.12, 0.75 52.33 M51.67 99.75 C32.82 83.31, 13.73 65.72, 0.11 50.74 M-1.95 52.94 C13.84 37.62, 25.27 26.82, 50.8 2 M0.66 50.92 C16.45 35.71, 32.61 18.7, 51.59 0.01\\" stroke=\\"#000000\\" stroke-width=\\"1\\" fill=\\"none\\"></path></g><g stroke-linecap=\\"round\\" transform=\\"translate(10 10) rotate(0 50 50)\\"><path d=\\"M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M5.51 34 C13.17 23.26, 20.2 13.31, 28.19 8.96 M5.48 33.35 C12.13 25.41, 19.79 15.96, 26.45 7.6 M5.56 37.62 C16.59 25.63, 28.15 12.22, 38.46 2.39 M5.11 40.5 C16.67 26.96, 28.16 13.15, 36.64 1.59 M4.66 45.59 C13.25 35.02, 21.41 28.15, 39.56 4.69 M4.57 46.97 C11.96 37.32, 20.9 26.56, 40.44 3.42 M5.51 50.51 C13.89 43.35, 21.63 34.54, 46.26 4.75 M4.27 51.77 C16.66 37.46, 28.38 22.96, 44.97 4.33 M0.17 60.65 C18.76 40.92, 37.97 17.6, 49.71 5.16 M0.46 61.18 C19.32 40.86, 37.47 20.77, 50.84 4.21 M2.75 65.39 C21.01 45.29, 37.92 25.46, 57.52 4.43 M3.54 66.52 C18.04 48.78, 32.49 30.26, 55.79 4.21 M4.72 71.04 C27.28 44.43, 49.83 20.12, 62.05 5.19 M4.98 68.42 C25.81 45.48, 47.44 20.41, 60.72 5.33 M5.52 72.07 C22.65 55.25, 37.54 35.66, 64.61 5.49 M7.57 72.36 C23.86 52.77, 40.82 32.55, 67.4 4.05 M9.59 78.6 C21.66 63, 36.06 48.95, 71.76 7.03 M10.08 76.55 C27.55 55.62, 45.62 35.85, 70.49 7 M12.56 81.85 C25.42 62.46, 40.04 46.55, 72.17 9.63 M11.06 79.79 C28.06 60.16, 44.33 40.26, 73.94 7.75 M13.55 82.49 C28.83 65.98, 48.28 43.76, 76.92 11.53 M14.8 84.16 C33.23 60.15, 53.34 38.08, 77.01 9.5 M18.1 87.31 C40.08 56.47, 62.85 30.47, 80.4 12.36 M15.8 86.08 C37.59 61.7, 60.84 34.46, 80.7 12.46 M19 88.26 C40.74 67.47, 58.92 43.28, 83.23 13.91 M19.34 89.69 C44.04 60.94, 70.07 31.37, 84.33 14.92 M24.66 90.68 C46.24 63.97, 68.7 37.2, 88.49 16.36 M23.39 91.54 C41.48 71.33, 57.27 52.46, 87.46 15.92 M26.62 93.33 C42.62 75.25, 55.76 56.91, 91.37 20.55 M25.78 92.9 C44.69 72.7, 64.26 51.51, 91.05 19.89 M29.13 94.58 C54.77 68.16, 76.36 39.34, 89.98 24.69 M29.39 94.36 C49.44 73.98, 66.44 53.75, 91.98 23.72 M33.42 96.74 C47.73 82.49, 62.82 64.22, 92.32 25.67 M34.06 96.57 C55.92 72.5, 76.96 48.57, 93.62 28.4 M36.63 98.74 C60.32 74.26, 79.82 54.48, 97.25 30.51 M37.14 99.24 C54.89 79.32, 74.61 58.8, 96.4 30.94 M40.66 99.17 C55.88 83.45, 65.33 69.82, 99.98 34.12 M41.95 98.58 C59.45 80.37, 76.18 63.41, 98.97 34.44 M49.2 99.75 C62.61 81.39, 76.76 66.6, 99.71 40.34 M48.46 99.18 C68.17 76.49, 88.85 52.13, 101.44 39.52 M53.89 98.89 C65.67 88.12, 73.58 74.8, 99.93 45.65 M53.06 97.85 C64.12 87.68, 74.24 77.45, 101.28 44.38 M58.61 99.36 C71.02 84.02, 84.02 72.64, 100.47 49.9 M58.48 99.78 C74.3 82.44, 89.18 65.6, 101.07 49.98 M64.37 99.36 C78.85 81.75, 90.01 65.78, 99.33 56.12 M62.3 99.9 C77.88 84.17, 91.11 66.99, 99.88 56.12 M72.13 92.65 C79.7 86.54, 88.47 76.42, 98.79 63.47 M73.38 93.43 C80.92 86.16, 85.53 79.8, 99.02 64.85\\" stroke=\\"#15aabf\\" stroke-width=\\"0.5\\" fill=\\"none\\"></path><path d=\\"M38.1 1.46 C45.72 -1.06, 55.49 -0.08, 63.58 2.19 C71.68 4.46, 80.88 9.29, 86.67 15.09 C92.46 20.89, 96.33 29.02, 98.32 36.99 C100.32 44.97, 101 54.87, 98.62 62.96 C96.24 71.05, 90.17 79.66, 84.03 85.55 C77.89 91.43, 69.57 96.06, 61.79 98.28 C54 100.51, 45.12 100.97, 37.32 98.91 C29.52 96.84, 21.11 92.03, 14.99 85.89 C8.88 79.75, 2.75 70.16, 0.63 62.05 C-1.48 53.94, -0.22 45.19, 2.3 37.23 C4.82 29.28, 9.28 20.51, 15.77 14.3 C22.25 8.1, 36.21 2.25, 41.23 0.02 C46.25 -2.21, 45.49 0.09, 45.88 0.91 M40.94 1.53 C48.29 -0.28, 59.04 0.38, 66.96 3.27 C74.89 6.16, 83.12 12.22, 88.48 18.88 C93.85 25.53, 97.82 35.15, 99.18 43.21 C100.54 51.28, 99.41 59.58, 96.65 67.29 C93.89 74.99, 88.87 84.03, 82.63 89.47 C76.39 94.91, 67.44 98.55, 59.2 99.93 C50.97 101.3, 41.25 100.52, 33.2 97.7 C25.15 94.87, 16.16 89.68, 10.9 82.99 C5.64 76.3, 2.84 65.86, 1.64 57.57 C0.45 49.28, 0.99 40.72, 3.74 33.24 C6.5 25.76, 11.77 18.2, 18.18 12.7 C24.59 7.2, 38.36 1.99, 42.22 0.24 C46.09 -1.5, 41.49 1.56, 41.37 2.2\\" stroke=\\"#000000\\" stroke-width=\\"1\\" fill=\\"none\\"></path></g>"
`;
| src/tests/scene/__snapshots__/export.test.ts.snap | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0002100031852023676,
0.0001772511750459671,
0.00016474389121867716,
0.00017628053319640458,
0.000010970930816256441
] |
{
"id": 1,
"code_window": [
" mutateElement(textElement, {\n",
" containerId: container.id,\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.CENTER,\n",
" boundElements: null,\n",
" });\n",
" redrawTextBoundingBox(textElement, container);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 261
} | import {
BOUND_TEXT_PADDING,
ROUNDNESS,
TEXT_ALIGN,
VERTICAL_ALIGN,
} from "../constants";
import { getNonDeletedElements, isTextElement, newElement } from "../element";
import { mutateElement } from "../element/mutateElement";
import {
computeContainerDimensionForBoundText,
getBoundTextElement,
measureText,
redrawTextBoundingBox,
} from "../element/textElement";
import {
getOriginalContainerHeightFromCache,
resetOriginalContainerCache,
} from "../element/textWysiwyg";
import {
hasBoundTextElement,
isTextBindableContainer,
isUsingAdaptiveRadius,
} from "../element/typeChecks";
import {
ExcalidrawElement,
ExcalidrawLinearElement,
ExcalidrawTextContainer,
ExcalidrawTextElement,
} from "../element/types";
import { getSelectedElements } from "../scene";
import { getFontString } from "../utils";
import { register } from "./register";
export const actionUnbindText = register({
name: "unbindText",
contextItemLabel: "labels.unbindText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return selectedElements.some((element) => hasBoundTextElement(element));
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
selectedElements.forEach((element) => {
const boundTextElement = getBoundTextElement(element);
if (boundTextElement) {
const { width, height } = measureText(
boundTextElement.originalText,
getFontString(boundTextElement),
);
const originalContainerHeight = getOriginalContainerHeightFromCache(
element.id,
);
resetOriginalContainerCache(element.id);
mutateElement(boundTextElement as ExcalidrawTextElement, {
containerId: null,
width,
height,
text: boundTextElement.originalText,
});
mutateElement(element, {
boundElements: element.boundElements?.filter(
(ele) => ele.id !== boundTextElement.id,
),
height: originalContainerHeight
? originalContainerHeight
: element.height,
});
}
});
return {
elements,
appState,
commitToHistory: true,
};
},
});
export const actionBindText = register({
name: "bindText",
contextItemLabel: "labels.bindText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
if (selectedElements.length === 2) {
const textElement =
isTextElement(selectedElements[0]) ||
isTextElement(selectedElements[1]);
let bindingContainer;
if (isTextBindableContainer(selectedElements[0])) {
bindingContainer = selectedElements[0];
} else if (isTextBindableContainer(selectedElements[1])) {
bindingContainer = selectedElements[1];
}
if (
textElement &&
bindingContainer &&
getBoundTextElement(bindingContainer) === null
) {
return true;
}
}
return false;
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
let textElement: ExcalidrawTextElement;
let container: ExcalidrawTextContainer;
if (
isTextElement(selectedElements[0]) &&
isTextBindableContainer(selectedElements[1])
) {
textElement = selectedElements[0];
container = selectedElements[1];
} else {
textElement = selectedElements[1] as ExcalidrawTextElement;
container = selectedElements[0] as ExcalidrawTextContainer;
}
mutateElement(textElement, {
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
});
mutateElement(container, {
boundElements: (container.boundElements || []).concat({
type: "text",
id: textElement.id,
}),
});
redrawTextBoundingBox(textElement, container);
return {
elements: pushTextAboveContainer(elements, container, textElement),
appState: { ...appState, selectedElementIds: { [container.id]: true } },
commitToHistory: true,
};
},
});
const pushTextAboveContainer = (
elements: readonly ExcalidrawElement[],
container: ExcalidrawElement,
textElement: ExcalidrawTextElement,
) => {
const updatedElements = elements.slice();
const textElementIndex = updatedElements.findIndex(
(ele) => ele.id === textElement.id,
);
updatedElements.splice(textElementIndex, 1);
const containerIndex = updatedElements.findIndex(
(ele) => ele.id === container.id,
);
updatedElements.splice(containerIndex + 1, 0, textElement);
return updatedElements;
};
const pushContainerBelowText = (
elements: readonly ExcalidrawElement[],
container: ExcalidrawElement,
textElement: ExcalidrawTextElement,
) => {
const updatedElements = elements.slice();
const containerIndex = updatedElements.findIndex(
(ele) => ele.id === container.id,
);
updatedElements.splice(containerIndex, 1);
const textElementIndex = updatedElements.findIndex(
(ele) => ele.id === textElement.id,
);
updatedElements.splice(textElementIndex, 0, container);
return updatedElements;
};
export const actionCreateContainerFromText = register({
name: "createContainerFromText",
contextItemLabel: "labels.createContainerFromText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return selectedElements.length === 1 && isTextElement(selectedElements[0]);
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
const updatedElements = elements.slice();
if (selectedElements.length === 1 && isTextElement(selectedElements[0])) {
const textElement = selectedElements[0];
const container = newElement({
type: "rectangle",
backgroundColor: appState.currentItemBackgroundColor,
boundElements: [
...(textElement.boundElements || []),
{ id: textElement.id, type: "text" },
],
angle: textElement.angle,
fillStyle: appState.currentItemFillStyle,
strokeColor: appState.currentItemStrokeColor,
roughness: appState.currentItemRoughness,
strokeWidth: appState.currentItemStrokeWidth,
strokeStyle: appState.currentItemStrokeStyle,
roundness:
appState.currentItemRoundness === "round"
? {
type: isUsingAdaptiveRadius("rectangle")
? ROUNDNESS.ADAPTIVE_RADIUS
: ROUNDNESS.PROPORTIONAL_RADIUS,
}
: null,
opacity: 100,
locked: false,
x: textElement.x - BOUND_TEXT_PADDING,
y: textElement.y - BOUND_TEXT_PADDING,
width: computeContainerDimensionForBoundText(
textElement.width,
"rectangle",
),
height: computeContainerDimensionForBoundText(
textElement.height,
"rectangle",
),
groupIds: textElement.groupIds,
});
// update bindings
if (textElement.boundElements?.length) {
const linearElementIds = textElement.boundElements
.filter((ele) => ele.type === "arrow")
.map((el) => el.id);
const linearElements = updatedElements.filter((ele) =>
linearElementIds.includes(ele.id),
) as ExcalidrawLinearElement[];
linearElements.forEach((ele) => {
let startBinding = null;
let endBinding = null;
if (ele.startBinding) {
startBinding = { ...ele.startBinding, elementId: container.id };
}
if (ele.endBinding) {
endBinding = { ...ele.endBinding, elementId: container.id };
}
mutateElement(ele, { startBinding, endBinding });
});
}
mutateElement(textElement, {
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
textAlign: TEXT_ALIGN.CENTER,
boundElements: null,
});
redrawTextBoundingBox(textElement, container);
return {
elements: pushContainerBelowText(
[...elements, container],
container,
textElement,
),
appState: {
...appState,
selectedElementIds: {
[container.id]: true,
[textElement.id]: false,
},
},
commitToHistory: true,
};
}
return {
elements: updatedElements,
appState,
commitToHistory: true,
};
},
});
| src/actions/actionBoundText.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.3281983435153961,
0.029456254094839096,
0.0001656407694099471,
0.001898465445265174,
0.07642849534749985
] |
{
"id": 1,
"code_window": [
" mutateElement(textElement, {\n",
" containerId: container.id,\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.CENTER,\n",
" boundElements: null,\n",
" });\n",
" redrawTextBoundingBox(textElement, container);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 261
} | ---
title: Introduction
slug: ../
---
## Try now
Go to [excalidraw.com](https://excalidraw.com) to start sketching.
## How are these docs structured
These docs are focused on developers, and structured in the following way:
- [Introduction](/docs/) — development setup and introduction.
- [@excalidraw/excalidraw](/docs/@excalidraw/excalidraw/installation) — docs for the npm package to help you integrate Excalidraw into your own app.
- Editor — IN PROGRESS. Docs describing the internals of the Excalidraw editor to help in contributing to the codebase.
| dev-docs/docs/introduction/get-started.mdx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017232095706276596,
0.0001705606991890818,
0.00016880044131539762,
0.0001705606991890818,
0.0000017602578736841679
] |
{
"id": 1,
"code_window": [
" mutateElement(textElement, {\n",
" containerId: container.id,\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.CENTER,\n",
" boundElements: null,\n",
" });\n",
" redrawTextBoundingBox(textElement, container);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 261
} | import React, {
useMemo,
useContext,
useLayoutEffect,
useState,
createContext,
} from "react";
export const withUpstreamOverride = <P,>(Component: React.ComponentType<P>) => {
type ContextValue = [boolean, React.Dispatch<React.SetStateAction<boolean>>];
const DefaultComponentContext = createContext<ContextValue>([
false,
() => {},
]);
const ComponentContext: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [isRenderedUpstream, setIsRenderedUpstream] = useState(false);
const contextValue: ContextValue = useMemo(
() => [isRenderedUpstream, setIsRenderedUpstream],
[isRenderedUpstream],
);
return (
<DefaultComponentContext.Provider value={contextValue}>
{children}
</DefaultComponentContext.Provider>
);
};
const DefaultComponent = (
props: P & {
// indicates whether component should render when not rendered upstream
/** @private internal */
__isFallback?: boolean;
},
) => {
const [isRenderedUpstream, setIsRenderedUpstream] = useContext(
DefaultComponentContext,
);
useLayoutEffect(() => {
if (!props.__isFallback) {
setIsRenderedUpstream(true);
return () => setIsRenderedUpstream(false);
}
}, [props.__isFallback, setIsRenderedUpstream]);
if (props.__isFallback && isRenderedUpstream) {
return null;
}
return <Component {...props} />;
};
if (Component.name) {
DefaultComponent.displayName = `${Component.name}_upstreamOverrideWrapper`;
ComponentContext.displayName = `${Component.name}_upstreamOverrideContextWrapper`;
}
return [ComponentContext, DefaultComponent] as const;
};
| src/components/hoc/withUpstreamOverride.tsx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017463973199483007,
0.00017133810615632683,
0.00016691772907506675,
0.00017220780136995018,
0.00000272779675469792
] |
{
"id": 1,
"code_window": [
" mutateElement(textElement, {\n",
" containerId: container.id,\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.CENTER,\n",
" boundElements: null,\n",
" });\n",
" redrawTextBoundingBox(textElement, container);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/actions/actionBoundText.tsx",
"type": "replace",
"edit_start_line_idx": 261
} | # Constants
### FONT_FAMILY
**How to use**
```js
import { FONT_FAMILY } from "@excalidraw/excalidraw";
```
`FONT_FAMILY` contains all the font families used in `Excalidraw` as explained below
| Font Family | Description |
| ----------- | ---------------------- |
| `Virgil` | The `handwritten` font |
| `Helvetica` | The `Normal` Font |
| `Cascadia` | The `Code` Font |
Defaults to `FONT_FAMILY.Virgil` unless passed in `initialData.appState.currentItemFontFamily`.
### THEME
**How to use**
```js
import { THEME } from "@excalidraw/excalidraw";
```
`THEME` contains all the themes supported by `Excalidraw` as explained below
| Theme | Description |
| ------- | ----------------- |
| `LIGHT` | The `light` theme |
| `DARK` | The `Dark` theme |
Defaults to `THEME.LIGHT` unless passed in `initialData.appState.theme`
### MIME_TYPES
[`MIME_TYPES`](https://github.com/excalidraw/excalidraw/blob/master/src/constants.ts#L101) contains all the mime types supported by `Excalidraw`.
**How to use **
```js
import { MIME_TYPES } from "@excalidraw/excalidraw";
```
| dev-docs/docs/@excalidraw/excalidraw/api/constants.mdx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0001733159297145903,
0.0001689037017058581,
0.0001632005732972175,
0.0001687075855443254,
0.0000034686693197727436
] |
{
"id": 2,
"code_window": [
"} from \"../tests/test-utils\";\n",
"import { queryByText } from \"@testing-library/react\";\n",
"\n",
"import { FONT_FAMILY } from \"../constants\";\n",
"import {\n",
" ExcalidrawTextElement,\n",
" ExcalidrawTextElementWithContainer,\n",
"} from \"./types\";\n",
"import { API } from \"../tests/helpers/api\";\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FONT_FAMILY, TEXT_ALIGN, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 12
} | import ReactDOM from "react-dom";
import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys";
import {
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react";
import { FONT_FAMILY } from "../constants";
import {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
} from "./types";
import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const tab = " ";
const mouse = new Pointer("mouse");
describe("textWysiwyg", () => {
describe("start text editing", () => {
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
});
it("should prefer editing selected text element (non-bindable container present)", async () => {
const line = API.createElement({
type: "line",
width: 100,
height: 0,
points: [
[0, 0],
[100, 0],
],
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: line.width / 2 - textSize / 2,
y: -textSize / 2,
width: textSize,
height: textSize,
});
h.elements = [text, line];
API.setSelectedElements([text]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
expect(
(h.state.editingElement as ExcalidrawTextElement).containerId,
).toBe(null);
});
it("should prefer editing selected text element (bindable container present)", async () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([boundText2]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText2.id);
});
it("should not create bound text on ENTER if text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
mutateElement(container, {
boundElements: [{ type: "text", id: text.id }],
});
h.elements = [container, text];
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
});
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText.id);
});
it("should edit text under cursor when clicked with text tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("text");
mouse.clickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
it("should edit text under cursor when double-clicked with selection tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("selection");
mouse.doubleClickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
});
describe("Test container-unbound text", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text");
mouse.clickOn(textElement);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "|Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
// cursor: " |Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(4);
expect(textarea.selectionEnd).toEqual(4);
});
it("should add a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "Line#1\nLin|e#2"
textarea.selectionStart = 10;
textarea.selectionEnd = 10;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
// cursor: "Line#1\n Lin|e#2"
expect(textarea.selectionStart).toEqual(14);
expect(textarea.selectionEnd).toEqual(14);
});
it("should add a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2\nLine#3";
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
textarea.selectionStart = 2;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(6);
expect(textarea.selectionEnd).toEqual(17);
});
it("should remove a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
textarea.value = `${tab}Line#1\nLine#2`;
// cursor: "| Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "|Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(0);
expect(textarea.selectionEnd).toEqual(0);
});
it("should remove a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Lin|e#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "Line#1\nLin|e#2"
expect(textarea.selectionStart).toEqual(11);
expect(textarea.selectionEnd).toEqual(11);
});
it("should remove a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
textarea.selectionStart = 6;
textarea.selectionEnd = 17;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(2);
expect(textarea.selectionEnd).toEqual(9);
});
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n | Line#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
// cursor: "Line#1\n|Line#2"
expect(textarea.selectionStart).toEqual(7);
// expect(textarea.selectionEnd).toEqual(7);
});
it("should remove partial tabs", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Line#|2"
textarea.value = `Line#1\n Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should remove nothing", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Li|ne#2"
textarea.value = `Line#1\nLine#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should resize text via shortcuts while in wysiwyg", () => {
textarea.value = "abc def";
const origFontSize = textElement.fontSize;
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_RIGHT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize * 1.1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_LEFT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize);
});
it("zooming via keyboard should zoom canvas", () => {
expect(h.state.zoom.value).toBe(1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.MINUS,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_SUBTRACT,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.8);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_ADD,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.EQUAL,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(1);
});
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
});
describe("Test container-bound text", () => {
let rectangle: any;
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
rectangle = UI.createElement("rectangle", {
x: 10,
y: 20,
width: 90,
height: 75,
});
});
it("should bind text to container when double clicked inside filled container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "red",
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "transparent",
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
expect(h.elements.length).toBe(3);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when clicked on container and enter pressed", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on container stroke", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
strokeWidth: 4,
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 2, rectangle.y + 2);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("shouldn't bind to non-text-bindable containers", async () => {
const freedraw = API.createElement({
type: "freedraw",
width: 100,
height: 0,
});
h.elements = [freedraw];
UI.clickTool("text");
mouse.clickAt(
freedraw.x + freedraw.width / 2,
freedraw.y + freedraw.height / 2,
);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
editor.dispatchEvent(new Event("input"));
expect(freedraw.boundElements).toBe(null);
expect(h.elements[1].type).toBe("text");
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = [];
const element = UI.createElement(type, {
width: 100,
height: 50,
});
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
});
it("should'nt bind text to container when not double clicked on center", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
// clicking somewhere on top left
mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toBe(null);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
UI.clickTool("text");
mouse.clickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle(/code/i));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
//undo
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Virgil);
//redo
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
});
it("should wrap text and vertcially center align once text submitted", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(25);
expect(text.height).toBe(48);
expect(text.width).toBe(60);
// Edit and text by removing second line and it should
// still vertically align correctly
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello");
expect(text.height).toBe(24);
expect(text.width).toBe(50);
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(30);
});
it("should unbind bound text when unbind action from context menu is triggered", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.reset();
UI.clickTool("selection");
mouse.clickAt(10, 20);
mouse.down();
mouse.up();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
null,
);
});
it("shouldn't bind to container if container has bound text", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
// Bind first text
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should respect text alignment when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
85,
5,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
375,
-539,
]
`);
});
it("should always bind to selected container and insert it in correct position", async () => {
const rectangle2 = UI.createElement("rectangle", {
x: 5,
y: 10,
width: 120,
height: 100,
});
API.setSelectedElements([rectangle]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(3);
expect(h.elements[1].type).toBe("text");
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle2.boundElements).toBeNull();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should scale font size correctly when resizing using shift", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(rectangle.width).toBe(90);
expect(rectangle.height).toBe(75);
expect(textElement.fontSize).toBe(20);
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 50], {
shift: true,
});
expect(rectangle.width).toBe(200);
expect(rectangle.height).toBe(166.66666666666669);
expect(textElement.fontSize).toBe(47.5);
});
it("should bind text correctly when container duplicated with alt-drag", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(h.elements.length).toBe(2);
mouse.select(rectangle);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle.x + 10, rectangle.y + 10);
mouse.up(rectangle.x + 10, rectangle.y + 10);
});
expect(h.elements.length).toBe(4);
const duplicatedRectangle = h.elements[0];
const duplicatedText = h
.elements[1] as ExcalidrawTextElementWithContainer;
const originalRect = h.elements[2];
const originalText = h.elements[3] as ExcalidrawTextElementWithContainer;
expect(originalRect.boundElements).toStrictEqual([
{ id: originalText.id, type: "text" },
]);
expect(originalText.containerId).toBe(originalRect.id);
expect(duplicatedRectangle.boundElements).toStrictEqual([
{ id: duplicatedText.id, type: "text" },
]);
expect(duplicatedText.containerId).toBe(duplicatedRectangle.id);
});
it("undo should work", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
const originalRectX = rectangle.x;
const originalRectY = rectangle.y;
const originalTextX = text.x;
const originalTextY = text.y;
mouse.select(rectangle);
mouse.downAt(rectangle.x, rectangle.y);
mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-35);
expect(text.x).toBe(85);
expect(text.y).toBe(-30);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(rectangle.x).toBe(originalRectX);
expect(rectangle.y).toBe(originalRectY);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.x).toBe(originalTextX);
expect(text.y).toBe(originalTextY);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should not allow bound text with only whitespaces", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: " " } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([]);
expect(h.elements[1].isDeleted).toBe(true);
});
it("should restore original container height and clear cache once text is unbind", async () => {
const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, {
target: { value: "Online whiteboard collaboration made easy" },
});
editor.blur();
expect(rectangle.height).toBe(178);
mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
expect(rectangle.height).toBe(originalRectHeight);
});
it("should reset the container height cache when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.height).toBe(156);
// cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156);
});
it("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
fireEvent.click(screen.getByTitle(/Very large/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
96.39999999999999,
);
});
describe("should align correctly", () => {
let editor: HTMLTextAreaElement;
beforeEach(async () => {
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
});
it("when top left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
25,
]
`);
});
it("when top center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
25,
]
`);
});
it("when top right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
25,
]
`);
});
it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
45.5,
]
`);
});
it("when center center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
45.5,
]
`);
});
it("when center right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
45.5,
]
`);
});
it("when bottom left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
});
it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
66,
]
`);
});
it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
66,
]
`);
});
});
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
expect(h.elements[1].width).toBe(600);
expect(h.elements[1].height).toBe(24);
expect((h.elements[1] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 34,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect((h.elements[2] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
});
});
});
| src/element/textWysiwyg.test.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.9454752206802368,
0.007999674417078495,
0.0001632019702810794,
0.00017703119374345988,
0.07984509319067001
] |
{
"id": 2,
"code_window": [
"} from \"../tests/test-utils\";\n",
"import { queryByText } from \"@testing-library/react\";\n",
"\n",
"import { FONT_FAMILY } from \"../constants\";\n",
"import {\n",
" ExcalidrawTextElement,\n",
" ExcalidrawTextElementWithContainer,\n",
"} from \"./types\";\n",
"import { API } from \"../tests/helpers/api\";\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FONT_FAMILY, TEXT_ALIGN, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 12
} | import { ExcalidrawElement } from "./element/types";
import { newElementWith } from "./element/mutateElement";
import { Box, getCommonBoundingBox } from "./element/bounds";
import { getMaximumGroups } from "./groups";
export interface Alignment {
position: "start" | "center" | "end";
axis: "x" | "y";
}
export const alignElements = (
selectedElements: ExcalidrawElement[],
alignment: Alignment,
): ExcalidrawElement[] => {
const groups: ExcalidrawElement[][] = getMaximumGroups(selectedElements);
const selectionBoundingBox = getCommonBoundingBox(selectedElements);
return groups.flatMap((group) => {
const translation = calculateTranslation(
group,
selectionBoundingBox,
alignment,
);
return group.map((element) =>
newElementWith(element, {
x: element.x + translation.x,
y: element.y + translation.y,
}),
);
});
};
const calculateTranslation = (
group: ExcalidrawElement[],
selectionBoundingBox: Box,
{ axis, position }: Alignment,
): { x: number; y: number } => {
const groupBoundingBox = getCommonBoundingBox(group);
const [min, max]: ["minX" | "minY", "maxX" | "maxY"] =
axis === "x" ? ["minX", "maxX"] : ["minY", "maxY"];
const noTranslation = { x: 0, y: 0 };
if (position === "start") {
return {
...noTranslation,
[axis]: selectionBoundingBox[min] - groupBoundingBox[min],
};
} else if (position === "end") {
return {
...noTranslation,
[axis]: selectionBoundingBox[max] - groupBoundingBox[max],
};
} // else if (position === "center") {
return {
...noTranslation,
[axis]:
(selectionBoundingBox[min] + selectionBoundingBox[max]) / 2 -
(groupBoundingBox[min] + groupBoundingBox[max]) / 2,
};
};
| src/align.ts | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00036279941559769213,
0.0002334486780455336,
0.00017380097415298223,
0.0001772730756783858,
0.00007690156780881807
] |
{
"id": 2,
"code_window": [
"} from \"../tests/test-utils\";\n",
"import { queryByText } from \"@testing-library/react\";\n",
"\n",
"import { FONT_FAMILY } from \"../constants\";\n",
"import {\n",
" ExcalidrawTextElement,\n",
" ExcalidrawTextElementWithContainer,\n",
"} from \"./types\";\n",
"import { API } from \"../tests/helpers/api\";\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FONT_FAMILY, TEXT_ALIGN, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 12
} | import { rotate } from "./math";
describe("rotate", () => {
it("should rotate over (x2, y2) and return the rotated coordinates for (x1, y1)", () => {
const x1 = 10;
const y1 = 20;
const x2 = 20;
const y2 = 30;
const angle = Math.PI / 2;
const [rotatedX, rotatedY] = rotate(x1, y1, x2, y2, angle);
expect([rotatedX, rotatedY]).toEqual([30, 20]);
const res2 = rotate(rotatedX, rotatedY, x2, y2, -angle);
expect(res2).toEqual([x1, x2]);
});
});
| src/math.test.ts | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00018202541104983538,
0.000179589434992522,
0.0001771534443832934,
0.000179589434992522,
0.000002435983333270997
] |
{
"id": 2,
"code_window": [
"} from \"../tests/test-utils\";\n",
"import { queryByText } from \"@testing-library/react\";\n",
"\n",
"import { FONT_FAMILY } from \"../constants\";\n",
"import {\n",
" ExcalidrawTextElement,\n",
" ExcalidrawTextElementWithContainer,\n",
"} from \"./types\";\n",
"import { API } from \"../tests/helpers/api\";\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FONT_FAMILY, TEXT_ALIGN, VERTICAL_ALIGN } from \"../constants\";\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 12
} | import { fileOpen, fileSave } from "./filesystem";
import { cleanAppStateForExport, clearAppStateForDatabase } from "../appState";
import {
EXPORT_DATA_TYPES,
EXPORT_SOURCE,
MIME_TYPES,
VERSIONS,
} from "../constants";
import { clearElementsForDatabase, clearElementsForExport } from "../element";
import { ExcalidrawElement } from "../element/types";
import { AppState, BinaryFiles, LibraryItems } from "../types";
import { isImageFileHandle, loadFromBlob, normalizeFile } from "./blob";
import {
ExportedDataState,
ImportedDataState,
ExportedLibraryData,
ImportedLibraryData,
} from "./types";
/**
* Strips out files which are only referenced by deleted elements
*/
const filterOutDeletedFiles = (
elements: readonly ExcalidrawElement[],
files: BinaryFiles,
) => {
const nextFiles: BinaryFiles = {};
for (const element of elements) {
if (
!element.isDeleted &&
"fileId" in element &&
element.fileId &&
files[element.fileId]
) {
nextFiles[element.fileId] = files[element.fileId];
}
}
return nextFiles;
};
export const serializeAsJSON = (
elements: readonly ExcalidrawElement[],
appState: Partial<AppState>,
files: BinaryFiles,
type: "local" | "database",
): string => {
const data: ExportedDataState = {
type: EXPORT_DATA_TYPES.excalidraw,
version: VERSIONS.excalidraw,
source: EXPORT_SOURCE,
elements:
type === "local"
? clearElementsForExport(elements)
: clearElementsForDatabase(elements),
appState:
type === "local"
? cleanAppStateForExport(appState)
: clearAppStateForDatabase(appState),
files:
type === "local"
? filterOutDeletedFiles(elements, files)
: // will be stripped from JSON
undefined,
};
return JSON.stringify(data, null, 2);
};
export const saveAsJSON = async (
elements: readonly ExcalidrawElement[],
appState: AppState,
files: BinaryFiles,
) => {
const serialized = serializeAsJSON(elements, appState, files, "local");
const blob = new Blob([serialized], {
type: MIME_TYPES.excalidraw,
});
const fileHandle = await fileSave(blob, {
name: appState.name,
extension: "excalidraw",
description: "Excalidraw file",
fileHandle: isImageFileHandle(appState.fileHandle)
? null
: appState.fileHandle,
});
return { fileHandle };
};
export const loadFromJSON = async (
localAppState: AppState,
localElements: readonly ExcalidrawElement[] | null,
) => {
const file = await fileOpen({
description: "Excalidraw files",
// ToDo: Be over-permissive until https://bugs.webkit.org/show_bug.cgi?id=34442
// gets resolved. Else, iOS users cannot open `.excalidraw` files.
// extensions: ["json", "excalidraw", "png", "svg"],
});
return loadFromBlob(
await normalizeFile(file),
localAppState,
localElements,
file.handle,
);
};
export const isValidExcalidrawData = (data?: {
type?: any;
elements?: any;
appState?: any;
}): data is ImportedDataState => {
return (
data?.type === EXPORT_DATA_TYPES.excalidraw &&
(!data.elements ||
(Array.isArray(data.elements) &&
(!data.appState || typeof data.appState === "object")))
);
};
export const isValidLibrary = (json: any): json is ImportedLibraryData => {
return (
typeof json === "object" &&
json &&
json.type === EXPORT_DATA_TYPES.excalidrawLibrary &&
(json.version === 1 || json.version === 2)
);
};
export const serializeLibraryAsJSON = (libraryItems: LibraryItems) => {
const data: ExportedLibraryData = {
type: EXPORT_DATA_TYPES.excalidrawLibrary,
version: VERSIONS.excalidrawLibrary,
source: EXPORT_SOURCE,
libraryItems,
};
return JSON.stringify(data, null, 2);
};
export const saveLibraryAsJSON = async (libraryItems: LibraryItems) => {
const serialized = serializeLibraryAsJSON(libraryItems);
await fileSave(
new Blob([serialized], {
type: MIME_TYPES.excalidrawlib,
}),
{
name: "library",
extension: "excalidrawlib",
description: "Excalidraw library file",
},
);
};
| src/data/json.ts | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.000535885221324861,
0.00024391138867940754,
0.0001633137435419485,
0.00019666741718538105,
0.00010736707190517336
] |
{
"id": 3,
"code_window": [
"\n",
" editor.dispatchEvent(new Event(\"input\"));\n",
" await new Promise((cb) => setTimeout(cb, 0));\n",
" editor.blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" editor.select();\n",
" fireEvent.click(screen.getByTitle(\"Left\"));\n",
" await new Promise((r) => setTimeout(r, 0));\n",
"\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "add",
"edit_start_line_idx": 1326
} | import ReactDOM from "react-dom";
import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys";
import {
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react";
import { FONT_FAMILY } from "../constants";
import {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
} from "./types";
import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const tab = " ";
const mouse = new Pointer("mouse");
describe("textWysiwyg", () => {
describe("start text editing", () => {
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
});
it("should prefer editing selected text element (non-bindable container present)", async () => {
const line = API.createElement({
type: "line",
width: 100,
height: 0,
points: [
[0, 0],
[100, 0],
],
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: line.width / 2 - textSize / 2,
y: -textSize / 2,
width: textSize,
height: textSize,
});
h.elements = [text, line];
API.setSelectedElements([text]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
expect(
(h.state.editingElement as ExcalidrawTextElement).containerId,
).toBe(null);
});
it("should prefer editing selected text element (bindable container present)", async () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([boundText2]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText2.id);
});
it("should not create bound text on ENTER if text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
mutateElement(container, {
boundElements: [{ type: "text", id: text.id }],
});
h.elements = [container, text];
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
});
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText.id);
});
it("should edit text under cursor when clicked with text tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("text");
mouse.clickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
it("should edit text under cursor when double-clicked with selection tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("selection");
mouse.doubleClickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
});
describe("Test container-unbound text", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text");
mouse.clickOn(textElement);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "|Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
// cursor: " |Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(4);
expect(textarea.selectionEnd).toEqual(4);
});
it("should add a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "Line#1\nLin|e#2"
textarea.selectionStart = 10;
textarea.selectionEnd = 10;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
// cursor: "Line#1\n Lin|e#2"
expect(textarea.selectionStart).toEqual(14);
expect(textarea.selectionEnd).toEqual(14);
});
it("should add a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2\nLine#3";
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
textarea.selectionStart = 2;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(6);
expect(textarea.selectionEnd).toEqual(17);
});
it("should remove a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
textarea.value = `${tab}Line#1\nLine#2`;
// cursor: "| Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "|Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(0);
expect(textarea.selectionEnd).toEqual(0);
});
it("should remove a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Lin|e#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "Line#1\nLin|e#2"
expect(textarea.selectionStart).toEqual(11);
expect(textarea.selectionEnd).toEqual(11);
});
it("should remove a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
textarea.selectionStart = 6;
textarea.selectionEnd = 17;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(2);
expect(textarea.selectionEnd).toEqual(9);
});
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n | Line#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
// cursor: "Line#1\n|Line#2"
expect(textarea.selectionStart).toEqual(7);
// expect(textarea.selectionEnd).toEqual(7);
});
it("should remove partial tabs", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Line#|2"
textarea.value = `Line#1\n Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should remove nothing", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Li|ne#2"
textarea.value = `Line#1\nLine#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should resize text via shortcuts while in wysiwyg", () => {
textarea.value = "abc def";
const origFontSize = textElement.fontSize;
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_RIGHT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize * 1.1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_LEFT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize);
});
it("zooming via keyboard should zoom canvas", () => {
expect(h.state.zoom.value).toBe(1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.MINUS,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_SUBTRACT,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.8);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_ADD,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.EQUAL,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(1);
});
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
});
describe("Test container-bound text", () => {
let rectangle: any;
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
rectangle = UI.createElement("rectangle", {
x: 10,
y: 20,
width: 90,
height: 75,
});
});
it("should bind text to container when double clicked inside filled container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "red",
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "transparent",
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
expect(h.elements.length).toBe(3);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when clicked on container and enter pressed", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on container stroke", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
strokeWidth: 4,
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 2, rectangle.y + 2);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("shouldn't bind to non-text-bindable containers", async () => {
const freedraw = API.createElement({
type: "freedraw",
width: 100,
height: 0,
});
h.elements = [freedraw];
UI.clickTool("text");
mouse.clickAt(
freedraw.x + freedraw.width / 2,
freedraw.y + freedraw.height / 2,
);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
editor.dispatchEvent(new Event("input"));
expect(freedraw.boundElements).toBe(null);
expect(h.elements[1].type).toBe("text");
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = [];
const element = UI.createElement(type, {
width: 100,
height: 50,
});
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
});
it("should'nt bind text to container when not double clicked on center", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
// clicking somewhere on top left
mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toBe(null);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
UI.clickTool("text");
mouse.clickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle(/code/i));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
//undo
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Virgil);
//redo
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
});
it("should wrap text and vertcially center align once text submitted", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(25);
expect(text.height).toBe(48);
expect(text.width).toBe(60);
// Edit and text by removing second line and it should
// still vertically align correctly
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello");
expect(text.height).toBe(24);
expect(text.width).toBe(50);
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(30);
});
it("should unbind bound text when unbind action from context menu is triggered", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.reset();
UI.clickTool("selection");
mouse.clickAt(10, 20);
mouse.down();
mouse.up();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
null,
);
});
it("shouldn't bind to container if container has bound text", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
// Bind first text
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should respect text alignment when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
85,
5,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
375,
-539,
]
`);
});
it("should always bind to selected container and insert it in correct position", async () => {
const rectangle2 = UI.createElement("rectangle", {
x: 5,
y: 10,
width: 120,
height: 100,
});
API.setSelectedElements([rectangle]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(3);
expect(h.elements[1].type).toBe("text");
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle2.boundElements).toBeNull();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should scale font size correctly when resizing using shift", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(rectangle.width).toBe(90);
expect(rectangle.height).toBe(75);
expect(textElement.fontSize).toBe(20);
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 50], {
shift: true,
});
expect(rectangle.width).toBe(200);
expect(rectangle.height).toBe(166.66666666666669);
expect(textElement.fontSize).toBe(47.5);
});
it("should bind text correctly when container duplicated with alt-drag", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(h.elements.length).toBe(2);
mouse.select(rectangle);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle.x + 10, rectangle.y + 10);
mouse.up(rectangle.x + 10, rectangle.y + 10);
});
expect(h.elements.length).toBe(4);
const duplicatedRectangle = h.elements[0];
const duplicatedText = h
.elements[1] as ExcalidrawTextElementWithContainer;
const originalRect = h.elements[2];
const originalText = h.elements[3] as ExcalidrawTextElementWithContainer;
expect(originalRect.boundElements).toStrictEqual([
{ id: originalText.id, type: "text" },
]);
expect(originalText.containerId).toBe(originalRect.id);
expect(duplicatedRectangle.boundElements).toStrictEqual([
{ id: duplicatedText.id, type: "text" },
]);
expect(duplicatedText.containerId).toBe(duplicatedRectangle.id);
});
it("undo should work", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
const originalRectX = rectangle.x;
const originalRectY = rectangle.y;
const originalTextX = text.x;
const originalTextY = text.y;
mouse.select(rectangle);
mouse.downAt(rectangle.x, rectangle.y);
mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-35);
expect(text.x).toBe(85);
expect(text.y).toBe(-30);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(rectangle.x).toBe(originalRectX);
expect(rectangle.y).toBe(originalRectY);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.x).toBe(originalTextX);
expect(text.y).toBe(originalTextY);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should not allow bound text with only whitespaces", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: " " } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([]);
expect(h.elements[1].isDeleted).toBe(true);
});
it("should restore original container height and clear cache once text is unbind", async () => {
const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, {
target: { value: "Online whiteboard collaboration made easy" },
});
editor.blur();
expect(rectangle.height).toBe(178);
mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
expect(rectangle.height).toBe(originalRectHeight);
});
it("should reset the container height cache when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.height).toBe(156);
// cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156);
});
it("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
fireEvent.click(screen.getByTitle(/Very large/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
96.39999999999999,
);
});
describe("should align correctly", () => {
let editor: HTMLTextAreaElement;
beforeEach(async () => {
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
});
it("when top left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
25,
]
`);
});
it("when top center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
25,
]
`);
});
it("when top right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
25,
]
`);
});
it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
45.5,
]
`);
});
it("when center center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
45.5,
]
`);
});
it("when center right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
45.5,
]
`);
});
it("when bottom left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
});
it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
66,
]
`);
});
it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
66,
]
`);
});
});
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
expect(h.elements[1].width).toBe(600);
expect(h.elements[1].height).toBe(24);
expect((h.elements[1] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 34,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect((h.elements[2] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
});
});
});
| src/element/textWysiwyg.test.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.7313910126686096,
0.011072147637605667,
0.00016435305587947369,
0.00017290278628934175,
0.08302772790193558
] |
{
"id": 3,
"code_window": [
"\n",
" editor.dispatchEvent(new Event(\"input\"));\n",
" await new Promise((cb) => setTimeout(cb, 0));\n",
" editor.blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" editor.select();\n",
" fireEvent.click(screen.getByTitle(\"Left\"));\n",
" await new Promise((r) => setTimeout(r, 0));\n",
"\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "add",
"edit_start_line_idx": 1326
} | import { isSomeElementSelected } from "../scene";
import { KEYS } from "../keys";
import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n";
import { register } from "./register";
import { getNonDeletedElements } from "../element";
import { ExcalidrawElement } from "../element/types";
import { AppState } from "../types";
import { newElementWith } from "../element/mutateElement";
import { getElementsInGroup } from "../groups";
import { LinearElementEditor } from "../element/linearElementEditor";
import { fixBindingsAfterDeletion } from "../element/binding";
import { isBoundToContainer } from "../element/typeChecks";
import { updateActiveTool } from "../utils";
import { TrashIcon } from "../components/icons";
const deleteSelectedElements = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
return {
elements: elements.map((el) => {
if (appState.selectedElementIds[el.id]) {
return newElementWith(el, { isDeleted: true });
}
if (
isBoundToContainer(el) &&
appState.selectedElementIds[el.containerId]
) {
return newElementWith(el, { isDeleted: true });
}
return el;
}),
appState: {
...appState,
selectedElementIds: {},
},
};
};
const handleGroupEditingState = (
appState: AppState,
elements: readonly ExcalidrawElement[],
): AppState => {
if (appState.editingGroupId) {
const siblingElements = getElementsInGroup(
getNonDeletedElements(elements),
appState.editingGroupId!,
);
if (siblingElements.length) {
return {
...appState,
selectedElementIds: { [siblingElements[0].id]: true },
};
}
}
return appState;
};
export const actionDeleteSelected = register({
name: "deleteSelectedElements",
trackEvent: { category: "element", action: "delete" },
perform: (elements, appState) => {
if (appState.editingLinearElement) {
const {
elementId,
selectedPointsIndices,
startBindingElement,
endBindingElement,
} = appState.editingLinearElement;
const element = LinearElementEditor.getElement(elementId);
if (!element) {
return false;
}
// case: no point selected → do nothing, as deleting the whole element
// is most likely a mistake, where you wanted to delete a specific point
// but failed to select it (or you thought it's selected, while it was
// only in a hover state)
if (selectedPointsIndices == null) {
return false;
}
// case: deleting last remaining point
if (element.points.length < 2) {
const nextElements = elements.map((el) => {
if (el.id === element.id) {
return newElementWith(el, { isDeleted: true });
}
return el;
});
const nextAppState = handleGroupEditingState(appState, nextElements);
return {
elements: nextElements,
appState: {
...nextAppState,
editingLinearElement: null,
},
commitToHistory: false,
};
}
// We cannot do this inside `movePoint` because it is also called
// when deleting the uncommitted point (which hasn't caused any binding)
const binding = {
startBindingElement: selectedPointsIndices?.includes(0)
? null
: startBindingElement,
endBindingElement: selectedPointsIndices?.includes(
element.points.length - 1,
)
? null
: endBindingElement,
};
LinearElementEditor.deletePoints(element, selectedPointsIndices);
return {
elements,
appState: {
...appState,
editingLinearElement: {
...appState.editingLinearElement,
...binding,
selectedPointsIndices:
selectedPointsIndices?.[0] > 0
? [selectedPointsIndices[0] - 1]
: [0],
},
},
commitToHistory: true,
};
}
let { elements: nextElements, appState: nextAppState } =
deleteSelectedElements(elements, appState);
fixBindingsAfterDeletion(
nextElements,
elements.filter(({ id }) => appState.selectedElementIds[id]),
);
nextAppState = handleGroupEditingState(nextAppState, nextElements);
return {
elements: nextElements,
appState: {
...nextAppState,
activeTool: updateActiveTool(appState, { type: "selection" }),
multiElement: null,
},
commitToHistory: isSomeElementSelected(
getNonDeletedElements(elements),
appState,
),
};
},
contextItemLabel: "labels.delete",
keyTest: (event, appState, elements) =>
(event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE) &&
!event[KEYS.CTRL_OR_CMD],
PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton
type="button"
icon={TrashIcon}
title={t("labels.delete")}
aria-label={t("labels.delete")}
onClick={() => updateData(null)}
visible={isSomeElementSelected(getNonDeletedElements(elements), appState)}
/>
),
});
| src/actions/actionDeleteSelected.tsx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017713689885567874,
0.00016936672909650952,
0.00016522921214345843,
0.00016953371232375503,
0.0000030217208859539824
] |
{
"id": 3,
"code_window": [
"\n",
" editor.dispatchEvent(new Event(\"input\"));\n",
" await new Promise((cb) => setTimeout(cb, 0));\n",
" editor.blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" editor.select();\n",
" fireEvent.click(screen.getByTitle(\"Left\"));\n",
" await new Promise((r) => setTimeout(r, 0));\n",
"\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "add",
"edit_start_line_idx": 1326
} | import { bumpVersion } from "./element/mutateElement";
import { ExcalidrawElement } from "./element/types";
import { getElementsInGroup } from "./groups";
import { getSelectedElements } from "./scene";
import Scene from "./scene/Scene";
import { AppState } from "./types";
import { arrayToMap, findIndex, findLastIndex } from "./utils";
/**
* Returns indices of elements to move based on selected elements.
* Includes contiguous deleted elements that are between two selected elements,
* e.g.: [0 (selected), 1 (deleted), 2 (deleted), 3 (selected)]
*/
const getIndicesToMove = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
let selectedIndices: number[] = [];
let deletedIndices: number[] = [];
let includeDeletedIndex = null;
let index = -1;
const selectedElementIds = arrayToMap(
getSelectedElements(elements, appState, true),
);
while (++index < elements.length) {
if (selectedElementIds.get(elements[index].id)) {
if (deletedIndices.length) {
selectedIndices = selectedIndices.concat(deletedIndices);
deletedIndices = [];
}
selectedIndices.push(index);
includeDeletedIndex = index + 1;
} else if (elements[index].isDeleted && includeDeletedIndex === index) {
includeDeletedIndex = index + 1;
deletedIndices.push(index);
} else {
deletedIndices = [];
}
}
return selectedIndices;
};
const toContiguousGroups = (array: number[]) => {
let cursor = 0;
return array.reduce((acc, value, index) => {
if (index > 0 && array[index - 1] !== value - 1) {
cursor = ++cursor;
}
(acc[cursor] || (acc[cursor] = [])).push(value);
return acc;
}, [] as number[][]);
};
/**
* @returns index of target element, consindering tightly-bound elements
* (currently non-linear elements bound to a container) as a one unit.
* If no binding present, returns `undefined`.
*/
const getTargetIndexAccountingForBinding = (
nextElement: ExcalidrawElement,
elements: readonly ExcalidrawElement[],
direction: "left" | "right",
) => {
if ("containerId" in nextElement && nextElement.containerId) {
if (direction === "left") {
const containerElement = Scene.getScene(nextElement)!.getElement(
nextElement.containerId,
);
if (containerElement) {
return elements.indexOf(containerElement);
}
} else {
return elements.indexOf(nextElement);
}
} else {
const boundElementId = nextElement.boundElements?.find(
(binding) => binding.type !== "arrow",
)?.id;
if (boundElementId) {
if (direction === "left") {
return elements.indexOf(nextElement);
}
const boundTextElement =
Scene.getScene(nextElement)!.getElement(boundElementId);
if (boundTextElement) {
return elements.indexOf(boundTextElement);
}
}
}
};
/**
* Returns next candidate index that's available to be moved to. Currently that
* is a non-deleted element, and not inside a group (unless we're editing it).
*/
const getTargetIndex = (
appState: AppState,
elements: readonly ExcalidrawElement[],
boundaryIndex: number,
direction: "left" | "right",
) => {
const sourceElement = elements[boundaryIndex];
const indexFilter = (element: ExcalidrawElement) => {
if (element.isDeleted) {
return false;
}
// if we're editing group, find closest sibling irrespective of whether
// there's a different-group element between them (for legacy reasons)
if (appState.editingGroupId) {
return element.groupIds.includes(appState.editingGroupId);
}
return true;
};
const candidateIndex =
direction === "left"
? findLastIndex(elements, indexFilter, Math.max(0, boundaryIndex - 1))
: findIndex(elements, indexFilter, boundaryIndex + 1);
const nextElement = elements[candidateIndex];
if (!nextElement) {
return -1;
}
if (appState.editingGroupId) {
if (
// candidate element is a sibling in current editing group → return
sourceElement?.groupIds.join("") === nextElement?.groupIds.join("")
) {
return (
getTargetIndexAccountingForBinding(nextElement, elements, direction) ??
candidateIndex
);
} else if (!nextElement?.groupIds.includes(appState.editingGroupId)) {
// candidate element is outside current editing group → prevent
return -1;
}
}
if (!nextElement.groupIds.length) {
return (
getTargetIndexAccountingForBinding(nextElement, elements, direction) ??
candidateIndex
);
}
const siblingGroupId = appState.editingGroupId
? nextElement.groupIds[
nextElement.groupIds.indexOf(appState.editingGroupId) - 1
]
: nextElement.groupIds[nextElement.groupIds.length - 1];
const elementsInSiblingGroup = getElementsInGroup(elements, siblingGroupId);
if (elementsInSiblingGroup.length) {
// assumes getElementsInGroup() returned elements are sorted
// by zIndex (ascending)
return direction === "left"
? elements.indexOf(elementsInSiblingGroup[0])
: elements.indexOf(
elementsInSiblingGroup[elementsInSiblingGroup.length - 1],
);
}
return candidateIndex;
};
const getTargetElementsMap = (
elements: readonly ExcalidrawElement[],
indices: number[],
) => {
return indices.reduce((acc, index) => {
const element = elements[index];
acc[element.id] = element;
return acc;
}, {} as Record<string, ExcalidrawElement>);
};
const shiftElements = (
appState: AppState,
elements: readonly ExcalidrawElement[],
direction: "left" | "right",
) => {
const indicesToMove = getIndicesToMove(elements, appState);
const targetElementsMap = getTargetElementsMap(elements, indicesToMove);
let groupedIndices = toContiguousGroups(indicesToMove);
if (direction === "right") {
groupedIndices = groupedIndices.reverse();
}
groupedIndices.forEach((indices, i) => {
const leadingIndex = indices[0];
const trailingIndex = indices[indices.length - 1];
const boundaryIndex = direction === "left" ? leadingIndex : trailingIndex;
const targetIndex = getTargetIndex(
appState,
elements,
boundaryIndex,
direction,
);
if (targetIndex === -1 || boundaryIndex === targetIndex) {
return;
}
const leadingElements =
direction === "left"
? elements.slice(0, targetIndex)
: elements.slice(0, leadingIndex);
const targetElements = elements.slice(leadingIndex, trailingIndex + 1);
const displacedElements =
direction === "left"
? elements.slice(targetIndex, leadingIndex)
: elements.slice(trailingIndex + 1, targetIndex + 1);
const trailingElements =
direction === "left"
? elements.slice(trailingIndex + 1)
: elements.slice(targetIndex + 1);
elements =
direction === "left"
? [
...leadingElements,
...targetElements,
...displacedElements,
...trailingElements,
]
: [
...leadingElements,
...displacedElements,
...targetElements,
...trailingElements,
];
});
return elements.map((element) => {
if (targetElementsMap[element.id]) {
return bumpVersion(element);
}
return element;
});
};
const shiftElementsToEnd = (
elements: readonly ExcalidrawElement[],
appState: AppState,
direction: "left" | "right",
) => {
const indicesToMove = getIndicesToMove(elements, appState);
const targetElementsMap = getTargetElementsMap(elements, indicesToMove);
const displacedElements: ExcalidrawElement[] = [];
let leadingIndex: number;
let trailingIndex: number;
if (direction === "left") {
if (appState.editingGroupId) {
const groupElements = getElementsInGroup(
elements,
appState.editingGroupId,
);
if (!groupElements.length) {
return elements;
}
leadingIndex = elements.indexOf(groupElements[0]);
} else {
leadingIndex = 0;
}
trailingIndex = indicesToMove[indicesToMove.length - 1];
} else {
if (appState.editingGroupId) {
const groupElements = getElementsInGroup(
elements,
appState.editingGroupId,
);
if (!groupElements.length) {
return elements;
}
trailingIndex = elements.indexOf(groupElements[groupElements.length - 1]);
} else {
trailingIndex = elements.length - 1;
}
leadingIndex = indicesToMove[0];
}
for (let index = leadingIndex; index < trailingIndex + 1; index++) {
if (!indicesToMove.includes(index)) {
displacedElements.push(elements[index]);
}
}
const targetElements = Object.values(targetElementsMap).map((element) => {
return bumpVersion(element);
});
const leadingElements = elements.slice(0, leadingIndex);
const trailingElements = elements.slice(trailingIndex + 1);
return direction === "left"
? [
...leadingElements,
...targetElements,
...displacedElements,
...trailingElements,
]
: [
...leadingElements,
...displacedElements,
...targetElements,
...trailingElements,
];
};
// public API
// -----------------------------------------------------------------------------
export const moveOneLeft = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
return shiftElements(appState, elements, "left");
};
export const moveOneRight = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
return shiftElements(appState, elements, "right");
};
export const moveAllLeft = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
return shiftElementsToEnd(elements, appState, "left");
};
export const moveAllRight = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
return shiftElementsToEnd(elements, appState, "right");
};
| src/zindex.ts | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017532378842588514,
0.0001709605858195573,
0.0001666616735747084,
0.00017128483159467578,
0.000002276925215483061
] |
{
"id": 3,
"code_window": [
"\n",
" editor.dispatchEvent(new Event(\"input\"));\n",
" await new Promise((cb) => setTimeout(cb, 0));\n",
" editor.blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" editor.select();\n",
" fireEvent.click(screen.getByTitle(\"Left\"));\n",
" await new Promise((r) => setTimeout(r, 0));\n",
"\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "add",
"edit_start_line_idx": 1326
} | @import "../css/variables.module";
.excalidraw {
.ExportDialog__preview {
--preview-padding: calc(var(--space-factor) * 4);
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
left center;
text-align: center;
padding: var(--preview-padding);
margin-bottom: calc(var(--space-factor) * 3);
}
.ExportDialog__preview canvas {
max-width: calc(100% - var(--preview-padding) * 2);
max-height: 25rem;
}
&.theme--dark .ExportDialog__preview canvas {
filter: none;
}
.ExportDialog__actions {
width: 100%;
display: flex;
grid-gap: calc(var(--space-factor) * 2);
align-items: top;
justify-content: space-between;
}
@include isMobile {
.ExportDialog {
display: flex;
flex-direction: column;
}
.ExportDialog__actions {
flex-direction: column;
align-items: center;
}
.ExportDialog__actions > * {
margin-bottom: calc(var(--space-factor) * 3);
}
.ExportDialog__preview canvas {
max-height: 30vh;
}
.ExportDialog__dialog,
.ExportDialog__dialog .Island {
height: 100%;
box-sizing: border-box;
}
.ExportDialog__dialog .Island {
overflow-y: auto;
}
}
.ExportDialog--json {
.ExportDialog-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
justify-items: center;
row-gap: 2em;
@media (max-width: 460px) {
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
.Card-details {
min-height: 40px;
}
}
.ProjectName {
width: fit-content;
margin: 1em auto;
align-items: flex-start;
flex-direction: column;
.TextInput {
width: auto;
}
}
.ProjectName-label {
margin: 0.625em 0;
font-weight: bold;
}
}
}
button.ExportDialog-imageExportButton {
border: 0;
width: 5rem;
height: 5rem;
margin: 0 0.2em;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border-radius: 1rem;
background-color: var(--button-color);
box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.28),
0 6px 10px 0 rgba(0, 0, 0, 0.14);
font-family: Cascadia;
font-size: 1.8em;
color: $oc-white;
&:hover {
background-color: var(--button-color-darker);
}
&:active {
background-color: var(--button-color-darkest);
box-shadow: none;
}
svg {
width: 0.9em;
}
}
}
| src/components/ExportDialog.scss | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017663865583017468,
0.00017211399972438812,
0.0001687486219452694,
0.0001717366831144318,
0.0000022279657514445717
] |
{
"id": 4,
"code_window": [
" editor.blur();\n",
" expect(h.elements[1].width).toBe(600);\n",
" expect(h.elements[1].height).toBe(24);\n",
" expect((h.elements[1] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const textElement = h.elements[1] as ExcalidrawTextElement;\n",
" expect(textElement.width).toBe(600);\n",
" expect(textElement.height).toBe(24);\n",
" expect(textElement.textAlign).toBe(TEXT_ALIGN.LEFT);\n",
" expect((textElement as ExcalidrawTextElement).text).toBe(\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1327
} | import ReactDOM from "react-dom";
import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys";
import {
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react";
import { FONT_FAMILY } from "../constants";
import {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
} from "./types";
import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const tab = " ";
const mouse = new Pointer("mouse");
describe("textWysiwyg", () => {
describe("start text editing", () => {
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
});
it("should prefer editing selected text element (non-bindable container present)", async () => {
const line = API.createElement({
type: "line",
width: 100,
height: 0,
points: [
[0, 0],
[100, 0],
],
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: line.width / 2 - textSize / 2,
y: -textSize / 2,
width: textSize,
height: textSize,
});
h.elements = [text, line];
API.setSelectedElements([text]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
expect(
(h.state.editingElement as ExcalidrawTextElement).containerId,
).toBe(null);
});
it("should prefer editing selected text element (bindable container present)", async () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([boundText2]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText2.id);
});
it("should not create bound text on ENTER if text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
mutateElement(container, {
boundElements: [{ type: "text", id: text.id }],
});
h.elements = [container, text];
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
});
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText.id);
});
it("should edit text under cursor when clicked with text tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("text");
mouse.clickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
it("should edit text under cursor when double-clicked with selection tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("selection");
mouse.doubleClickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
});
describe("Test container-unbound text", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text");
mouse.clickOn(textElement);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "|Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
// cursor: " |Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(4);
expect(textarea.selectionEnd).toEqual(4);
});
it("should add a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "Line#1\nLin|e#2"
textarea.selectionStart = 10;
textarea.selectionEnd = 10;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
// cursor: "Line#1\n Lin|e#2"
expect(textarea.selectionStart).toEqual(14);
expect(textarea.selectionEnd).toEqual(14);
});
it("should add a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2\nLine#3";
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
textarea.selectionStart = 2;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(6);
expect(textarea.selectionEnd).toEqual(17);
});
it("should remove a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
textarea.value = `${tab}Line#1\nLine#2`;
// cursor: "| Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "|Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(0);
expect(textarea.selectionEnd).toEqual(0);
});
it("should remove a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Lin|e#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "Line#1\nLin|e#2"
expect(textarea.selectionStart).toEqual(11);
expect(textarea.selectionEnd).toEqual(11);
});
it("should remove a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
textarea.selectionStart = 6;
textarea.selectionEnd = 17;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(2);
expect(textarea.selectionEnd).toEqual(9);
});
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n | Line#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
// cursor: "Line#1\n|Line#2"
expect(textarea.selectionStart).toEqual(7);
// expect(textarea.selectionEnd).toEqual(7);
});
it("should remove partial tabs", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Line#|2"
textarea.value = `Line#1\n Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should remove nothing", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Li|ne#2"
textarea.value = `Line#1\nLine#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should resize text via shortcuts while in wysiwyg", () => {
textarea.value = "abc def";
const origFontSize = textElement.fontSize;
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_RIGHT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize * 1.1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_LEFT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize);
});
it("zooming via keyboard should zoom canvas", () => {
expect(h.state.zoom.value).toBe(1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.MINUS,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_SUBTRACT,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.8);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_ADD,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.EQUAL,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(1);
});
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
});
describe("Test container-bound text", () => {
let rectangle: any;
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
rectangle = UI.createElement("rectangle", {
x: 10,
y: 20,
width: 90,
height: 75,
});
});
it("should bind text to container when double clicked inside filled container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "red",
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "transparent",
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
expect(h.elements.length).toBe(3);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when clicked on container and enter pressed", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on container stroke", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
strokeWidth: 4,
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 2, rectangle.y + 2);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("shouldn't bind to non-text-bindable containers", async () => {
const freedraw = API.createElement({
type: "freedraw",
width: 100,
height: 0,
});
h.elements = [freedraw];
UI.clickTool("text");
mouse.clickAt(
freedraw.x + freedraw.width / 2,
freedraw.y + freedraw.height / 2,
);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
editor.dispatchEvent(new Event("input"));
expect(freedraw.boundElements).toBe(null);
expect(h.elements[1].type).toBe("text");
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = [];
const element = UI.createElement(type, {
width: 100,
height: 50,
});
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
});
it("should'nt bind text to container when not double clicked on center", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
// clicking somewhere on top left
mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toBe(null);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
UI.clickTool("text");
mouse.clickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle(/code/i));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
//undo
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Virgil);
//redo
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
});
it("should wrap text and vertcially center align once text submitted", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(25);
expect(text.height).toBe(48);
expect(text.width).toBe(60);
// Edit and text by removing second line and it should
// still vertically align correctly
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello");
expect(text.height).toBe(24);
expect(text.width).toBe(50);
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(30);
});
it("should unbind bound text when unbind action from context menu is triggered", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.reset();
UI.clickTool("selection");
mouse.clickAt(10, 20);
mouse.down();
mouse.up();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
null,
);
});
it("shouldn't bind to container if container has bound text", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
// Bind first text
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should respect text alignment when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
85,
5,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
375,
-539,
]
`);
});
it("should always bind to selected container and insert it in correct position", async () => {
const rectangle2 = UI.createElement("rectangle", {
x: 5,
y: 10,
width: 120,
height: 100,
});
API.setSelectedElements([rectangle]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(3);
expect(h.elements[1].type).toBe("text");
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle2.boundElements).toBeNull();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should scale font size correctly when resizing using shift", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(rectangle.width).toBe(90);
expect(rectangle.height).toBe(75);
expect(textElement.fontSize).toBe(20);
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 50], {
shift: true,
});
expect(rectangle.width).toBe(200);
expect(rectangle.height).toBe(166.66666666666669);
expect(textElement.fontSize).toBe(47.5);
});
it("should bind text correctly when container duplicated with alt-drag", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(h.elements.length).toBe(2);
mouse.select(rectangle);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle.x + 10, rectangle.y + 10);
mouse.up(rectangle.x + 10, rectangle.y + 10);
});
expect(h.elements.length).toBe(4);
const duplicatedRectangle = h.elements[0];
const duplicatedText = h
.elements[1] as ExcalidrawTextElementWithContainer;
const originalRect = h.elements[2];
const originalText = h.elements[3] as ExcalidrawTextElementWithContainer;
expect(originalRect.boundElements).toStrictEqual([
{ id: originalText.id, type: "text" },
]);
expect(originalText.containerId).toBe(originalRect.id);
expect(duplicatedRectangle.boundElements).toStrictEqual([
{ id: duplicatedText.id, type: "text" },
]);
expect(duplicatedText.containerId).toBe(duplicatedRectangle.id);
});
it("undo should work", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
const originalRectX = rectangle.x;
const originalRectY = rectangle.y;
const originalTextX = text.x;
const originalTextY = text.y;
mouse.select(rectangle);
mouse.downAt(rectangle.x, rectangle.y);
mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-35);
expect(text.x).toBe(85);
expect(text.y).toBe(-30);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(rectangle.x).toBe(originalRectX);
expect(rectangle.y).toBe(originalRectY);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.x).toBe(originalTextX);
expect(text.y).toBe(originalTextY);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should not allow bound text with only whitespaces", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: " " } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([]);
expect(h.elements[1].isDeleted).toBe(true);
});
it("should restore original container height and clear cache once text is unbind", async () => {
const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, {
target: { value: "Online whiteboard collaboration made easy" },
});
editor.blur();
expect(rectangle.height).toBe(178);
mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
expect(rectangle.height).toBe(originalRectHeight);
});
it("should reset the container height cache when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.height).toBe(156);
// cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156);
});
it("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
fireEvent.click(screen.getByTitle(/Very large/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
96.39999999999999,
);
});
describe("should align correctly", () => {
let editor: HTMLTextAreaElement;
beforeEach(async () => {
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
});
it("when top left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
25,
]
`);
});
it("when top center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
25,
]
`);
});
it("when top right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
25,
]
`);
});
it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
45.5,
]
`);
});
it("when center center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
45.5,
]
`);
});
it("when center right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
45.5,
]
`);
});
it("when bottom left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
});
it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
66,
]
`);
});
it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
66,
]
`);
});
});
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
expect(h.elements[1].width).toBe(600);
expect(h.elements[1].height).toBe(24);
expect((h.elements[1] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 34,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect((h.elements[2] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
});
});
});
| src/element/textWysiwyg.test.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.9961941242218018,
0.02687622793018818,
0.00016349634097423404,
0.00042071170173585415,
0.1347852349281311
] |
{
"id": 4,
"code_window": [
" editor.blur();\n",
" expect(h.elements[1].width).toBe(600);\n",
" expect(h.elements[1].height).toBe(24);\n",
" expect((h.elements[1] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const textElement = h.elements[1] as ExcalidrawTextElement;\n",
" expect(textElement.width).toBe(600);\n",
" expect(textElement.height).toBe(24);\n",
" expect(textElement.textAlign).toBe(TEXT_ALIGN.LEFT);\n",
" expect((textElement as ExcalidrawTextElement).text).toBe(\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1327
} | import { render, GlobalTestState } from "./test-utils";
import ExcalidrawApp from "../excalidraw-app";
import { KEYS } from "../keys";
import { Keyboard, Pointer, UI } from "./helpers/ui";
import { CURSOR_TYPE } from "../constants";
const { h } = window;
const mouse = new Pointer("mouse");
const touch = new Pointer("touch");
const pen = new Pointer("pen");
const pointerTypes = [mouse, touch, pen];
describe("view mode", () => {
beforeEach(async () => {
await render(<ExcalidrawApp />);
});
it("after switching to view mode – cursor type should be pointer", async () => {
h.setState({ viewModeEnabled: true });
expect(GlobalTestState.canvas.style.cursor).toBe(CURSOR_TYPE.GRAB);
});
it("after switching to view mode, moving, clicking, and pressing space key – cursor type should be pointer", async () => {
h.setState({ viewModeEnabled: true });
pointerTypes.forEach((pointerType) => {
const pointer = pointerType;
pointer.reset();
pointer.move(100, 100);
pointer.click();
Keyboard.keyPress(KEYS.SPACE);
expect(GlobalTestState.canvas.style.cursor).toBe(CURSOR_TYPE.GRAB);
});
});
it("cursor should stay as grabbing type when hovering over canvas elements", async () => {
// create a rectangle, then hover over it – cursor should be
// move type for mouse and grab for touch & pen
// then switch to view-mode and cursor should be grabbing type
UI.createElement("rectangle", { size: 100 });
pointerTypes.forEach((pointerType) => {
const pointer = pointerType;
pointer.moveTo(50, 50);
// eslint-disable-next-line dot-notation
if (pointerType["pointerType"] === "mouse") {
expect(GlobalTestState.canvas.style.cursor).toBe(CURSOR_TYPE.MOVE);
} else {
expect(GlobalTestState.canvas.style.cursor).toBe(CURSOR_TYPE.GRAB);
}
h.setState({ viewModeEnabled: true });
expect(GlobalTestState.canvas.style.cursor).toBe(CURSOR_TYPE.GRAB);
});
});
});
| src/tests/viewMode.test.tsx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0021936858538538218,
0.0005323117366060615,
0.0001659567788010463,
0.0001731566444505006,
0.0007450757548213005
] |
{
"id": 4,
"code_window": [
" editor.blur();\n",
" expect(h.elements[1].width).toBe(600);\n",
" expect(h.elements[1].height).toBe(24);\n",
" expect((h.elements[1] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const textElement = h.elements[1] as ExcalidrawTextElement;\n",
" expect(textElement.width).toBe(600);\n",
" expect(textElement.height).toBe(24);\n",
" expect(textElement.textAlign).toBe(TEXT_ALIGN.LEFT);\n",
" expect((textElement as ExcalidrawTextElement).text).toBe(\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1327
} | if (process.env.NODE_ENV === "production") {
module.exports = require("./dist/excalidraw.production.min.js");
} else {
module.exports = require("./dist/excalidraw.development.js");
}
| src/packages/excalidraw/main.js | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00020257243886590004,
0.00020257243886590004,
0.00020257243886590004,
0.00020257243886590004,
0
] |
{
"id": 4,
"code_window": [
" editor.blur();\n",
" expect(h.elements[1].width).toBe(600);\n",
" expect(h.elements[1].height).toBe(24);\n",
" expect((h.elements[1] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const textElement = h.elements[1] as ExcalidrawTextElement;\n",
" expect(textElement.width).toBe(600);\n",
" expect(textElement.height).toBe(24);\n",
" expect(textElement.textAlign).toBe(TEXT_ALIGN.LEFT);\n",
" expect((textElement as ExcalidrawTextElement).text).toBe(\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1327
} | import { useSetAtom } from "jotai";
import React from "react";
import { appLangCodeAtom } from "..";
import { defaultLang, useI18n } from "../../i18n";
import { languages } from "../../i18n";
export const LanguageList = ({ style }: { style?: React.CSSProperties }) => {
const { t, langCode } = useI18n();
const setLangCode = useSetAtom(appLangCodeAtom);
return (
<select
className="dropdown-select dropdown-select__language"
onChange={({ target }) => setLangCode(target.value)}
value={langCode}
aria-label={t("buttons.selectLanguage")}
style={style}
>
<option key={defaultLang.code} value={defaultLang.code}>
{defaultLang.label}
</option>
{languages.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.label}
</option>
))}
</select>
);
};
| src/excalidraw-app/components/LanguageList.tsx | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0001790561364032328,
0.00017867849965114146,
0.00017794047016650438,
0.0001790388923836872,
5.219131367084628e-7
] |
{
"id": 5,
"code_window": [
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n",
" API.setSelectedElements([h.elements[1]]);\n",
"\n",
" fireEvent.contextMenu(GlobalTestState.canvas, {\n",
" button: 2,\n",
" clientX: 20,\n",
" clientY: 30,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" API.setSelectedElements([textElement]);\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1333
} | import ReactDOM from "react-dom";
import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys";
import {
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react";
import { FONT_FAMILY } from "../constants";
import {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
} from "./types";
import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const tab = " ";
const mouse = new Pointer("mouse");
describe("textWysiwyg", () => {
describe("start text editing", () => {
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
});
it("should prefer editing selected text element (non-bindable container present)", async () => {
const line = API.createElement({
type: "line",
width: 100,
height: 0,
points: [
[0, 0],
[100, 0],
],
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: line.width / 2 - textSize / 2,
y: -textSize / 2,
width: textSize,
height: textSize,
});
h.elements = [text, line];
API.setSelectedElements([text]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
expect(
(h.state.editingElement as ExcalidrawTextElement).containerId,
).toBe(null);
});
it("should prefer editing selected text element (bindable container present)", async () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([boundText2]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText2.id);
});
it("should not create bound text on ENTER if text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
mutateElement(container, {
boundElements: [{ type: "text", id: text.id }],
});
h.elements = [container, text];
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
});
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText.id);
});
it("should edit text under cursor when clicked with text tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("text");
mouse.clickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
it("should edit text under cursor when double-clicked with selection tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("selection");
mouse.doubleClickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
});
describe("Test container-unbound text", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text");
mouse.clickOn(textElement);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "|Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
// cursor: " |Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(4);
expect(textarea.selectionEnd).toEqual(4);
});
it("should add a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "Line#1\nLin|e#2"
textarea.selectionStart = 10;
textarea.selectionEnd = 10;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
// cursor: "Line#1\n Lin|e#2"
expect(textarea.selectionStart).toEqual(14);
expect(textarea.selectionEnd).toEqual(14);
});
it("should add a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2\nLine#3";
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
textarea.selectionStart = 2;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(6);
expect(textarea.selectionEnd).toEqual(17);
});
it("should remove a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
textarea.value = `${tab}Line#1\nLine#2`;
// cursor: "| Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "|Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(0);
expect(textarea.selectionEnd).toEqual(0);
});
it("should remove a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Lin|e#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "Line#1\nLin|e#2"
expect(textarea.selectionStart).toEqual(11);
expect(textarea.selectionEnd).toEqual(11);
});
it("should remove a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
textarea.selectionStart = 6;
textarea.selectionEnd = 17;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(2);
expect(textarea.selectionEnd).toEqual(9);
});
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n | Line#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
// cursor: "Line#1\n|Line#2"
expect(textarea.selectionStart).toEqual(7);
// expect(textarea.selectionEnd).toEqual(7);
});
it("should remove partial tabs", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Line#|2"
textarea.value = `Line#1\n Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should remove nothing", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Li|ne#2"
textarea.value = `Line#1\nLine#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should resize text via shortcuts while in wysiwyg", () => {
textarea.value = "abc def";
const origFontSize = textElement.fontSize;
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_RIGHT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize * 1.1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_LEFT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize);
});
it("zooming via keyboard should zoom canvas", () => {
expect(h.state.zoom.value).toBe(1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.MINUS,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_SUBTRACT,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.8);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_ADD,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.EQUAL,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(1);
});
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
});
describe("Test container-bound text", () => {
let rectangle: any;
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
rectangle = UI.createElement("rectangle", {
x: 10,
y: 20,
width: 90,
height: 75,
});
});
it("should bind text to container when double clicked inside filled container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "red",
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "transparent",
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
expect(h.elements.length).toBe(3);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when clicked on container and enter pressed", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on container stroke", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
strokeWidth: 4,
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 2, rectangle.y + 2);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("shouldn't bind to non-text-bindable containers", async () => {
const freedraw = API.createElement({
type: "freedraw",
width: 100,
height: 0,
});
h.elements = [freedraw];
UI.clickTool("text");
mouse.clickAt(
freedraw.x + freedraw.width / 2,
freedraw.y + freedraw.height / 2,
);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
editor.dispatchEvent(new Event("input"));
expect(freedraw.boundElements).toBe(null);
expect(h.elements[1].type).toBe("text");
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = [];
const element = UI.createElement(type, {
width: 100,
height: 50,
});
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
});
it("should'nt bind text to container when not double clicked on center", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
// clicking somewhere on top left
mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toBe(null);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
UI.clickTool("text");
mouse.clickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle(/code/i));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
//undo
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Virgil);
//redo
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
});
it("should wrap text and vertcially center align once text submitted", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(25);
expect(text.height).toBe(48);
expect(text.width).toBe(60);
// Edit and text by removing second line and it should
// still vertically align correctly
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello");
expect(text.height).toBe(24);
expect(text.width).toBe(50);
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(30);
});
it("should unbind bound text when unbind action from context menu is triggered", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.reset();
UI.clickTool("selection");
mouse.clickAt(10, 20);
mouse.down();
mouse.up();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
null,
);
});
it("shouldn't bind to container if container has bound text", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
// Bind first text
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should respect text alignment when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
85,
5,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
375,
-539,
]
`);
});
it("should always bind to selected container and insert it in correct position", async () => {
const rectangle2 = UI.createElement("rectangle", {
x: 5,
y: 10,
width: 120,
height: 100,
});
API.setSelectedElements([rectangle]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(3);
expect(h.elements[1].type).toBe("text");
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle2.boundElements).toBeNull();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should scale font size correctly when resizing using shift", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(rectangle.width).toBe(90);
expect(rectangle.height).toBe(75);
expect(textElement.fontSize).toBe(20);
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 50], {
shift: true,
});
expect(rectangle.width).toBe(200);
expect(rectangle.height).toBe(166.66666666666669);
expect(textElement.fontSize).toBe(47.5);
});
it("should bind text correctly when container duplicated with alt-drag", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(h.elements.length).toBe(2);
mouse.select(rectangle);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle.x + 10, rectangle.y + 10);
mouse.up(rectangle.x + 10, rectangle.y + 10);
});
expect(h.elements.length).toBe(4);
const duplicatedRectangle = h.elements[0];
const duplicatedText = h
.elements[1] as ExcalidrawTextElementWithContainer;
const originalRect = h.elements[2];
const originalText = h.elements[3] as ExcalidrawTextElementWithContainer;
expect(originalRect.boundElements).toStrictEqual([
{ id: originalText.id, type: "text" },
]);
expect(originalText.containerId).toBe(originalRect.id);
expect(duplicatedRectangle.boundElements).toStrictEqual([
{ id: duplicatedText.id, type: "text" },
]);
expect(duplicatedText.containerId).toBe(duplicatedRectangle.id);
});
it("undo should work", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
const originalRectX = rectangle.x;
const originalRectY = rectangle.y;
const originalTextX = text.x;
const originalTextY = text.y;
mouse.select(rectangle);
mouse.downAt(rectangle.x, rectangle.y);
mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-35);
expect(text.x).toBe(85);
expect(text.y).toBe(-30);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(rectangle.x).toBe(originalRectX);
expect(rectangle.y).toBe(originalRectY);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.x).toBe(originalTextX);
expect(text.y).toBe(originalTextY);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should not allow bound text with only whitespaces", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: " " } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([]);
expect(h.elements[1].isDeleted).toBe(true);
});
it("should restore original container height and clear cache once text is unbind", async () => {
const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, {
target: { value: "Online whiteboard collaboration made easy" },
});
editor.blur();
expect(rectangle.height).toBe(178);
mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
expect(rectangle.height).toBe(originalRectHeight);
});
it("should reset the container height cache when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.height).toBe(156);
// cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156);
});
it("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
fireEvent.click(screen.getByTitle(/Very large/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
96.39999999999999,
);
});
describe("should align correctly", () => {
let editor: HTMLTextAreaElement;
beforeEach(async () => {
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
});
it("when top left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
25,
]
`);
});
it("when top center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
25,
]
`);
});
it("when top right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
25,
]
`);
});
it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
45.5,
]
`);
});
it("when center center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
45.5,
]
`);
});
it("when center right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
45.5,
]
`);
});
it("when bottom left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
});
it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
66,
]
`);
});
it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
66,
]
`);
});
});
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
expect(h.elements[1].width).toBe(600);
expect(h.elements[1].height).toBe(24);
expect((h.elements[1] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 34,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect((h.elements[2] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
});
});
});
| src/element/textWysiwyg.test.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.9950055480003357,
0.008519682101905346,
0.00016363187751267105,
0.0002782181545626372,
0.08414877951145172
] |
{
"id": 5,
"code_window": [
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n",
" API.setSelectedElements([h.elements[1]]);\n",
"\n",
" fireEvent.contextMenu(GlobalTestState.canvas, {\n",
" button: 2,\n",
" clientX: 20,\n",
" clientY: 30,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" API.setSelectedElements([textElement]);\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1333
} | {
// These tasks will run in order when initializing your CodeSandbox project.
"setupTasks": [
{
"name": "Install Dependencies",
"command": "yarn install"
}
],
// These tasks can be run from CodeSandbox. Running one will open a log in the app.
"tasks": {
"build": {
"name": "Build",
"command": "yarn build",
"runAtStart": false
},
"fix": {
"name": "Fix",
"command": "yarn fix",
"runAtStart": false
},
"prettier": {
"name": "Prettify",
"command": "yarn prettier",
"runAtStart": false
},
"start": {
"name": "Start Excalidraw",
"command": "yarn start",
"runAtStart": true
},
"test": {
"name": "Run Tests",
"command": "yarn test",
"runAtStart": false
},
"install-deps": {
"name": "Install Dependencies",
"command": "yarn install",
"restartOn": { "files": ["yarn.lock"] }
}
}
}
| .codesandbox/tasks.json | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017612420197110623,
0.00017454619228374213,
0.00017183464660774916,
0.00017465653945691884,
0.0000014700478914164705
] |
{
"id": 5,
"code_window": [
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n",
" API.setSelectedElements([h.elements[1]]);\n",
"\n",
" fireEvent.contextMenu(GlobalTestState.canvas, {\n",
" button: 2,\n",
" clientX: 20,\n",
" clientY: 30,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" API.setSelectedElements([textElement]);\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1333
} | import {
Spreadsheet,
tryParseCells,
tryParseNumber,
VALID_SPREADSHEET,
} from "./charts";
describe("charts", () => {
describe("tryParseNumber", () => {
it.each<[string, number]>([
["1", 1],
["0", 0],
["-1", -1],
["0.1", 0.1],
[".1", 0.1],
["1.", 1],
["424.", 424],
["$1", 1],
["-.1", -0.1],
["-$1", -1],
["$-1", -1],
])("should correctly identify %s as numbers", (given, expected) => {
expect(tryParseNumber(given)).toEqual(expected);
});
it.each<[string]>([["a"], ["$"], ["$a"], ["-$a"]])(
"should correctly identify %s as not a number",
(given) => {
expect(tryParseNumber(given)).toBeNull();
},
);
});
describe("tryParseCells", () => {
it("Successfully parses a spreadsheet", () => {
const spreadsheet = [
["time", "value"],
["01:00", "61"],
["02:00", "-60"],
["03:00", "85"],
["04:00", "-67"],
["05:00", "54"],
["06:00", "95"],
];
const result = tryParseCells(spreadsheet);
expect(result.type).toBe(VALID_SPREADSHEET);
const { title, labels, values } = (
result as { type: typeof VALID_SPREADSHEET; spreadsheet: Spreadsheet }
).spreadsheet;
expect(title).toEqual("value");
expect(labels).toEqual([
"01:00",
"02:00",
"03:00",
"04:00",
"05:00",
"06:00",
]);
expect(values).toEqual([61, -60, 85, -67, 54, 95]);
});
it("Uses the second column as the label if it is not a number", () => {
const spreadsheet = [
["time", "value"],
["01:00", "61"],
["02:00", "-60"],
["03:00", "85"],
["04:00", "-67"],
["05:00", "54"],
["06:00", "95"],
];
const result = tryParseCells(spreadsheet);
expect(result.type).toBe(VALID_SPREADSHEET);
const { title, labels, values } = (
result as { type: typeof VALID_SPREADSHEET; spreadsheet: Spreadsheet }
).spreadsheet;
expect(title).toEqual("value");
expect(labels).toEqual([
"01:00",
"02:00",
"03:00",
"04:00",
"05:00",
"06:00",
]);
expect(values).toEqual([61, -60, 85, -67, 54, 95]);
});
it("treats the first column as labels if both columns are numbers", () => {
const spreadsheet = [
["time", "value"],
["01", "61"],
["02", "-60"],
["03", "85"],
["04", "-67"],
["05", "54"],
["06", "95"],
];
const result = tryParseCells(spreadsheet);
expect(result.type).toBe(VALID_SPREADSHEET);
const { title, labels, values } = (
result as { type: typeof VALID_SPREADSHEET; spreadsheet: Spreadsheet }
).spreadsheet;
expect(title).toEqual("value");
expect(labels).toEqual(["01", "02", "03", "04", "05", "06"]);
expect(values).toEqual([61, -60, 85, -67, 54, 95]);
});
});
});
| src/charts.test.ts | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00017788111290428787,
0.00017412345914635807,
0.00016996166959870607,
0.00017421859956812114,
0.0000017314671367785195
] |
{
"id": 5,
"code_window": [
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
"\n",
" API.setSelectedElements([h.elements[1]]);\n",
"\n",
" fireEvent.contextMenu(GlobalTestState.canvas, {\n",
" button: 2,\n",
" clientX: 20,\n",
" clientY: 30,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" API.setSelectedElements([textElement]);\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1333
} | import { ExcalidrawElement, FileId } from "../../element/types";
import { getSceneVersion } from "../../element";
import Portal from "../collab/Portal";
import { restoreElements } from "../../data/restore";
import {
AppState,
BinaryFileData,
BinaryFileMetadata,
DataURL,
} from "../../types";
import { FILE_CACHE_MAX_AGE_SEC } from "../app_constants";
import { decompressData } from "../../data/encode";
import { encryptData, decryptData } from "../../data/encryption";
import { MIME_TYPES } from "../../constants";
import { reconcileElements } from "../collab/reconciliation";
import { getSyncableElements, SyncableExcalidrawElement } from ".";
// private
// -----------------------------------------------------------------------------
let FIREBASE_CONFIG: Record<string, any>;
try {
FIREBASE_CONFIG = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG);
} catch (error: any) {
console.warn(
`Error JSON parsing firebase config. Supplied value: ${process.env.REACT_APP_FIREBASE_CONFIG}`,
);
FIREBASE_CONFIG = {};
}
let firebasePromise: Promise<typeof import("firebase/app").default> | null =
null;
let firestorePromise: Promise<any> | null | true = null;
let firebaseStoragePromise: Promise<any> | null | true = null;
let isFirebaseInitialized = false;
const _loadFirebase = async () => {
const firebase = (
await import(/* webpackChunkName: "firebase" */ "firebase/app")
).default;
if (!isFirebaseInitialized) {
try {
firebase.initializeApp(FIREBASE_CONFIG);
} catch (error: any) {
// trying initialize again throws. Usually this is harmless, and happens
// mainly in dev (HMR)
if (error.code === "app/duplicate-app") {
console.warn(error.name, error.code);
} else {
throw error;
}
}
isFirebaseInitialized = true;
}
return firebase;
};
const _getFirebase = async (): Promise<
typeof import("firebase/app").default
> => {
if (!firebasePromise) {
firebasePromise = _loadFirebase();
}
return firebasePromise;
};
// -----------------------------------------------------------------------------
const loadFirestore = async () => {
const firebase = await _getFirebase();
if (!firestorePromise) {
firestorePromise = import(
/* webpackChunkName: "firestore" */ "firebase/firestore"
);
}
if (firestorePromise !== true) {
await firestorePromise;
firestorePromise = true;
}
return firebase;
};
export const loadFirebaseStorage = async () => {
const firebase = await _getFirebase();
if (!firebaseStoragePromise) {
firebaseStoragePromise = import(
/* webpackChunkName: "storage" */ "firebase/storage"
);
}
if (firebaseStoragePromise !== true) {
await firebaseStoragePromise;
firebaseStoragePromise = true;
}
return firebase;
};
interface FirebaseStoredScene {
sceneVersion: number;
iv: firebase.default.firestore.Blob;
ciphertext: firebase.default.firestore.Blob;
}
const encryptElements = async (
key: string,
elements: readonly ExcalidrawElement[],
): Promise<{ ciphertext: ArrayBuffer; iv: Uint8Array }> => {
const json = JSON.stringify(elements);
const encoded = new TextEncoder().encode(json);
const { encryptedBuffer, iv } = await encryptData(key, encoded);
return { ciphertext: encryptedBuffer, iv };
};
const decryptElements = async (
data: FirebaseStoredScene,
roomKey: string,
): Promise<readonly ExcalidrawElement[]> => {
const ciphertext = data.ciphertext.toUint8Array();
const iv = data.iv.toUint8Array();
const decrypted = await decryptData(iv, ciphertext, roomKey);
const decodedData = new TextDecoder("utf-8").decode(
new Uint8Array(decrypted),
);
return JSON.parse(decodedData);
};
class FirebaseSceneVersionCache {
private static cache = new WeakMap<SocketIOClient.Socket, number>();
static get = (socket: SocketIOClient.Socket) => {
return FirebaseSceneVersionCache.cache.get(socket);
};
static set = (
socket: SocketIOClient.Socket,
elements: readonly SyncableExcalidrawElement[],
) => {
FirebaseSceneVersionCache.cache.set(socket, getSceneVersion(elements));
};
}
export const isSavedToFirebase = (
portal: Portal,
elements: readonly ExcalidrawElement[],
): boolean => {
if (portal.socket && portal.roomId && portal.roomKey) {
const sceneVersion = getSceneVersion(elements);
return FirebaseSceneVersionCache.get(portal.socket) === sceneVersion;
}
// if no room exists, consider the room saved so that we don't unnecessarily
// prevent unload (there's nothing we could do at that point anyway)
return true;
};
export const saveFilesToFirebase = async ({
prefix,
files,
}: {
prefix: string;
files: { id: FileId; buffer: Uint8Array }[];
}) => {
const firebase = await loadFirebaseStorage();
const erroredFiles = new Map<FileId, true>();
const savedFiles = new Map<FileId, true>();
await Promise.all(
files.map(async ({ id, buffer }) => {
try {
await firebase
.storage()
.ref(`${prefix}/${id}`)
.put(
new Blob([buffer], {
type: MIME_TYPES.binary,
}),
{
cacheControl: `public, max-age=${FILE_CACHE_MAX_AGE_SEC}`,
},
);
savedFiles.set(id, true);
} catch (error: any) {
erroredFiles.set(id, true);
}
}),
);
return { savedFiles, erroredFiles };
};
const createFirebaseSceneDocument = async (
firebase: ResolutionType<typeof loadFirestore>,
elements: readonly SyncableExcalidrawElement[],
roomKey: string,
) => {
const sceneVersion = getSceneVersion(elements);
const { ciphertext, iv } = await encryptElements(roomKey, elements);
return {
sceneVersion,
ciphertext: firebase.firestore.Blob.fromUint8Array(
new Uint8Array(ciphertext),
),
iv: firebase.firestore.Blob.fromUint8Array(iv),
} as FirebaseStoredScene;
};
export const saveToFirebase = async (
portal: Portal,
elements: readonly SyncableExcalidrawElement[],
appState: AppState,
) => {
const { roomId, roomKey, socket } = portal;
if (
// bail if no room exists as there's nothing we can do at this point
!roomId ||
!roomKey ||
!socket ||
isSavedToFirebase(portal, elements)
) {
return false;
}
const firebase = await loadFirestore();
const firestore = firebase.firestore();
const docRef = firestore.collection("scenes").doc(roomId);
const savedData = await firestore.runTransaction(async (transaction) => {
const snapshot = await transaction.get(docRef);
if (!snapshot.exists) {
const sceneDocument = await createFirebaseSceneDocument(
firebase,
elements,
roomKey,
);
transaction.set(docRef, sceneDocument);
return {
elements,
reconciledElements: null,
};
}
const prevDocData = snapshot.data() as FirebaseStoredScene;
const prevElements = getSyncableElements(
await decryptElements(prevDocData, roomKey),
);
const reconciledElements = getSyncableElements(
reconcileElements(elements, prevElements, appState),
);
const sceneDocument = await createFirebaseSceneDocument(
firebase,
reconciledElements,
roomKey,
);
transaction.update(docRef, sceneDocument);
return {
elements,
reconciledElements,
};
});
FirebaseSceneVersionCache.set(socket, savedData.elements);
return { reconciledElements: savedData.reconciledElements };
};
export const loadFromFirebase = async (
roomId: string,
roomKey: string,
socket: SocketIOClient.Socket | null,
): Promise<readonly ExcalidrawElement[] | null> => {
const firebase = await loadFirestore();
const db = firebase.firestore();
const docRef = db.collection("scenes").doc(roomId);
const doc = await docRef.get();
if (!doc.exists) {
return null;
}
const storedScene = doc.data() as FirebaseStoredScene;
const elements = getSyncableElements(
await decryptElements(storedScene, roomKey),
);
if (socket) {
FirebaseSceneVersionCache.set(socket, elements);
}
return restoreElements(elements, null);
};
export const loadFilesFromFirebase = async (
prefix: string,
decryptionKey: string,
filesIds: readonly FileId[],
) => {
const loadedFiles: BinaryFileData[] = [];
const erroredFiles = new Map<FileId, true>();
await Promise.all(
[...new Set(filesIds)].map(async (id) => {
try {
const url = `https://firebasestorage.googleapis.com/v0/b/${
FIREBASE_CONFIG.storageBucket
}/o/${encodeURIComponent(prefix.replace(/^\//, ""))}%2F${id}`;
const response = await fetch(`${url}?alt=media`);
if (response.status < 400) {
const arrayBuffer = await response.arrayBuffer();
const { data, metadata } = await decompressData<BinaryFileMetadata>(
new Uint8Array(arrayBuffer),
{
decryptionKey,
},
);
const dataURL = new TextDecoder().decode(data) as DataURL;
loadedFiles.push({
mimeType: metadata.mimeType || MIME_TYPES.binary,
id,
dataURL,
created: metadata?.created || Date.now(),
lastRetrieved: metadata?.created || Date.now(),
});
} else {
erroredFiles.set(id, true);
}
} catch (error: any) {
erroredFiles.set(id, true);
console.error(error);
}
}),
);
return { loadedFiles, erroredFiles };
};
| src/excalidraw-app/data/firebase.ts | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.001121842535212636,
0.0002726831298787147,
0.00016281665011774749,
0.00017600785940885544,
0.00021307812130544335
] |
{
"id": 6,
"code_window": [
" x: 15,\n",
" y: 25,\n",
" }),\n",
" );\n",
" expect((h.elements[2] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
" });\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(h.elements[2] as ExcalidrawTextElement).toEqual(\n",
" expect.objectContaining({\n",
" text: \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.LEFT,\n",
" boundElements: null,\n",
" }),\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1379
} | import ReactDOM from "react-dom";
import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys";
import {
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react";
import { FONT_FAMILY } from "../constants";
import {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
} from "./types";
import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const tab = " ";
const mouse = new Pointer("mouse");
describe("textWysiwyg", () => {
describe("start text editing", () => {
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
});
it("should prefer editing selected text element (non-bindable container present)", async () => {
const line = API.createElement({
type: "line",
width: 100,
height: 0,
points: [
[0, 0],
[100, 0],
],
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: line.width / 2 - textSize / 2,
y: -textSize / 2,
width: textSize,
height: textSize,
});
h.elements = [text, line];
API.setSelectedElements([text]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
expect(
(h.state.editingElement as ExcalidrawTextElement).containerId,
).toBe(null);
});
it("should prefer editing selected text element (bindable container present)", async () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([boundText2]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText2.id);
});
it("should not create bound text on ENTER if text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
});
const textSize = 20;
const text = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
mutateElement(container, {
boundElements: [{ type: "text", id: text.id }],
});
h.elements = [container, text];
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(text.id);
});
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
const container = API.createElement({
type: "rectangle",
width: 100,
boundElements: [],
});
const textSize = 20;
const boundText = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
const boundText2 = API.createElement({
type: "text",
text: "ola",
x: container.width / 2 - textSize / 2,
y: container.height / 2 - textSize / 2,
width: textSize,
height: textSize,
containerId: container.id,
});
h.elements = [container, boundText, boundText2];
mutateElement(container, {
boundElements: [{ type: "text", id: boundText.id }],
});
API.setSelectedElements([container]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingElement?.id).toBe(boundText.id);
});
it("should edit text under cursor when clicked with text tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("text");
mouse.clickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
it("should edit text under cursor when double-clicked with selection tool", () => {
const text = API.createElement({
type: "text",
text: "ola",
x: 60,
y: 0,
width: 100,
height: 100,
});
h.elements = [text];
UI.clickTool("selection");
mouse.doubleClickAt(text.x + 50, text.y + 50);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
expect(editor).not.toBe(null);
expect(h.state.editingElement?.id).toBe(text.id);
expect(h.elements.length).toBe(1);
});
});
describe("Test container-unbound text", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text");
mouse.clickOn(textElement);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "|Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
// cursor: " |Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(4);
expect(textarea.selectionEnd).toEqual(4);
});
it("should add a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2";
// cursor: "Line#1\nLin|e#2"
textarea.selectionStart = 10;
textarea.selectionEnd = 10;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
// cursor: "Line#1\n Lin|e#2"
expect(textarea.selectionStart).toEqual(14);
expect(textarea.selectionEnd).toEqual(14);
});
it("should add a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2\nLine#3";
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
textarea.selectionStart = 2;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(6);
expect(textarea.selectionEnd).toEqual(17);
});
it("should remove a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
textarea.value = `${tab}Line#1\nLine#2`;
// cursor: "| Line#1\nLine#2"
textarea.selectionStart = 0;
textarea.selectionEnd = 0;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "|Line#1\nLine#2"
expect(textarea.selectionStart).toEqual(0);
expect(textarea.selectionEnd).toEqual(0);
});
it("should remove a tab at the start of the second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Lin|e#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
// cursor: "Line#1\nLin|e#2"
expect(textarea.selectionStart).toEqual(11);
expect(textarea.selectionEnd).toEqual(11);
});
it("should remove a tab at the start of the first and second line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
textarea.selectionStart = 6;
textarea.selectionEnd = 17;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
expect(textarea.selectionStart).toEqual(2);
expect(textarea.selectionEnd).toEqual(9);
});
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n | Line#2"
textarea.value = `Line#1\n${tab}Line#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
// cursor: "Line#1\n|Line#2"
expect(textarea.selectionStart).toEqual(7);
// expect(textarea.selectionEnd).toEqual(7);
});
it("should remove partial tabs", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Line#|2"
textarea.value = `Line#1\n Line#2`;
textarea.selectionStart = 15;
textarea.selectionEnd = 15;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should remove nothing", () => {
const event = new KeyboardEvent("keydown", {
key: KEYS.TAB,
shiftKey: true,
});
// cursor: "Line#1\n Li|ne#2"
textarea.value = `Line#1\nLine#2`;
textarea.selectionStart = 9;
textarea.selectionEnd = 9;
textarea.dispatchEvent(event);
expect(textarea.value).toEqual(`Line#1\nLine#2`);
});
it("should resize text via shortcuts while in wysiwyg", () => {
textarea.value = "abc def";
const origFontSize = textElement.fontSize;
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_RIGHT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize * 1.1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
key: KEYS.CHEVRON_LEFT,
ctrlKey: true,
shiftKey: true,
}),
);
expect(textElement.fontSize).toBe(origFontSize);
});
it("zooming via keyboard should zoom canvas", () => {
expect(h.state.zoom.value).toBe(1);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.MINUS,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_SUBTRACT,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.8);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.NUM_ADD,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(0.9);
textarea.dispatchEvent(
new KeyboardEvent("keydown", {
code: CODES.EQUAL,
ctrlKey: true,
}),
);
expect(h.state.zoom.value).toBe(1);
});
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
});
describe("Test container-bound text", () => {
let rectangle: any;
const { h } = window;
beforeEach(async () => {
await render(<ExcalidrawApp />);
h.elements = [];
rectangle = UI.createElement("rectangle", {
x: 10,
y: 20,
width: 90,
height: 75,
});
});
it("should bind text to container when double clicked inside filled container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "red",
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
backgroundColor: "transparent",
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
expect(h.elements.length).toBe(2);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
expect(h.elements.length).toBe(3);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when clicked on container and enter pressed", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should bind text to container when double clicked on container stroke", async () => {
const rectangle = API.createElement({
type: "rectangle",
x: 10,
y: 20,
width: 90,
height: 75,
strokeWidth: 4,
});
h.elements = [rectangle];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
mouse.doubleClickAt(rectangle.x + 2, rectangle.y + 2);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("shouldn't bind to non-text-bindable containers", async () => {
const freedraw = API.createElement({
type: "freedraw",
width: 100,
height: 0,
});
h.elements = [freedraw];
UI.clickTool("text");
mouse.clickAt(
freedraw.x + freedraw.width / 2,
freedraw.y + freedraw.height / 2,
);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
editor.dispatchEvent(new Event("input"));
expect(freedraw.boundElements).toBe(null);
expect(h.elements[1].type).toBe("text");
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = [];
const element = UI.createElement(type, {
width: 100,
height: 50,
});
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
});
it("should'nt bind text to container when not double clicked on center", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
// clicking somewhere on top left
mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(null);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toBe(null);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
UI.clickTool("text");
mouse.clickAt(
rectangle.x + rectangle.width / 2,
rectangle.y + rectangle.height / 2,
);
mouse.down();
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle(/code/i));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
//undo
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Virgil);
//redo
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
});
it("should wrap text and vertcially center align once text submitted", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello World!",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(25);
expect(text.height).toBe(48);
expect(text.width).toBe(60);
// Edit and text by removing second line and it should
// still vertically align correctly
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Hello",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello");
expect(text.height).toBe(24);
expect(text.width).toBe(50);
expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2,
);
expect(text.x).toBe(30);
});
it("should unbind bound text when unbind action from context menu is triggered", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.reset();
UI.clickTool("selection");
mouse.clickAt(10, 20);
mouse.down();
mouse.up();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
null,
);
});
it("shouldn't bind to container if container has bound text", async () => {
expect(h.elements.length).toBe(1);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
// Bind first text
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.containerId).toBe(rectangle.id);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should respect text alignment when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
85,
5,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
375,
-539,
]
`);
});
it("should always bind to selected container and insert it in correct position", async () => {
const rectangle2 = UI.createElement("rectangle", {
x: 5,
y: 10,
width: 120,
height: 100,
});
API.setSelectedElements([rectangle]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(3);
expect(h.elements[1].type).toBe("text");
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle2.boundElements).toBeNull();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should scale font size correctly when resizing using shift", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(rectangle.width).toBe(90);
expect(rectangle.height).toBe(75);
expect(textElement.fontSize).toBe(20);
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 50], {
shift: true,
});
expect(rectangle.width).toBe(200);
expect(rectangle.height).toBe(166.66666666666669);
expect(textElement.fontSize).toBe(47.5);
});
it("should bind text correctly when container duplicated with alt-drag", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(h.elements.length).toBe(2);
mouse.select(rectangle);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle.x + 10, rectangle.y + 10);
mouse.up(rectangle.x + 10, rectangle.y + 10);
});
expect(h.elements.length).toBe(4);
const duplicatedRectangle = h.elements[0];
const duplicatedText = h
.elements[1] as ExcalidrawTextElementWithContainer;
const originalRect = h.elements[2];
const originalText = h.elements[3] as ExcalidrawTextElementWithContainer;
expect(originalRect.boundElements).toStrictEqual([
{ id: originalText.id, type: "text" },
]);
expect(originalText.containerId).toBe(originalRect.id);
expect(duplicatedRectangle.boundElements).toStrictEqual([
{ id: duplicatedText.id, type: "text" },
]);
expect(duplicatedText.containerId).toBe(duplicatedRectangle.id);
});
it("undo should work", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
const originalRectX = rectangle.x;
const originalRectY = rectangle.y;
const originalTextX = text.x;
const originalTextY = text.y;
mouse.select(rectangle);
mouse.downAt(rectangle.x, rectangle.y);
mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-35);
expect(text.x).toBe(85);
expect(text.y).toBe(-30);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z);
});
expect(rectangle.x).toBe(originalRectX);
expect(rectangle.y).toBe(originalRectY);
text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.x).toBe(originalTextX);
expect(text.y).toBe(originalTextY);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
});
it("should not allow bound text with only whitespaces", async () => {
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: " " } });
editor.blur();
expect(rectangle.boundElements).toStrictEqual([]);
expect(h.elements[1].isDeleted).toBe(true);
});
it("should restore original container height and clear cache once text is unbind", async () => {
const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, {
target: { value: "Online whiteboard collaboration made easy" },
});
editor.blur();
expect(rectangle.height).toBe(178);
mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(h.elements[0].boundElements).toEqual([]);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
expect(rectangle.height).toBe(originalRectHeight);
});
it("should reset the container height cache when resizing", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
let editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.height).toBe(156);
// cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156);
});
it("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
fireEvent.click(screen.getByTitle(/Very large/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(
96.39999999999999,
);
});
describe("should align correctly", () => {
let editor: HTMLTextAreaElement;
beforeEach(async () => {
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello" } });
editor.blur();
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
editor.select();
});
it("when top left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
25,
]
`);
});
it("when top center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
25,
]
`);
});
it("when top right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
25,
]
`);
});
it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
45.5,
]
`);
});
it("when center center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
45.5,
]
`);
});
it("when center right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
45.5,
]
`);
});
it("when bottom left", async () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
15,
66,
]
`);
});
it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
30,
66,
]
`);
});
it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
45,
66,
]
`);
});
});
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.blur();
expect(h.elements[1].width).toBe(600);
expect(h.elements[1].height).toBe(24);
expect((h.elements[1] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 34,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect((h.elements[2] as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
});
});
});
| src/element/textWysiwyg.test.tsx | 1 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.8388929963111877,
0.010375996120274067,
0.0001598547532921657,
0.00022606873244512826,
0.07299160957336426
] |
{
"id": 6,
"code_window": [
" x: 15,\n",
" y: 25,\n",
" }),\n",
" );\n",
" expect((h.elements[2] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
" });\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(h.elements[2] as ExcalidrawTextElement).toEqual(\n",
" expect.objectContaining({\n",
" text: \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.LEFT,\n",
" boundElements: null,\n",
" }),\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1379
} | this.workbox=this.workbox||{},this.workbox.strategies=function(e,t,s,n,r){"use strict";try{self["workbox:strategies:4.3.1"]&&_()}catch(e){}class i{constructor(e={}){this.t=t.cacheNames.getRuntimeName(e.cacheName),this.s=e.plugins||[],this.i=e.fetchOptions||null,this.h=e.matchOptions||null}async handle({event:e,request:t}){return this.makeRequest({event:e,request:t||e.request})}async makeRequest({event:e,request:t}){"string"==typeof t&&(t=new Request(t));let n,i=await s.cacheWrapper.match({cacheName:this.t,request:t,event:e,matchOptions:this.h,plugins:this.s});if(!i)try{i=await this.u(t,e)}catch(e){n=e}if(!i)throw new r.WorkboxError("no-response",{url:t.url,error:n});return i}async u(e,t){const r=await n.fetchWrapper.fetch({request:e,event:t,fetchOptions:this.i,plugins:this.s}),i=r.clone(),h=s.cacheWrapper.put({cacheName:this.t,request:e,response:i,event:t,plugins:this.s});if(t)try{t.waitUntil(h)}catch(e){}return r}}class h{constructor(e={}){this.t=t.cacheNames.getRuntimeName(e.cacheName),this.s=e.plugins||[],this.h=e.matchOptions||null}async handle({event:e,request:t}){return this.makeRequest({event:e,request:t||e.request})}async makeRequest({event:e,request:t}){"string"==typeof t&&(t=new Request(t));const n=await s.cacheWrapper.match({cacheName:this.t,request:t,event:e,matchOptions:this.h,plugins:this.s});if(!n)throw new r.WorkboxError("no-response",{url:t.url});return n}}const u={cacheWillUpdate:({response:e})=>200===e.status||0===e.status?e:null};class a{constructor(e={}){if(this.t=t.cacheNames.getRuntimeName(e.cacheName),e.plugins){let t=e.plugins.some(e=>!!e.cacheWillUpdate);this.s=t?e.plugins:[u,...e.plugins]}else this.s=[u];this.o=e.networkTimeoutSeconds,this.i=e.fetchOptions||null,this.h=e.matchOptions||null}async handle({event:e,request:t}){return this.makeRequest({event:e,request:t||e.request})}async makeRequest({event:e,request:t}){const s=[];"string"==typeof t&&(t=new Request(t));const n=[];let i;if(this.o){const{id:r,promise:h}=this.l({request:t,event:e,logs:s});i=r,n.push(h)}const h=this.q({timeoutId:i,request:t,event:e,logs:s});n.push(h);let u=await Promise.race(n);if(u||(u=await h),!u)throw new r.WorkboxError("no-response",{url:t.url});return u}l({request:e,logs:t,event:s}){let n;return{promise:new Promise(t=>{n=setTimeout(async()=>{t(await this.p({request:e,event:s}))},1e3*this.o)}),id:n}}async q({timeoutId:e,request:t,logs:r,event:i}){let h,u;try{u=await n.fetchWrapper.fetch({request:t,event:i,fetchOptions:this.i,plugins:this.s})}catch(e){h=e}if(e&&clearTimeout(e),h||!u)u=await this.p({request:t,event:i});else{const e=u.clone(),n=s.cacheWrapper.put({cacheName:this.t,request:t,response:e,event:i,plugins:this.s});if(i)try{i.waitUntil(n)}catch(e){}}return u}p({event:e,request:t}){return s.cacheWrapper.match({cacheName:this.t,request:t,event:e,matchOptions:this.h,plugins:this.s})}}class c{constructor(e={}){this.t=t.cacheNames.getRuntimeName(e.cacheName),this.s=e.plugins||[],this.i=e.fetchOptions||null}async handle({event:e,request:t}){return this.makeRequest({event:e,request:t||e.request})}async makeRequest({event:e,request:t}){let s,i;"string"==typeof t&&(t=new Request(t));try{i=await n.fetchWrapper.fetch({request:t,event:e,fetchOptions:this.i,plugins:this.s})}catch(e){s=e}if(!i)throw new r.WorkboxError("no-response",{url:t.url,error:s});return i}}class o{constructor(e={}){if(this.t=t.cacheNames.getRuntimeName(e.cacheName),this.s=e.plugins||[],e.plugins){let t=e.plugins.some(e=>!!e.cacheWillUpdate);this.s=t?e.plugins:[u,...e.plugins]}else this.s=[u];this.i=e.fetchOptions||null,this.h=e.matchOptions||null}async handle({event:e,request:t}){return this.makeRequest({event:e,request:t||e.request})}async makeRequest({event:e,request:t}){"string"==typeof t&&(t=new Request(t));const n=this.u({request:t,event:e});let i,h=await s.cacheWrapper.match({cacheName:this.t,request:t,event:e,matchOptions:this.h,plugins:this.s});if(h){if(e)try{e.waitUntil(n)}catch(i){}}else try{h=await n}catch(e){i=e}if(!h)throw new r.WorkboxError("no-response",{url:t.url,error:i});return h}async u({request:e,event:t}){const r=await n.fetchWrapper.fetch({request:e,event:t,fetchOptions:this.i,plugins:this.s}),i=s.cacheWrapper.put({cacheName:this.t,request:e,response:r.clone(),event:t,plugins:this.s});if(t)try{t.waitUntil(i)}catch(e){}return r}}const l={cacheFirst:i,cacheOnly:h,networkFirst:a,networkOnly:c,staleWhileRevalidate:o},q=e=>{const t=l[e];return e=>new t(e)},w=q("cacheFirst"),p=q("cacheOnly"),v=q("networkFirst"),y=q("networkOnly"),m=q("staleWhileRevalidate");return e.CacheFirst=i,e.CacheOnly=h,e.NetworkFirst=a,e.NetworkOnly=c,e.StaleWhileRevalidate=o,e.cacheFirst=w,e.cacheOnly=p,e.networkFirst=v,e.networkOnly=y,e.staleWhileRevalidate=m,e}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private);
//# sourceMappingURL=workbox-strategies.prod.js.map
| public/workbox/workbox-strategies.prod.js | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0001894619781523943,
0.0001894619781523943,
0.0001894619781523943,
0.0001894619781523943,
0
] |
{
"id": 6,
"code_window": [
" x: 15,\n",
" y: 25,\n",
" }),\n",
" );\n",
" expect((h.elements[2] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
" });\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(h.elements[2] as ExcalidrawTextElement).toEqual(\n",
" expect.objectContaining({\n",
" text: \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.LEFT,\n",
" boundElements: null,\n",
" }),\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1379
} | this.workbox=this.workbox||{},this.workbox.googleAnalytics=function(e,t,o,n,a,c,w){"use strict";try{self["workbox:google-analytics:4.3.1"]&&_()}catch(e){}const r=/^\/(\w+\/)?collect/,s=e=>async({queue:t})=>{let o;for(;o=await t.shiftRequest();){const{request:n,timestamp:a}=o,c=new URL(n.url);try{const w="POST"===n.method?new URLSearchParams(await n.clone().text()):c.searchParams,r=a-(Number(w.get("qt"))||0),s=Date.now()-r;if(w.set("qt",s),e.parameterOverrides)for(const t of Object.keys(e.parameterOverrides)){const o=e.parameterOverrides[t];w.set(t,o)}"function"==typeof e.hitFilter&&e.hitFilter.call(null,w),await fetch(new Request(c.origin+c.pathname,{body:w.toString(),method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"text/plain"}}))}catch(e){throw await t.unshiftRequest(o),e}}},i=e=>{const t=({url:e})=>"www.google-analytics.com"===e.hostname&&r.test(e.pathname),o=new w.NetworkOnly({plugins:[e]});return[new n.Route(t,o,"GET"),new n.Route(t,o,"POST")]},l=e=>{const t=new c.NetworkFirst({cacheName:e});return new n.Route(({url:e})=>"www.google-analytics.com"===e.hostname&&"/analytics.js"===e.pathname,t,"GET")},m=e=>{const t=new c.NetworkFirst({cacheName:e});return new n.Route(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtag/js"===e.pathname,t,"GET")},u=e=>{const t=new c.NetworkFirst({cacheName:e});return new n.Route(({url:e})=>"www.googletagmanager.com"===e.hostname&&"/gtm.js"===e.pathname,t,"GET")};return e.initialize=((e={})=>{const n=o.cacheNames.getGoogleAnalyticsName(e.cacheName),c=new t.Plugin("workbox-google-analytics",{maxRetentionTime:2880,onSync:s(e)}),w=[u(n),l(n),m(n),...i(c)],r=new a.Router;for(const e of w)r.registerRoute(e);r.addFetchListener()}),e}({},workbox.backgroundSync,workbox.core._private,workbox.routing,workbox.routing,workbox.strategies,workbox.strategies);
//# sourceMappingURL=workbox-offline-ga.prod.js.map
| public/workbox/workbox-offline-ga.prod.js | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.0001659482513787225,
0.0001659482513787225,
0.0001659482513787225,
0.0001659482513787225,
0
] |
{
"id": 6,
"code_window": [
" x: 15,\n",
" y: 25,\n",
" }),\n",
" );\n",
" expect((h.elements[2] as ExcalidrawTextElement).text).toBe(\n",
" \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" );\n",
" });\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(h.elements[2] as ExcalidrawTextElement).toEqual(\n",
" expect.objectContaining({\n",
" text: \"Excalidraw is an opensource virtual collaborative whiteboard\",\n",
" verticalAlign: VERTICAL_ALIGN.MIDDLE,\n",
" textAlign: TEXT_ALIGN.LEFT,\n",
" boundElements: null,\n",
" }),\n"
],
"file_path": "src/element/textWysiwyg.test.tsx",
"type": "replace",
"edit_start_line_idx": 1379
} | @import "../css/variables.module";
.excalidraw {
.single-library-item {
position: relative;
&-status {
position: absolute;
top: 0.3rem;
left: 0.3rem;
font-size: 0.7rem;
color: $oc-red-7;
background: rgba(255, 255, 255, 0.9);
padding: 0.1rem 0.2rem;
border-radius: 0.2rem;
}
&__svg {
background-color: $oc-white;
padding: 0.3rem;
width: 7.5rem;
height: 7.5rem;
border: 1px solid var(--button-gray-2);
svg {
width: 100%;
height: 100%;
}
}
.ToolIcon__icon {
background-color: $oc-white;
width: auto;
height: auto;
margin: 0 0.5rem;
}
.ToolIcon,
.ToolIcon_type_button:hover {
background-color: white;
}
.required,
.error {
color: $oc-red-8;
font-weight: bold;
font-size: 1rem;
margin: 0.2rem;
}
.error {
font-weight: 500;
margin: 0;
padding: 0.3em 0;
}
&--remove {
position: absolute;
top: 0.2rem;
right: 1rem;
.ToolIcon__icon {
margin: 0;
}
.ToolIcon__icon {
background-color: $oc-red-6;
&:hover {
background-color: $oc-red-7;
}
&:active {
background-color: $oc-red-8;
}
}
svg {
color: $oc-white;
padding: 0.26rem;
border-radius: 0.3em;
width: 1rem;
height: 1rem;
}
}
}
}
| src/components/SingleLibraryItem.scss | 0 | https://github.com/excalidraw/excalidraw/commit/5c0b15ce2b7f4f3ad80892bff55246a55995778f | [
0.00018229409761261195,
0.00017821777146309614,
0.00017508340533822775,
0.00017823933740146458,
0.000002257821961393347
] |
{
"id": 0,
"code_window": [
"\t\t\t\tconst onDidRemoveLM = Event.filter(that._onDidChangeProviders.event, e => e.removed.includes(languageModelId));\n",
"\t\t\t\treturn Event.signal(Event.any(onDidChangeAccess, onDidRemoveLM));\n",
"\t\t\t},\n",
"\t\t\tmakeRequest(messages, options, token) {\n",
"\t\t\t\tif (!that._accesslist.get(from)) {\n",
"\t\t\t\t\tthrow new Error('Access to chat has been revoked');\n",
"\t\t\t\t}\n",
"\t\t\t\tif (!that._languageModelIds.has(languageModelId)) {\n",
"\t\t\t\t\tthrow new Error('Language Model has been removed');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tmakeChatRequest(messages, options, token) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostChatProvider.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.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
export interface LanguageModelResponse {
/**
* The overall result of the request which represents failure or success
* but _not_ the actual response or responses
*/
// TODO@API define this type!
result: Thenable<unknown>;
stream: AsyncIterable<string>;
}
/**
* Represents access to using a language model. Access can be revoked at any time and extension
* must check if the access is {@link LanguageModelAccess.isRevoked still valid} before using it.
*/
export interface LanguageModelAccess {
/**
* Whether the access to the language model has been revoked.
*/
readonly isRevoked: boolean;
/**
* An event that is fired when the access the language model has has been revoked or re-granted.
*/
readonly onDidChangeAccess: Event<void>;
/**
* The name of the model.
*
* It is expected that the model name can be used to lookup properties like token limits or what
* `options` are available.
*/
readonly model: string;
/**
* Make a request to the language model.
*
* *Note:* This will throw an error if access has been revoked.
*
* @param messages
* @param options
*/
makeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;
}
export interface LanguageModelAccessOptions {
/**
* A human-readable message that explains why access to a language model is needed and what feature is enabled by it.
*/
justification?: string;
}
/**
* An event describing the change in the set of available language models.
*/
export interface LanguageModelChangeEvent {
/**
* Added language models.
*/
readonly added: readonly string[];
/**
* Removed language models.
*/
readonly removed: readonly string[];
}
//@API DEFINE the namespace for this: env, lm, ai?
export namespace chat {
/**
* Request access to a language model.
*
* *Note* that this function will throw an error when the user didn't grant access
*
* @param id The id of the language model, e.g `copilot`
* @returns A thenable that resolves to a language model access object, rejects is access wasn't granted
*/
export function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;
/**
* The identifiers of all language models that are currently available.
*/
export const languageModels: readonly string[];
/**
* An event that is fired when the set of available language models changes.
*/
//@API is this really needed?
export const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;
}
}
| src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.011384956538677216,
0.001983225578442216,
0.00016383639012929052,
0.0009196386090479791,
0.003104811767116189
] |
{
"id": 0,
"code_window": [
"\t\t\t\tconst onDidRemoveLM = Event.filter(that._onDidChangeProviders.event, e => e.removed.includes(languageModelId));\n",
"\t\t\t\treturn Event.signal(Event.any(onDidChangeAccess, onDidRemoveLM));\n",
"\t\t\t},\n",
"\t\t\tmakeRequest(messages, options, token) {\n",
"\t\t\t\tif (!that._accesslist.get(from)) {\n",
"\t\t\t\t\tthrow new Error('Access to chat has been revoked');\n",
"\t\t\t\t}\n",
"\t\t\t\tif (!that._languageModelIds.has(languageModelId)) {\n",
"\t\t\t\t\tthrow new Error('Language Model has been removed');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tmakeChatRequest(messages, options, token) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostChatProvider.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 { URI } from 'vs/base/common/uri';
import { RunOnceScheduler } from 'vs/base/common/async';
import { IModelService } from 'vs/editor/common/services/model';
import { ILink } from 'vs/editor/common/languages';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OUTPUT_MODE_ID, LOG_MODE_ID } from 'vs/workbench/services/output/common/output';
import { MonacoWebWorker, createWebWorker } from 'vs/editor/browser/services/webWorker';
import { ICreateData, OutputLinkComputer } from 'vs/workbench/contrib/output/common/outputLinkComputer';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
export class OutputLinkProvider {
private static readonly DISPOSE_WORKER_TIME = 3 * 60 * 1000; // dispose worker after 3 minutes of inactivity
private worker?: MonacoWebWorker<OutputLinkComputer>;
private disposeWorkerScheduler: RunOnceScheduler;
private linkProviderRegistration: IDisposable | undefined;
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IModelService private readonly modelService: IModelService,
@ILanguageConfigurationService private readonly languageConfigurationService: ILanguageConfigurationService,
@ILanguageFeaturesService private readonly languageFeaturesService: ILanguageFeaturesService,
) {
this.disposeWorkerScheduler = new RunOnceScheduler(() => this.disposeWorker(), OutputLinkProvider.DISPOSE_WORKER_TIME);
this.registerListeners();
this.updateLinkProviderWorker();
}
private registerListeners(): void {
this.contextService.onDidChangeWorkspaceFolders(() => this.updateLinkProviderWorker());
}
private updateLinkProviderWorker(): void {
// Setup link provider depending on folders being opened or not
const folders = this.contextService.getWorkspace().folders;
if (folders.length > 0) {
if (!this.linkProviderRegistration) {
this.linkProviderRegistration = this.languageFeaturesService.linkProvider.register([{ language: OUTPUT_MODE_ID, scheme: '*' }, { language: LOG_MODE_ID, scheme: '*' }], {
provideLinks: async model => {
const links = await this.provideLinks(model.uri);
return links && { links };
}
});
}
} else {
dispose(this.linkProviderRegistration);
this.linkProviderRegistration = undefined;
}
// Dispose worker to recreate with folders on next provideLinks request
this.disposeWorker();
this.disposeWorkerScheduler.cancel();
}
private getOrCreateWorker(): MonacoWebWorker<OutputLinkComputer> {
this.disposeWorkerScheduler.schedule();
if (!this.worker) {
const createData: ICreateData = {
workspaceFolders: this.contextService.getWorkspace().folders.map(folder => folder.uri.toString())
};
this.worker = createWebWorker<OutputLinkComputer>(this.modelService, this.languageConfigurationService, {
moduleId: 'vs/workbench/contrib/output/common/outputLinkComputer',
createData,
label: 'outputLinkComputer'
});
}
return this.worker;
}
private async provideLinks(modelUri: URI): Promise<ILink[]> {
const linkComputer = await this.getOrCreateWorker().withSyncedResources([modelUri]);
return linkComputer.computeLinks(modelUri.toString());
}
private disposeWorker(): void {
if (this.worker) {
this.worker.dispose();
this.worker = undefined;
}
}
}
| src/vs/workbench/contrib/output/browser/outputLinkProvider.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0001735289115458727,
0.00016994698671624064,
0.00016579673683736473,
0.0001702802546788007,
0.000002782648834909196
] |
{
"id": 0,
"code_window": [
"\t\t\t\tconst onDidRemoveLM = Event.filter(that._onDidChangeProviders.event, e => e.removed.includes(languageModelId));\n",
"\t\t\t\treturn Event.signal(Event.any(onDidChangeAccess, onDidRemoveLM));\n",
"\t\t\t},\n",
"\t\t\tmakeRequest(messages, options, token) {\n",
"\t\t\t\tif (!that._accesslist.get(from)) {\n",
"\t\t\t\t\tthrow new Error('Access to chat has been revoked');\n",
"\t\t\t\t}\n",
"\t\t\t\tif (!that._languageModelIds.has(languageModelId)) {\n",
"\t\t\t\t\tthrow new Error('Language Model has been removed');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tmakeChatRequest(messages, options, token) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostChatProvider.ts",
"type": "replace",
"edit_start_line_idx": 221
} | @echo off
yarn %*
| scripts/npm.bat | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017057829245459288,
0.00017057829245459288,
0.00017057829245459288,
0.00017057829245459288,
0
] |
{
"id": 0,
"code_window": [
"\t\t\t\tconst onDidRemoveLM = Event.filter(that._onDidChangeProviders.event, e => e.removed.includes(languageModelId));\n",
"\t\t\t\treturn Event.signal(Event.any(onDidChangeAccess, onDidRemoveLM));\n",
"\t\t\t},\n",
"\t\t\tmakeRequest(messages, options, token) {\n",
"\t\t\t\tif (!that._accesslist.get(from)) {\n",
"\t\t\t\t\tthrow new Error('Access to chat has been revoked');\n",
"\t\t\t\t}\n",
"\t\t\t\tif (!that._languageModelIds.has(languageModelId)) {\n",
"\t\t\t\t\tthrow new Error('Language Model has been removed');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tmakeChatRequest(messages, options, token) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostChatProvider.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 vscode from 'vscode';
import { LanguageClient, ServerOptions, TransportKind } from 'vscode-languageclient/node';
import { MdLanguageClient, startClient } from './client/client';
import { activateShared } from './extension.shared';
import { VsCodeOutputLogger } from './logging';
import { IMdParser, MarkdownItEngine } from './markdownEngine';
import { getMarkdownExtensionContributions } from './markdownExtensions';
import { githubSlugifier } from './slugify';
export async function activate(context: vscode.ExtensionContext) {
const contributions = getMarkdownExtensionContributions(context);
context.subscriptions.push(contributions);
const logger = new VsCodeOutputLogger();
context.subscriptions.push(logger);
const engine = new MarkdownItEngine(contributions, githubSlugifier, logger);
const client = await startServer(context, engine);
context.subscriptions.push(client);
activateShared(context, client, engine, logger, contributions);
}
function startServer(context: vscode.ExtensionContext, parser: IMdParser): Promise<MdLanguageClient> {
const clientMain = vscode.extensions.getExtension('vscode.markdown-language-features')?.packageJSON?.main || '';
const serverMain = `./server/${clientMain.indexOf('/dist/') !== -1 ? 'dist' : 'out'}/node/workerMain`;
const serverModule = context.asAbsolutePath(serverMain);
// The debug options for the server
const debugOptions = { execArgv: ['--nolazy', '--inspect=' + (7000 + Math.round(Math.random() * 999))] };
// If the extension is launch in debug mode the debug server options are use
// Otherwise the run options are used
const serverOptions: ServerOptions = {
run: { module: serverModule, transport: TransportKind.ipc },
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};
// pass the location of the localization bundle to the server
process.env['VSCODE_L10N_BUNDLE_LOCATION'] = vscode.l10n.uri?.toString() ?? '';
return startClient((id, name, clientOptions) => {
return new LanguageClient(id, name, serverOptions, clientOptions);
}, parser);
}
| extensions/markdown-language-features/src/extension.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017377712356392294,
0.00017166063480544835,
0.00016706294263713062,
0.00017220382869709283,
0.0000021540427042054944
] |
{
"id": 1,
"code_window": [
"\t// \t/**\n",
"\t// \t * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.\n",
"\t// \t */\n",
"\t// \tresponse: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];\n",
"\n",
"\t// \t/**\n",
"\t// \t * The result that was received from the chat agent.\n",
"\t// \t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// agentId: string\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.011884897015988827,
0.0011034305207431316,
0.0001649438199819997,
0.00029587262542918324,
0.0019311286741867661
] |
{
"id": 1,
"code_window": [
"\t// \t/**\n",
"\t// \t * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.\n",
"\t// \t */\n",
"\t// \tresponse: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];\n",
"\n",
"\t// \t/**\n",
"\t// \t * The result that was received from the chat agent.\n",
"\t// \t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// agentId: string\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import 'vs/css!./findOptionsWidget';
import { CaseSensitiveToggle, RegexToggle, WholeWordsToggle } from 'vs/base/browser/ui/findinput/findInputToggles';
import { Widget } from 'vs/base/browser/ui/widget';
import { RunOnceScheduler } from 'vs/base/common/async';
import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition, OverlayWidgetPositionPreference } from 'vs/editor/browser/editorBrowser';
import { FIND_IDS } from 'vs/editor/contrib/find/browser/findModel';
import { FindReplaceState } from 'vs/editor/contrib/find/browser/findState';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { asCssVariable, inputActiveOptionBackground, inputActiveOptionBorder, inputActiveOptionForeground } from 'vs/platform/theme/common/colorRegistry';
export class FindOptionsWidget extends Widget implements IOverlayWidget {
private static readonly ID = 'editor.contrib.findOptionsWidget';
private readonly _editor: ICodeEditor;
private readonly _state: FindReplaceState;
private readonly _keybindingService: IKeybindingService;
private readonly _domNode: HTMLElement;
private readonly regex: RegexToggle;
private readonly wholeWords: WholeWordsToggle;
private readonly caseSensitive: CaseSensitiveToggle;
constructor(
editor: ICodeEditor,
state: FindReplaceState,
keybindingService: IKeybindingService
) {
super();
this._editor = editor;
this._state = state;
this._keybindingService = keybindingService;
this._domNode = document.createElement('div');
this._domNode.className = 'findOptionsWidget';
this._domNode.style.display = 'none';
this._domNode.style.top = '10px';
this._domNode.style.zIndex = '12';
this._domNode.setAttribute('role', 'presentation');
this._domNode.setAttribute('aria-hidden', 'true');
const toggleStyles = {
inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground),
};
this.caseSensitive = this._register(new CaseSensitiveToggle({
appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
isChecked: this._state.matchCase,
...toggleStyles
}));
this._domNode.appendChild(this.caseSensitive.domNode);
this._register(this.caseSensitive.onChange(() => {
this._state.change({
matchCase: this.caseSensitive.checked
}, false);
}));
this.wholeWords = this._register(new WholeWordsToggle({
appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
isChecked: this._state.wholeWord,
...toggleStyles
}));
this._domNode.appendChild(this.wholeWords.domNode);
this._register(this.wholeWords.onChange(() => {
this._state.change({
wholeWord: this.wholeWords.checked
}, false);
}));
this.regex = this._register(new RegexToggle({
appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
isChecked: this._state.isRegex,
...toggleStyles
}));
this._domNode.appendChild(this.regex.domNode);
this._register(this.regex.onChange(() => {
this._state.change({
isRegex: this.regex.checked
}, false);
}));
this._editor.addOverlayWidget(this);
this._register(this._state.onFindReplaceStateChange((e) => {
let somethingChanged = false;
if (e.isRegex) {
this.regex.checked = this._state.isRegex;
somethingChanged = true;
}
if (e.wholeWord) {
this.wholeWords.checked = this._state.wholeWord;
somethingChanged = true;
}
if (e.matchCase) {
this.caseSensitive.checked = this._state.matchCase;
somethingChanged = true;
}
if (!this._state.isRevealed && somethingChanged) {
this._revealTemporarily();
}
}));
this._register(dom.addDisposableListener(this._domNode, dom.EventType.MOUSE_LEAVE, (e) => this._onMouseLeave()));
this._register(dom.addDisposableListener(this._domNode, 'mouseover', (e) => this._onMouseOver()));
}
private _keybindingLabelFor(actionId: string): string {
const kb = this._keybindingService.lookupKeybinding(actionId);
if (!kb) {
return '';
}
return ` (${kb.getLabel()})`;
}
public override dispose(): void {
this._editor.removeOverlayWidget(this);
super.dispose();
}
// ----- IOverlayWidget API
public getId(): string {
return FindOptionsWidget.ID;
}
public getDomNode(): HTMLElement {
return this._domNode;
}
public getPosition(): IOverlayWidgetPosition {
return {
preference: OverlayWidgetPositionPreference.TOP_RIGHT_CORNER
};
}
public highlightFindOptions(): void {
this._revealTemporarily();
}
private _hideSoon = this._register(new RunOnceScheduler(() => this._hide(), 2000));
private _revealTemporarily(): void {
this._show();
this._hideSoon.schedule();
}
private _onMouseLeave(): void {
this._hideSoon.schedule();
}
private _onMouseOver(): void {
this._hideSoon.cancel();
}
private _isVisible: boolean = false;
private _show(): void {
if (this._isVisible) {
return;
}
this._isVisible = true;
this._domNode.style.display = 'block';
}
private _hide(): void {
if (!this._isVisible) {
return;
}
this._isVisible = false;
this._domNode.style.display = 'none';
}
}
| src/vs/editor/contrib/find/browser/findOptionsWidget.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017334549920633435,
0.0001710633805487305,
0.00016800880257505924,
0.00017139135161414742,
0.0000014295278560894076
] |
{
"id": 1,
"code_window": [
"\t// \t/**\n",
"\t// \t * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.\n",
"\t// \t */\n",
"\t// \tresponse: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];\n",
"\n",
"\t// \t/**\n",
"\t// \t * The result that was received from the chat agent.\n",
"\t// \t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// agentId: string\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 35
} | /**
* Semver UMD module
* Copyright (c) Isaac Z. Schlueter and Contributors
* https://github.com/npm/node-semver
*/
/**
* DO NOT EDIT THIS FILE
*/
!function(e,r){if("object"==typeof exports&&"object"==typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var t=r();for(var n in t)("object"==typeof exports?exports:e)[n]=t[n]}}("undefined"!=typeof self?self:this,(function(){return function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){(function(t){var n;r=e.exports=H,n="object"==typeof t&&t.env&&t.env.NODE_DEBUG&&/\bsemver\b/i.test(t.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},r.SEMVER_SPEC_VERSION="2.0.0";var o=256,i=Number.MAX_SAFE_INTEGER||9007199254740991,s=r.re=[],a=r.src=[],u=0,c=u++;a[c]="0|[1-9]\\d*";var p=u++;a[p]="[0-9]+";var f=u++;a[f]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var l=u++;a[l]="("+a[c]+")\\.("+a[c]+")\\.("+a[c]+")";var h=u++;a[h]="("+a[p]+")\\.("+a[p]+")\\.("+a[p]+")";var v=u++;a[v]="(?:"+a[c]+"|"+a[f]+")";var m=u++;a[m]="(?:"+a[p]+"|"+a[f]+")";var w=u++;a[w]="(?:-("+a[v]+"(?:\\."+a[v]+")*))";var g=u++;a[g]="(?:-?("+a[m]+"(?:\\."+a[m]+")*))";var y=u++;a[y]="[0-9A-Za-z-]+";var d=u++;a[d]="(?:\\+("+a[y]+"(?:\\."+a[y]+")*))";var b=u++,j="v?"+a[l]+a[w]+"?"+a[d]+"?";a[b]="^"+j+"$";var E="[v=\\s]*"+a[h]+a[g]+"?"+a[d]+"?",T=u++;a[T]="^"+E+"$";var x=u++;a[x]="((?:<|>)?=?)";var $=u++;a[$]=a[p]+"|x|X|\\*";var k=u++;a[k]=a[c]+"|x|X|\\*";var S=u++;a[S]="[v=\\s]*("+a[k]+")(?:\\.("+a[k]+")(?:\\.("+a[k]+")(?:"+a[w]+")?"+a[d]+"?)?)?";var R=u++;a[R]="[v=\\s]*("+a[$]+")(?:\\.("+a[$]+")(?:\\.("+a[$]+")(?:"+a[g]+")?"+a[d]+"?)?)?";var I=u++;a[I]="^"+a[x]+"\\s*"+a[S]+"$";var _=u++;a[_]="^"+a[x]+"\\s*"+a[R]+"$";var O=u++;a[O]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var A=u++;a[A]="(?:~>?)";var M=u++;a[M]="(\\s*)"+a[A]+"\\s+",s[M]=new RegExp(a[M],"g");var V=u++;a[V]="^"+a[A]+a[S]+"$";var P=u++;a[P]="^"+a[A]+a[R]+"$";var C=u++;a[C]="(?:\\^)";var L=u++;a[L]="(\\s*)"+a[C]+"\\s+",s[L]=new RegExp(a[L],"g");var N=u++;a[N]="^"+a[C]+a[S]+"$";var q=u++;a[q]="^"+a[C]+a[R]+"$";var D=u++;a[D]="^"+a[x]+"\\s*("+E+")$|^$";var X=u++;a[X]="^"+a[x]+"\\s*("+j+")$|^$";var z=u++;a[z]="(\\s*)"+a[x]+"\\s*("+E+"|"+a[S]+")",s[z]=new RegExp(a[z],"g");var G=u++;a[G]="^\\s*("+a[S]+")\\s+-\\s+("+a[S]+")\\s*$";var Z=u++;a[Z]="^\\s*("+a[R]+")\\s+-\\s+("+a[R]+")\\s*$";var B=u++;a[B]="(<|>)?=?\\s*\\*";for(var U=0;U<35;U++)n(U,a[U]),s[U]||(s[U]=new RegExp(a[U]));function F(e,r){if(e instanceof H)return e;if("string"!=typeof e)return null;if(e.length>o)return null;if(!(r?s[T]:s[b]).test(e))return null;try{return new H(e,r)}catch(e){return null}}function H(e,r){if(e instanceof H){if(e.loose===r)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>o)throw new TypeError("version is longer than "+o+" characters");if(!(this instanceof H))return new H(e,r);n("SemVer",e,r),this.loose=r;var t=e.trim().match(r?s[T]:s[b]);if(!t)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+t[1],this.minor=+t[2],this.patch=+t[3],this.major>i||this.major<0)throw new TypeError("Invalid major version");if(this.minor>i||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>i||this.patch<0)throw new TypeError("Invalid patch version");t[4]?this.prerelease=t[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var r=+e;if(r>=0&&r<i)return r}return e})):this.prerelease=[],this.build=t[5]?t[5].split("."):[],this.format()}r.parse=F,r.valid=function(e,r){var t=F(e,r);return t?t.version:null},r.clean=function(e,r){var t=F(e.trim().replace(/^[=v]+/,""),r);return t?t.version:null},r.SemVer=H,H.prototype.format=function(){return this.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version},H.prototype.toString=function(){return this.version},H.prototype.compare=function(e){return n("SemVer.compare",this.version,this.loose,e),e instanceof H||(e=new H(e,this.loose)),this.compareMain(e)||this.comparePre(e)},H.prototype.compareMain=function(e){return e instanceof H||(e=new H(e,this.loose)),K(this.major,e.major)||K(this.minor,e.minor)||K(this.patch,e.patch)},H.prototype.comparePre=function(e){if(e instanceof H||(e=new H(e,this.loose)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;var r=0;do{var t=this.prerelease[r],o=e.prerelease[r];if(n("prerelease compare",r,t,o),void 0===t&&void 0===o)return 0;if(void 0===o)return 1;if(void 0===t)return-1;if(t!==o)return K(t,o)}while(++r)},H.prototype.inc=function(e,r){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r),this.inc("pre",r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",r),this.inc("pre",r);break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":if(0===this.prerelease.length)this.prerelease=[0];else{for(var t=this.prerelease.length;--t>=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}r&&(this.prerelease[0]===r?isNaN(this.prerelease[1])&&(this.prerelease=[r,0]):this.prerelease=[r,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},r.inc=function(e,r,t,n){"string"==typeof t&&(n=t,t=void 0);try{return new H(e,t).inc(r,n).version}catch(e){return null}},r.diff=function(e,r){if(ee(e,r))return null;var t=F(e),n=F(r);if(t.prerelease.length||n.prerelease.length){for(var o in t)if(("major"===o||"minor"===o||"patch"===o)&&t[o]!==n[o])return"pre"+o;return"prerelease"}for(var o in t)if(("major"===o||"minor"===o||"patch"===o)&&t[o]!==n[o])return o},r.compareIdentifiers=K;var J=/^[0-9]+$/;function K(e,r){var t=J.test(e),n=J.test(r);return t&&n&&(e=+e,r=+r),t&&!n?-1:n&&!t?1:e<r?-1:e>r?1:0}function Q(e,r,t){return new H(e,t).compare(new H(r,t))}function W(e,r,t){return Q(e,r,t)>0}function Y(e,r,t){return Q(e,r,t)<0}function ee(e,r,t){return 0===Q(e,r,t)}function re(e,r,t){return 0!==Q(e,r,t)}function te(e,r,t){return Q(e,r,t)>=0}function ne(e,r,t){return Q(e,r,t)<=0}function oe(e,r,t,n){var o;switch(r){case"===":"object"==typeof e&&(e=e.version),"object"==typeof t&&(t=t.version),o=e===t;break;case"!==":"object"==typeof e&&(e=e.version),"object"==typeof t&&(t=t.version),o=e!==t;break;case"":case"=":case"==":o=ee(e,t,n);break;case"!=":o=re(e,t,n);break;case">":o=W(e,t,n);break;case">=":o=te(e,t,n);break;case"<":o=Y(e,t,n);break;case"<=":o=ne(e,t,n);break;default:throw new TypeError("Invalid operator: "+r)}return o}function ie(e,r){if(e instanceof ie){if(e.loose===r)return e;e=e.value}if(!(this instanceof ie))return new ie(e,r);n("comparator",e,r),this.loose=r,this.parse(e),this.semver===se?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}r.rcompareIdentifiers=function(e,r){return K(r,e)},r.major=function(e,r){return new H(e,r).major},r.minor=function(e,r){return new H(e,r).minor},r.patch=function(e,r){return new H(e,r).patch},r.compare=Q,r.compareLoose=function(e,r){return Q(e,r,!0)},r.rcompare=function(e,r,t){return Q(r,e,t)},r.sort=function(e,t){return e.sort((function(e,n){return r.compare(e,n,t)}))},r.rsort=function(e,t){return e.sort((function(e,n){return r.rcompare(e,n,t)}))},r.gt=W,r.lt=Y,r.eq=ee,r.neq=re,r.gte=te,r.lte=ne,r.cmp=oe,r.Comparator=ie;var se={};function ae(e,r){if(e instanceof ae)return e.loose===r?e:new ae(e.raw,r);if(e instanceof ie)return new ae(e.value,r);if(!(this instanceof ae))return new ae(e,r);if(this.loose=r,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ue(e){return!e||"x"===e.toLowerCase()||"*"===e}function ce(e,r,t,n,o,i,s,a,u,c,p,f,l){return((r=ue(t)?"":ue(n)?">="+t+".0.0":ue(o)?">="+t+"."+n+".0":">="+r)+" "+(a=ue(u)?"":ue(c)?"<"+(+u+1)+".0.0":ue(p)?"<"+u+"."+(+c+1)+".0":f?"<="+u+"."+c+"."+p+"-"+f:"<="+a)).trim()}function pe(e,r){for(var t=0;t<e.length;t++)if(!e[t].test(r))return!1;if(r.prerelease.length){for(t=0;t<e.length;t++)if(n(e[t].semver),e[t].semver!==se&&e[t].semver.prerelease.length>0){var o=e[t].semver;if(o.major===r.major&&o.minor===r.minor&&o.patch===r.patch)return!0}return!1}return!0}function fe(e,r,t){try{r=new ae(r,t)}catch(e){return!1}return r.test(e)}function le(e,r,t,n){var o,i,s,a,u;switch(e=new H(e,n),r=new ae(r,n),t){case">":o=W,i=ne,s=Y,a=">",u=">=";break;case"<":o=Y,i=te,s=W,a="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(fe(e,r,n))return!1;for(var c=0;c<r.set.length;++c){var p=r.set[c],f=null,l=null;if(p.forEach((function(e){e.semver===se&&(e=new ie(">=0.0.0")),f=f||e,l=l||e,o(e.semver,f.semver,n)?f=e:s(e.semver,l.semver,n)&&(l=e)})),f.operator===a||f.operator===u)return!1;if((!l.operator||l.operator===a)&&i(e,l.semver))return!1;if(l.operator===u&&s(e,l.semver))return!1}return!0}ie.prototype.parse=function(e){var r=this.loose?s[D]:s[X],t=e.match(r);if(!t)throw new TypeError("Invalid comparator: "+e);this.operator=t[1],"="===this.operator&&(this.operator=""),t[2]?this.semver=new H(t[2],this.loose):this.semver=se},ie.prototype.toString=function(){return this.value},ie.prototype.test=function(e){return n("Comparator.test",e,this.loose),this.semver===se||("string"==typeof e&&(e=new H(e,this.loose)),oe(e,this.operator,this.semver,this.loose))},ie.prototype.intersects=function(e,r){if(!(e instanceof ie))throw new TypeError("a Comparator is required");var t;if(""===this.operator)return t=new ae(e.value,r),fe(this.value,t,r);if(""===e.operator)return t=new ae(this.value,r),fe(e.semver,t,r);var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),o=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),i=this.semver.version===e.semver.version,s=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=oe(this.semver,"<",e.semver,r)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),u=oe(this.semver,">",e.semver,r)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||o||i&&s||a||u},r.Range=ae,ae.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},ae.prototype.toString=function(){return this.range},ae.prototype.parseRange=function(e){var r=this.loose;e=e.trim(),n("range",e,r);var t=r?s[Z]:s[G];e=e.replace(t,ce),n("hyphen replace",e),e=e.replace(s[z],"$1$2$3"),n("comparator trim",e,s[z]),e=(e=(e=e.replace(s[M],"$1~")).replace(s[L],"$1^")).split(/\s+/).join(" ");var o=r?s[D]:s[X],i=e.split(" ").map((function(e){return function(e,r){return n("comp",e),e=function(e,r){return e.trim().split(/\s+/).map((function(e){return function(e,r){n("caret",e,r);var t=r?s[q]:s[N];return e.replace(t,(function(r,t,o,i,s){var a;return n("caret",e,r,t,o,i,s),ue(t)?a="":ue(o)?a=">="+t+".0.0 <"+(+t+1)+".0.0":ue(i)?a="0"===t?">="+t+"."+o+".0 <"+t+"."+(+o+1)+".0":">="+t+"."+o+".0 <"+(+t+1)+".0.0":s?(n("replaceCaret pr",s),"-"!==s.charAt(0)&&(s="-"+s),a="0"===t?"0"===o?">="+t+"."+o+"."+i+s+" <"+t+"."+o+"."+(+i+1):">="+t+"."+o+"."+i+s+" <"+t+"."+(+o+1)+".0":">="+t+"."+o+"."+i+s+" <"+(+t+1)+".0.0"):(n("no pr"),a="0"===t?"0"===o?">="+t+"."+o+"."+i+" <"+t+"."+o+"."+(+i+1):">="+t+"."+o+"."+i+" <"+t+"."+(+o+1)+".0":">="+t+"."+o+"."+i+" <"+(+t+1)+".0.0"),n("caret return",a),a}))}(e,r)})).join(" ")}(e,r),n("caret",e),e=function(e,r){return e.trim().split(/\s+/).map((function(e){return function(e,r){var t=r?s[P]:s[V];return e.replace(t,(function(r,t,o,i,s){var a;return n("tilde",e,r,t,o,i,s),ue(t)?a="":ue(o)?a=">="+t+".0.0 <"+(+t+1)+".0.0":ue(i)?a=">="+t+"."+o+".0 <"+t+"."+(+o+1)+".0":s?(n("replaceTilde pr",s),"-"!==s.charAt(0)&&(s="-"+s),a=">="+t+"."+o+"."+i+s+" <"+t+"."+(+o+1)+".0"):a=">="+t+"."+o+"."+i+" <"+t+"."+(+o+1)+".0",n("tilde return",a),a}))}(e,r)})).join(" ")}(e,r),n("tildes",e),e=function(e,r){return n("replaceXRanges",e,r),e.split(/\s+/).map((function(e){return function(e,r){e=e.trim();var t=r?s[_]:s[I];return e.replace(t,(function(r,t,o,i,s,a){n("xRange",e,r,t,o,i,s,a);var u=ue(o),c=u||ue(i),p=c||ue(s);return"="===t&&p&&(t=""),u?r=">"===t||"<"===t?"<0.0.0":"*":t&&p?(c&&(i=0),p&&(s=0),">"===t?(t=">=",c?(o=+o+1,i=0,s=0):p&&(i=+i+1,s=0)):"<="===t&&(t="<",c?o=+o+1:i=+i+1),r=t+o+"."+i+"."+s):c?r=">="+o+".0.0 <"+(+o+1)+".0.0":p&&(r=">="+o+"."+i+".0 <"+o+"."+(+i+1)+".0"),n("xRange return",r),r}))}(e,r)})).join(" ")}(e,r),n("xrange",e),e=function(e,r){return n("replaceStars",e,r),e.trim().replace(s[B],"")}(e,r),n("stars",e),e}(e,r)})).join(" ").split(/\s+/);return this.loose&&(i=i.filter((function(e){return!!e.match(o)}))),i=i.map((function(e){return new ie(e,r)}))},ae.prototype.intersects=function(e,r){if(!(e instanceof ae))throw new TypeError("a Range is required");return this.set.some((function(t){return t.every((function(t){return e.set.some((function(e){return e.every((function(e){return t.intersects(e,r)}))}))}))}))},r.toComparators=function(e,r){return new ae(e,r).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},ae.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new H(e,this.loose));for(var r=0;r<this.set.length;r++)if(pe(this.set[r],e))return!0;return!1},r.satisfies=fe,r.maxSatisfying=function(e,r,t){var n=null,o=null;try{var i=new ae(r,t)}catch(e){return null}return e.forEach((function(e){i.test(e)&&(n&&-1!==o.compare(e)||(o=new H(n=e,t)))})),n},r.minSatisfying=function(e,r,t){var n=null,o=null;try{var i=new ae(r,t)}catch(e){return null}return e.forEach((function(e){i.test(e)&&(n&&1!==o.compare(e)||(o=new H(n=e,t)))})),n},r.validRange=function(e,r){try{return new ae(e,r).range||"*"}catch(e){return null}},r.ltr=function(e,r,t){return le(e,r,"<",t)},r.gtr=function(e,r,t){return le(e,r,">",t)},r.outside=le,r.prerelease=function(e,r){var t=F(e,r);return t&&t.prerelease.length?t.prerelease:null},r.intersects=function(e,r,t){return e=new ae(e,t),r=new ae(r,t),e.intersects(r)},r.coerce=function(e){if(e instanceof H)return e;if("string"!=typeof e)return null;var r=e.match(s[O]);return null==r?null:F((r[1]||"0")+"."+(r[2]||"0")+"."+(r[3]||"0"))}}).call(this,t(1))},function(e,r){var t,n,o=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(e){n=s}}();var u,c=[],p=!1,f=-1;function l(){p&&u&&(p=!1,u.length?c=u.concat(c):f=-1,c.length&&h())}function h(){if(!p){var e=a(l);p=!0;for(var r=c.length;r;){for(u=c,c=[];++f<r;)u&&u[f].run();f=-1,r=c.length}u=null,p=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{n(e)}catch(r){try{return n.call(null,e)}catch(r){return n.call(this,e)}}}(e)}}function v(e,r){this.fun=e,this.array=r}function m(){}o.nextTick=function(e){var r=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)r[t-1]=arguments[t];c.push(new v(e,r)),1!==c.length||p||a(h)},v.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=m,o.addListener=m,o.once=m,o.off=m,o.removeListener=m,o.removeAllListeners=m,o.emit=m,o.prependListener=m,o.prependOnceListener=m,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}}])}));
| src/vs/base/common/semver/semver.js | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.000171445615706034,
0.00016883312491700053,
0.00016622061957605183,
0.00016883312491700053,
0.0000026124980649910867
] |
{
"id": 1,
"code_window": [
"\t// \t/**\n",
"\t// \t * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.\n",
"\t// \t */\n",
"\t// \tresponse: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];\n",
"\n",
"\t// \t/**\n",
"\t// \t * The result that was received from the chat agent.\n",
"\t// \t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// agentId: string\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ISettableObservable } from 'vs/base/common/observable';
import { WellDefinedPrefixTree } from 'vs/base/common/prefixTree';
import { URI } from 'vs/base/common/uri';
import { Range } from 'vs/editor/common/core/range';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { MutableObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';
import { TestCoverage } from 'vs/workbench/contrib/testing/common/testCoverage';
import { TestId } from 'vs/workbench/contrib/testing/common/testId';
import { ITestProfileService } from 'vs/workbench/contrib/testing/common/testProfileService';
import { LiveTestResult } from 'vs/workbench/contrib/testing/common/testResult';
import { ITestResultService } from 'vs/workbench/contrib/testing/common/testResultService';
import { IMainThreadTestController, ITestRootProvider, ITestService } from 'vs/workbench/contrib/testing/common/testService';
import { CoverageDetails, ExtensionRunTestsRequest, IFileCoverage, ITestItem, ITestMessage, ITestRunProfile, ITestRunTask, ResolvedTestRunRequest, TestResultState, TestsDiffOp } from 'vs/workbench/contrib/testing/common/testTypes';
import { IExtHostContext, extHostNamedCustomer } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { ExtHostContext, ExtHostTestingShape, ILocationDto, ITestControllerPatch, MainContext, MainThreadTestingShape } from '../common/extHost.protocol';
@extHostNamedCustomer(MainContext.MainThreadTesting)
export class MainThreadTesting extends Disposable implements MainThreadTestingShape, ITestRootProvider {
private readonly proxy: ExtHostTestingShape;
private readonly diffListener = this._register(new MutableDisposable());
private readonly testProviderRegistrations = new Map<string, {
instance: IMainThreadTestController;
label: MutableObservableValue<string>;
canRefresh: MutableObservableValue<boolean>;
disposable: IDisposable;
}>();
constructor(
extHostContext: IExtHostContext,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@ITestService private readonly testService: ITestService,
@ITestProfileService private readonly testProfiles: ITestProfileService,
@ITestResultService private readonly resultService: ITestResultService,
) {
super();
this.proxy = extHostContext.getProxy(ExtHostContext.ExtHostTesting);
this._register(this.testService.onDidCancelTestRun(({ runId }) => {
this.proxy.$cancelExtensionTestRun(runId);
}));
this._register(Event.debounce(testProfiles.onDidChange, (_last, e) => e)(() => {
const obj: Record</* controller id */string, /* profile id */ number[]> = {};
for (const { controller, profiles } of this.testProfiles.all()) {
obj[controller.id] = profiles.filter(p => p.isDefault).map(p => p.profileId);
}
this.proxy.$setDefaultRunProfiles(obj);
}));
this._register(resultService.onResultsChanged(evt => {
const results = 'completed' in evt ? evt.completed : ('inserted' in evt ? evt.inserted : undefined);
const serialized = results?.toJSONWithMessages();
if (serialized) {
this.proxy.$publishTestResults([serialized]);
}
}));
}
/**
* @inheritdoc
*/
$markTestRetired(testIds: string[] | undefined): void {
let tree: WellDefinedPrefixTree<undefined> | undefined;
if (testIds) {
tree = new WellDefinedPrefixTree();
for (const id of testIds) {
tree.insert(TestId.fromString(id).path, undefined);
}
}
for (const result of this.resultService.results) {
// all non-live results are already entirely outdated
if (result instanceof LiveTestResult) {
result.markRetired(tree);
}
}
}
/**
* @inheritdoc
*/
$publishTestRunProfile(profile: ITestRunProfile): void {
const controller = this.testProviderRegistrations.get(profile.controllerId);
if (controller) {
this.testProfiles.addProfile(controller.instance, profile);
}
}
/**
* @inheritdoc
*/
$updateTestRunConfig(controllerId: string, profileId: number, update: Partial<ITestRunProfile>): void {
this.testProfiles.updateProfile(controllerId, profileId, update);
}
/**
* @inheritdoc
*/
$removeTestProfile(controllerId: string, profileId: number): void {
this.testProfiles.removeProfile(controllerId, profileId);
}
/**
* @inheritdoc
*/
$addTestsToRun(controllerId: string, runId: string, tests: ITestItem.Serialized[]): void {
this.withLiveRun(runId, r => r.addTestChainToRun(controllerId,
tests.map(t => ITestItem.deserialize(this.uriIdentityService, t))));
}
/**
* @inheritdoc
*/
$signalCoverageAvailable(runId: string, taskId: string, available: boolean): void {
this.withLiveRun(runId, run => {
const task = run.tasks.find(t => t.id === taskId);
if (!task) {
return;
}
const fn = available ? ((token: CancellationToken) => TestCoverage.load(taskId, {
provideFileCoverage: async token => await this.proxy.$provideFileCoverage(runId, taskId, token)
.then(c => c.map(u => IFileCoverage.deserialize(this.uriIdentityService, u))),
resolveFileCoverage: (i, token) => this.proxy.$resolveFileCoverage(runId, taskId, i, token)
.then(d => d.map(CoverageDetails.deserialize)),
}, this.uriIdentityService, token)) : undefined;
(task.coverage as ISettableObservable<undefined | ((tkn: CancellationToken) => Promise<TestCoverage>)>).set(fn, undefined);
});
}
/**
* @inheritdoc
*/
$startedExtensionTestRun(req: ExtensionRunTestsRequest): void {
this.resultService.createLiveResult(req);
}
/**
* @inheritdoc
*/
$startedTestRunTask(runId: string, task: ITestRunTask): void {
this.withLiveRun(runId, r => r.addTask(task));
}
/**
* @inheritdoc
*/
$finishedTestRunTask(runId: string, taskId: string): void {
this.withLiveRun(runId, r => r.markTaskComplete(taskId));
}
/**
* @inheritdoc
*/
$finishedExtensionTestRun(runId: string): void {
this.withLiveRun(runId, r => r.markComplete());
}
/**
* @inheritdoc
*/
public $updateTestStateInRun(runId: string, taskId: string, testId: string, state: TestResultState, duration?: number): void {
this.withLiveRun(runId, r => r.updateState(testId, taskId, state, duration));
}
/**
* @inheritdoc
*/
public $appendOutputToRun(runId: string, taskId: string, output: VSBuffer, locationDto?: ILocationDto, testId?: string): void {
const location = locationDto && {
uri: URI.revive(locationDto.uri),
range: Range.lift(locationDto.range)
};
this.withLiveRun(runId, r => r.appendOutput(output, taskId, location, testId));
}
/**
* @inheritdoc
*/
public $appendTestMessagesInRun(runId: string, taskId: string, testId: string, messages: ITestMessage.Serialized[]): void {
const r = this.resultService.getResult(runId);
if (r && r instanceof LiveTestResult) {
for (const message of messages) {
r.appendMessage(testId, taskId, ITestMessage.deserialize(this.uriIdentityService, message));
}
}
}
/**
* @inheritdoc
*/
public $registerTestController(controllerId: string, labelStr: string, canRefreshValue: boolean) {
const disposable = new DisposableStore();
const label = disposable.add(new MutableObservableValue(labelStr));
const canRefresh = disposable.add(new MutableObservableValue(canRefreshValue));
const controller: IMainThreadTestController = {
id: controllerId,
label,
canRefresh,
syncTests: () => this.proxy.$syncTests(),
refreshTests: token => this.proxy.$refreshTests(controllerId, token),
configureRunProfile: id => this.proxy.$configureRunProfile(controllerId, id),
runTests: (reqs, token) => this.proxy.$runControllerTests(reqs, token),
startContinuousRun: (reqs, token) => this.proxy.$startContinuousRun(reqs, token),
expandTest: (testId, levels) => this.proxy.$expandTest(testId, isFinite(levels) ? levels : -1),
};
disposable.add(toDisposable(() => this.testProfiles.removeProfile(controllerId)));
disposable.add(this.testService.registerTestController(controllerId, controller));
this.testProviderRegistrations.set(controllerId, {
instance: controller,
label,
canRefresh,
disposable
});
}
/**
* @inheritdoc
*/
public $updateController(controllerId: string, patch: ITestControllerPatch) {
const controller = this.testProviderRegistrations.get(controllerId);
if (!controller) {
return;
}
if (patch.label !== undefined) {
controller.label.value = patch.label;
}
if (patch.canRefresh !== undefined) {
controller.canRefresh.value = patch.canRefresh;
}
}
/**
* @inheritdoc
*/
public $unregisterTestController(controllerId: string) {
this.testProviderRegistrations.get(controllerId)?.disposable.dispose();
this.testProviderRegistrations.delete(controllerId);
}
/**
* @inheritdoc
*/
public $subscribeToDiffs(): void {
this.proxy.$acceptDiff(this.testService.collection.getReviverDiff().map(TestsDiffOp.serialize));
this.diffListener.value = this.testService.onDidProcessDiff(this.proxy.$acceptDiff, this.proxy);
}
/**
* @inheritdoc
*/
public $unsubscribeFromDiffs(): void {
this.diffListener.clear();
}
/**
* @inheritdoc
*/
public $publishDiff(controllerId: string, diff: TestsDiffOp.Serialized[]): void {
this.testService.publishDiff(controllerId,
diff.map(d => TestsDiffOp.deserialize(this.uriIdentityService, d)));
}
public async $runTests(req: ResolvedTestRunRequest, token: CancellationToken): Promise<string> {
const result = await this.testService.runResolvedTests(req, token);
return result.id;
}
public override dispose() {
super.dispose();
for (const subscription of this.testProviderRegistrations.values()) {
subscription.disposable.dispose();
}
this.testProviderRegistrations.clear();
}
private withLiveRun<T>(runId: string, fn: (run: LiveTestResult) => T): T | undefined {
const r = this.resultService.getResult(runId);
return r && r instanceof LiveTestResult ? fn(r) : undefined;
}
}
| src/vs/workbench/api/browser/mainThreadTesting.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017565811867825687,
0.00017176431720145047,
0.00016527663683518767,
0.0001721066073514521,
0.0000024760847736615688
] |
{
"id": 2,
"code_window": [
"\t\t * All of the chat messages so far in the current chat session.\n",
"\t\t */\n",
"\t\thistory: ChatAgentHistoryEntry[];\n",
"\n",
"\t\t// TODO@API have \"turns\"\n",
"\t\t// history2: (ChatAgentRequest | ChatAgentResponse)[];\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// location:\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 47
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.9428392052650452,
0.0159442238509655,
0.00016483047511428595,
0.00025527377147227526,
0.11869245767593384
] |
{
"id": 2,
"code_window": [
"\t\t * All of the chat messages so far in the current chat session.\n",
"\t\t */\n",
"\t\thistory: ChatAgentHistoryEntry[];\n",
"\n",
"\t\t// TODO@API have \"turns\"\n",
"\t\t// history2: (ChatAgentRequest | ChatAgentResponse)[];\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// location:\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 47
} | /*---------------------------------------------------------------------------------------------
* 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/callHierarchy';
import * as peekView from 'vs/editor/contrib/peekView/browser/peekView';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { CallHierarchyDirection, CallHierarchyModel } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';
import { WorkbenchAsyncDataTree, IWorkbenchAsyncDataTreeOptions } from 'vs/platform/list/browser/listService';
import { FuzzyScore } from 'vs/base/common/filters';
import * as callHTree from 'vs/workbench/contrib/callHierarchy/browser/callHierarchyTree';
import { IAsyncDataTreeViewState } from 'vs/base/browser/ui/tree/asyncDataTree';
import { localize } from 'vs/nls';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { IRange, Range } from 'vs/editor/common/core/range';
import { SplitView, Orientation, Sizing } from 'vs/base/browser/ui/splitview/splitview';
import { Dimension, isKeyboardEvent } from 'vs/base/browser/dom';
import { Event } from 'vs/base/common/event';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EmbeddedCodeEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model';
import { themeColorFromId, IThemeService, IColorTheme } from 'vs/platform/theme/common/themeService';
import { IPosition } from 'vs/editor/common/core/position';
import { IAction } from 'vs/base/common/actions';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { Color } from 'vs/base/common/color';
import { TreeMouseEventTarget, ITreeNode } from 'vs/base/browser/ui/tree/tree';
import { URI } from 'vs/base/common/uri';
import { MenuId, IMenuService } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
const enum State {
Loading = 'loading',
Message = 'message',
Data = 'data'
}
class LayoutInfo {
static store(info: LayoutInfo, storageService: IStorageService): void {
storageService.store('callHierarchyPeekLayout', JSON.stringify(info), StorageScope.PROFILE, StorageTarget.MACHINE);
}
static retrieve(storageService: IStorageService): LayoutInfo {
const value = storageService.get('callHierarchyPeekLayout', StorageScope.PROFILE, '{}');
const defaultInfo: LayoutInfo = { ratio: 0.7, height: 17 };
try {
return { ...defaultInfo, ...JSON.parse(value) };
} catch {
return defaultInfo;
}
}
constructor(
public ratio: number,
public height: number
) { }
}
class CallHierarchyTree extends WorkbenchAsyncDataTree<CallHierarchyModel, callHTree.Call, FuzzyScore> { }
export class CallHierarchyTreePeekWidget extends peekView.PeekViewWidget {
static readonly TitleMenu = new MenuId('callhierarchy/title');
private _parent!: HTMLElement;
private _message!: HTMLElement;
private _splitView!: SplitView;
private _tree!: CallHierarchyTree;
private _treeViewStates = new Map<CallHierarchyDirection, IAsyncDataTreeViewState>();
private _editor!: EmbeddedCodeEditorWidget;
private _dim!: Dimension;
private _layoutInfo!: LayoutInfo;
private readonly _previewDisposable = new DisposableStore();
constructor(
editor: ICodeEditor,
private readonly _where: IPosition,
private _direction: CallHierarchyDirection,
@IThemeService themeService: IThemeService,
@peekView.IPeekViewService private readonly _peekViewService: peekView.IPeekViewService,
@IEditorService private readonly _editorService: IEditorService,
@ITextModelService private readonly _textModelService: ITextModelService,
@IStorageService private readonly _storageService: IStorageService,
@IMenuService private readonly _menuService: IMenuService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
super(editor, { showFrame: true, showArrow: true, isResizeable: true, isAccessible: true }, _instantiationService);
this.create();
this._peekViewService.addExclusiveWidget(editor, this);
this._applyTheme(themeService.getColorTheme());
this._disposables.add(themeService.onDidColorThemeChange(this._applyTheme, this));
this._disposables.add(this._previewDisposable);
}
override dispose(): void {
LayoutInfo.store(this._layoutInfo, this._storageService);
this._splitView.dispose();
this._tree.dispose();
this._editor.dispose();
super.dispose();
}
get direction(): CallHierarchyDirection {
return this._direction;
}
private _applyTheme(theme: IColorTheme) {
const borderColor = theme.getColor(peekView.peekViewBorder) || Color.transparent;
this.style({
arrowColor: borderColor,
frameColor: borderColor,
headerBackgroundColor: theme.getColor(peekView.peekViewTitleBackground) || Color.transparent,
primaryHeadingColor: theme.getColor(peekView.peekViewTitleForeground),
secondaryHeadingColor: theme.getColor(peekView.peekViewTitleInfoForeground)
});
}
protected override _fillHead(container: HTMLElement): void {
super._fillHead(container, true);
const menu = this._menuService.createMenu(CallHierarchyTreePeekWidget.TitleMenu, this._contextKeyService);
const updateToolbar = () => {
const actions: IAction[] = [];
createAndFillInActionBarActions(menu, undefined, actions);
this._actionbarWidget!.clear();
this._actionbarWidget!.push(actions, { label: false, icon: true });
};
this._disposables.add(menu);
this._disposables.add(menu.onDidChange(updateToolbar));
updateToolbar();
}
protected _fillBody(parent: HTMLElement): void {
this._layoutInfo = LayoutInfo.retrieve(this._storageService);
this._dim = new Dimension(0, 0);
this._parent = parent;
parent.classList.add('call-hierarchy');
const message = document.createElement('div');
message.classList.add('message');
parent.appendChild(message);
this._message = message;
this._message.tabIndex = 0;
const container = document.createElement('div');
container.classList.add('results');
parent.appendChild(container);
this._splitView = new SplitView(container, { orientation: Orientation.HORIZONTAL });
// editor stuff
const editorContainer = document.createElement('div');
editorContainer.classList.add('editor');
container.appendChild(editorContainer);
const editorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
overviewRulerLanes: 2,
fixedOverflowWidgets: true,
minimap: {
enabled: false
}
};
this._editor = this._instantiationService.createInstance(
EmbeddedCodeEditorWidget,
editorContainer,
editorOptions,
{},
this.editor
);
// tree stuff
const treeContainer = document.createElement('div');
treeContainer.classList.add('tree');
container.appendChild(treeContainer);
const options: IWorkbenchAsyncDataTreeOptions<callHTree.Call, FuzzyScore> = {
sorter: new callHTree.Sorter(),
accessibilityProvider: new callHTree.AccessibilityProvider(() => this._direction),
identityProvider: new callHTree.IdentityProvider(() => this._direction),
expandOnlyOnTwistieClick: true,
overrideStyles: {
listBackground: peekView.peekViewResultsBackground
}
};
this._tree = this._instantiationService.createInstance(
CallHierarchyTree,
'CallHierarchyPeek',
treeContainer,
new callHTree.VirtualDelegate(),
[this._instantiationService.createInstance(callHTree.CallRenderer)],
this._instantiationService.createInstance(callHTree.DataSource, () => this._direction),
options
);
// split stuff
this._splitView.addView({
onDidChange: Event.None,
element: editorContainer,
minimumSize: 200,
maximumSize: Number.MAX_VALUE,
layout: (width) => {
if (this._dim.height) {
this._editor.layout({ height: this._dim.height, width });
}
}
}, Sizing.Distribute);
this._splitView.addView({
onDidChange: Event.None,
element: treeContainer,
minimumSize: 100,
maximumSize: Number.MAX_VALUE,
layout: (width) => {
if (this._dim.height) {
this._tree.layout(this._dim.height, width);
}
}
}, Sizing.Distribute);
this._disposables.add(this._splitView.onDidSashChange(() => {
if (this._dim.width) {
this._layoutInfo.ratio = this._splitView.getViewSize(0) / this._dim.width;
}
}));
// update editor
this._disposables.add(this._tree.onDidChangeFocus(this._updatePreview, this));
this._disposables.add(this._editor.onMouseDown(e => {
const { event, target } = e;
if (event.detail !== 2) {
return;
}
const [focus] = this._tree.getFocus();
if (!focus) {
return;
}
this.dispose();
this._editorService.openEditor({
resource: focus.item.uri,
options: { selection: target.range! }
});
}));
this._disposables.add(this._tree.onMouseDblClick(e => {
if (e.target === TreeMouseEventTarget.Twistie) {
return;
}
if (e.element) {
this.dispose();
this._editorService.openEditor({
resource: e.element.item.uri,
options: { selection: e.element.item.selectionRange, pinned: true }
});
}
}));
this._disposables.add(this._tree.onDidChangeSelection(e => {
const [element] = e.elements;
// don't close on click
if (element && isKeyboardEvent(e.browserEvent)) {
this.dispose();
this._editorService.openEditor({
resource: element.item.uri,
options: { selection: element.item.selectionRange, pinned: true }
});
}
}));
}
private async _updatePreview() {
const [element] = this._tree.getFocus();
if (!element) {
return;
}
this._previewDisposable.clear();
// update: editor and editor highlights
const options: IModelDecorationOptions = {
description: 'call-hierarchy-decoration',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'call-decoration',
overviewRuler: {
color: themeColorFromId(peekView.peekViewEditorMatchHighlight),
position: OverviewRulerLane.Center
},
};
let previewUri: URI;
if (this._direction === CallHierarchyDirection.CallsFrom) {
// outgoing calls: show caller and highlight focused calls
previewUri = element.parent ? element.parent.item.uri : element.model.root.uri;
} else {
// incoming calls: show caller and highlight focused calls
previewUri = element.item.uri;
}
const value = await this._textModelService.createModelReference(previewUri);
this._editor.setModel(value.object.textEditorModel);
// set decorations for caller ranges (if in the same file)
const decorations: IModelDeltaDecoration[] = [];
let fullRange: IRange | undefined;
let locations = element.locations;
if (!locations) {
locations = [{ uri: element.item.uri, range: element.item.selectionRange }];
}
for (const loc of locations) {
if (loc.uri.toString() === previewUri.toString()) {
decorations.push({ range: loc.range, options });
fullRange = !fullRange ? loc.range : Range.plusRange(loc.range, fullRange);
}
}
if (fullRange) {
this._editor.revealRangeInCenter(fullRange, ScrollType.Immediate);
const decorationsCollection = this._editor.createDecorationsCollection(decorations);
this._previewDisposable.add(toDisposable(() => decorationsCollection.clear()));
}
this._previewDisposable.add(value);
// update: title
const title = this._direction === CallHierarchyDirection.CallsFrom
? localize('callFrom', "Calls from '{0}'", element.model.root.name)
: localize('callsTo', "Callers of '{0}'", element.model.root.name);
this.setTitle(title);
}
showLoading(): void {
this._parent.dataset['state'] = State.Loading;
this.setTitle(localize('title.loading', "Loading..."));
this._show();
}
showMessage(message: string): void {
this._parent.dataset['state'] = State.Message;
this.setTitle('');
this.setMetaTitle('');
this._message.innerText = message;
this._show();
this._message.focus();
}
async showModel(model: CallHierarchyModel): Promise<void> {
this._show();
const viewState = this._treeViewStates.get(this._direction);
await this._tree.setInput(model, viewState);
const root = <ITreeNode<callHTree.Call, FuzzyScore>>this._tree.getNode(model).children[0];
await this._tree.expand(root.element);
if (root.children.length === 0) {
//
this.showMessage(this._direction === CallHierarchyDirection.CallsFrom
? localize('empt.callsFrom', "No calls from '{0}'", model.root.name)
: localize('empt.callsTo', "No callers of '{0}'", model.root.name));
} else {
this._parent.dataset['state'] = State.Data;
if (!viewState || this._tree.getFocus().length === 0) {
this._tree.setFocus([root.children[0].element]);
}
this._tree.domFocus();
this._updatePreview();
}
}
getModel(): CallHierarchyModel | undefined {
return this._tree.getInput();
}
getFocused(): callHTree.Call | undefined {
return this._tree.getFocus()[0];
}
async updateDirection(newDirection: CallHierarchyDirection): Promise<void> {
const model = this._tree.getInput();
if (model && newDirection !== this._direction) {
this._treeViewStates.set(this._direction, this._tree.getViewState());
this._direction = newDirection;
await this.showModel(model);
}
}
private _show() {
if (!this._isShowing) {
this.editor.revealLineInCenterIfOutsideViewport(this._where.lineNumber, ScrollType.Smooth);
super.show(Range.fromPositions(this._where), this._layoutInfo.height);
}
}
protected override _onWidth(width: number) {
if (this._dim) {
this._doLayoutBody(this._dim.height, width);
}
}
protected override _doLayoutBody(height: number, width: number): void {
if (this._dim.height !== height || this._dim.width !== width) {
super._doLayoutBody(height, width);
this._dim = new Dimension(width, height);
this._layoutInfo.height = this._viewZone ? this._viewZone.heightInLines : this._layoutInfo.height;
this._splitView.layout(width);
this._splitView.resizeView(0, width * this._layoutInfo.ratio);
}
}
}
| src/vs/workbench/contrib/callHierarchy/browser/callHierarchyPeek.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017767514509614557,
0.00017201683658640832,
0.00016774915275163949,
0.00017187814228236675,
0.0000020930103801219957
] |
{
"id": 2,
"code_window": [
"\t\t * All of the chat messages so far in the current chat session.\n",
"\t\t */\n",
"\t\thistory: ChatAgentHistoryEntry[];\n",
"\n",
"\t\t// TODO@API have \"turns\"\n",
"\t\t// history2: (ChatAgentRequest | ChatAgentResponse)[];\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// location:\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 47
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export type PerfName = 'startTime' | 'extensionActivated' | 'inputLoaded' | 'webviewCommLoaded' | 'customMarkdownLoaded' | 'editorLoaded';
type PerformanceMark = { [key in PerfName]?: number };
export class NotebookPerfMarks {
private _marks: PerformanceMark = {};
get value(): PerformanceMark {
return { ...this._marks };
}
mark(name: PerfName): void {
if (this._marks[name]) {
console.error(`Skipping overwrite of notebook perf value: ${name}`);
return;
}
this._marks[name] = Date.now();
}
}
| src/vs/workbench/contrib/notebook/common/notebookPerformance.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017420896620023996,
0.00017245188064407557,
0.00017106675659306347,
0.00017207993369083852,
0.0000013094862651996664
] |
{
"id": 2,
"code_window": [
"\t\t * All of the chat messages so far in the current chat session.\n",
"\t\t */\n",
"\t\thistory: ChatAgentHistoryEntry[];\n",
"\n",
"\t\t// TODO@API have \"turns\"\n",
"\t\t// history2: (ChatAgentRequest | ChatAgentResponse)[];\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// location:\n",
"\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 47
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13 3.5V6H12V4H6.5L6.146 3.854L5.293 3H1V10.418L0.025 13.342L0.5 14L0 13.5V2.5L0.5 2H5.5L5.854 2.146L6.707 3H12.5L13 3.5Z" fill="#C5C5C5"/>
<path d="M15.151 6H8.50002L8.14602 6.146L7.29302 7H2.50002L2.02502 7.342L0.0250244 13.342L0.500024 14L12.516 14L13 13.629L15.634 6.629L15.151 6ZM12.133 13L1.19302 13L2.86002 8H7.50002L7.85402 7.854L8.70702 7H14.5L12.133 13Z" fill="#C5C5C5"/>
</svg>
| extensions/theme-defaults/fileicons/images/folder-open-dark.svg | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.000168866608873941,
0.000168866608873941,
0.000168866608873941,
0.000168866608873941,
0
] |
{
"id": 3,
"code_window": [
"\t\t// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?\n",
"\t\treadonly followupPlaceholder?: string;\n",
"\t}\n",
"\n",
"\texport interface ChatAgentSubCommandProvider {\n",
"\n",
"\t\t/**\n",
"\t\t * Returns a list of subCommands that its agent is capable of handling. A subCommand\n",
"\t\t * can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API NAME: w/o Sub just `ChatAgentCommand` etc pp\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 155
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.9784440398216248,
0.020689688622951508,
0.00016495876479893923,
0.0003472704556770623,
0.12716132402420044
] |
{
"id": 3,
"code_window": [
"\t\t// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?\n",
"\t\treadonly followupPlaceholder?: string;\n",
"\t}\n",
"\n",
"\texport interface ChatAgentSubCommandProvider {\n",
"\n",
"\t\t/**\n",
"\t\t * Returns a list of subCommands that its agent is capable of handling. A subCommand\n",
"\t\t * can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API NAME: w/o Sub just `ChatAgentCommand` etc pp\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 155
} | {
"displayName": "Kimbie Dark Theme",
"description": "Kimbie dark theme for Visual Studio Code",
"themeLabel": "Kimbie Dark"
}
| extensions/theme-kimbie-dark/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017038437363225967,
0.00017038437363225967,
0.00017038437363225967,
0.00017038437363225967,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.