mirror of
https://github.com/ckaczor/azuredatastudio.git
synced 2026-02-10 02:02:35 -05:00
Merge VS Code 1.26.1 (#2394)
* Squash merge commits for 1.26 (#1) (#2323) * Polish tag search as per feedback (#55269) * Polish tag search as per feedback * Updated regex * Allow users to opt-out of features that send online requests in the background (#55097) * settings sweep #54690 * Minor css tweaks to enable eoverflow elipsis in more places (#55277) * fix an issue with titlebarheight when not scaling with zoom * Settings descriptions update #54690 * fixes #55209 * Settings editor - many padding fixes * More space above level 2 label * Fixing Cannot debug npm script using Yarn #55103 * Settings editor - show ellipsis when description overflows * Settings editor - ... fix measuring around links, relayout * Setting descriptions * Settings editor - fix ... for some short lines, fix select container width * Settings editor - overlay trees so scrollable shadow is full width * Fix #54133 - missing extension settings after reload * Settings color token description tweak * Settings editor - disable overflow indicator temporarily, needs to be faster * Added command to Run the selected npm script * fixes #54452 * fixes #54929 * fixes #55248 * prefix command with extension name * Contribute run selected to the context menu * node-debug@1.26.6 * Allow terminal rendererType to be swapped out at runtime Part of #53274 Fixes #55344 * Settings editor - fix not focusing search when restoring editor setInput must be actually async. Will be fixed naturally when we aren't using winJS promises... * Settings editor - TOC should only expand the section with a selected item * Bump node-debug2 * Settings editor - Tree focus outlines * Settings editor - don't blink the scrollbar when toc selection changes And hide TOC correctly when the editor is narrow * Settings editor - header rows should not be selectable * fixes #54877 * change debug assignee to isi * Settings sweep (#54690) * workaround for #55051 * Settings sweep (#54690) * settings sweep #54690 * Don't try closing tags when you type > after another > * Describe what implementation code lens does Fixes #55370 * fix javadoc formatter setting description * fixes #55325 * update to officical TS version * Settings editor - Even more padding, use semibold instead of bold * Fix #55357 - fix TOC twistie * fixes #55288 * explorer: refresh on di change file system provider registration fixes #53256 * Disable push to Linux repo to test standalone publisher * New env var to notify log level to extensions #54001 * Disable snippets in extension search (when not in suggest dropdown) (#55281) * Disable snippits in extension search (when not in suggest dropdown) * Add monaco input contributions * Fix bug preventing snippetSuggestions from taking effect in sub-editors * Latest emmet helper to fix #52366 * Fix comment updates for threads within same file * Allow extensions to log telemetry to log files #54001 * Pull latest css grammar * files.exclude control - use same style for "add" vs "edit" * files.exclude control - focus/keyboard behavior * don't show menubar too early * files.exclude - better styling * Place cursor at end of extensions search box on autofill (#55254) * Place cursor at end of extensions search box on autofill * Use position instead of selection * fix linux build issue (empty if block) * Settings editor - fix extension category prefixes * Settings editor - add simple ellipsis for first line that overflows, doesn't cover case when first line does not overflow but there is more text, TODO * File/Text search provider docs * Fixes #52655 * Include epoch (#55008) * Fixes #53385 * Fixes #49480 * VS Code Insiders (Users) not opening Fixes #55353 * Better handling of the case when the extension host fails to start * Fixes #53966 * Remove confusing Start from wordPartLeft commands ID * vscode-xterm@3.6.0-beta12 Fixes #55488 * Initial size is set to infinity!! Fixes #55461 * Polish embeddedEditorBackground * configuration service misses event * Fix #55224 - fix duplicate results in multiroot workspace from splitting the diskseach query * Select all not working in issue reporter on mac, fixes #55424 * Disable fuzzy matching for extensions autosuggest (#55498) * Fix clipping of extensions search border in some third party themes (#55504) * fixes #55538 * Fix bug causing an aria alert to not be shown the third time (and odd numbers thereafter) * Settings editor - work around rendering glitch with webkit-line-clamp * Settings editor - revert earlier '...' changes * Settings editor - move enumDescription to its own div, because it disturbs -webkit-line-clamp for some reason * Settings editor - better overflow indicator * Don't show existing filters in autocomplete (#55495) * Dont show existing filters in autocomplete * Simplify * Settings Editor: Add aria labels for input elements Fixes: #54836 (#55543) * fixes #55223 * Update vscode-css-languageservice to 3.0.10-next.1 * Fix #55509 - settings navigation * Fix #55519 * Fix #55520 * FIx #55524 * Fix #55556 - include wordSeparators in all search queries, so findTextInFiles can respect isWordMatch correctly * oss updates for endgame * Fix unit tests * fixes #55522 * Avoid missing manifest error from bubbling up #54757 * Settings format crawl * Search provider - Fix FileSearchProvider to return array, not progress * Fix #55598 * Settings editor - fix NPE rendering settings with no description * dont render inden guides in search box (#55600) * fixes #55454 * More settings crawl * Another change for #55598 - maxResults applies to FileSearch and TextSearch but not FileIndex * Fix FileSearchProvider unit tests for progress change * fixes #55561 * Settings description update for #54690 * Update setting descriptions for online services * Minor edits * fixes #55513 * fixes #55451 * Fix #55612 - fix findTextInFiles cancellation * fixes #55539 * More setting description tweaks * Setting to disable online experiments #54354 * fixes #55507 * fixes #55515 * Show online services action only in Insiders for now * Settings editor - change toc behavior default to 'filter' * Settings editor - nicer filter count style during search * Fix #55617 - search viewlet icons * Settings editor - better styling for element count indicator * SearchProvider - fix NPE when searching extraFileResources * Allow extends to work without json suffix Fixes #16905 * Remove accessability options logic entirely Follow up on #55451 * use latest version of DAP * fixes #55490 * fixes #55122 * fixes #52332 * Avoid assumptions about git: URIs (fixes #36236) * relative path for descriptions * resourece: get rid of isFile context key fixes #48275 * Register previous ids for compatibility (#53497) * more tuning for #48275 * no need to always re-read "files explorer" fixes #52003 * read out active composites properly fixes #51967 * Update link colors for hc theme to meet color contrast ratio, fixes #55651 Also updated link color for `textLinkActiveForeground` to be the same as `textLinkForeground` as it wasn't properly updated * detect 'winpty-agent.exe'; fixes #55672 * node-debug@1.26.7 * reset counter on new label * Settings editor - fix multiple setting links in one description * Settings editor - color code blocks in setting descriptions, fix #55532 * Settings editor - hover color in TOC * Settings editor - fix navigation NPE * Settings editor - fix text control width * Settings editor - maybe fix #55684 * Fix bug causing cursor to not move on paste * fixes #53582 * Use ctrlCmd instead of ctrl for go down from search box * fixes #55264 * fixes #55456 * filter for spcaes before triggering search (#55611) * Fix #55698 - don't lose filtered TOC counts when refreshing TOC * fixes #55421 * fixes #28979 * fixes #55576 * only add check for updates to windows/linux help * readonly files: append decoration to label fixes #53022 * debug: do not show toolbar while initialising fixes #55026 * Opening launch.json should not activate debug extensions fixes #55029 * fixes #55435 * fixes #55434 * fixes #55439 * trigger menu only on altkey up * Fix #50555 - fix settings editor memory leak * Fix #55712 - no need to focus 'a' anymore when restoring control focus after tree render * fixes #55335 * proper fix for readonly model fixes #53022 * improve FoldingRangeKind spec (for #55686) * Use class with static fields (fixes #55494) * Fixes #53671 * fixes #54630 * [html] should disable ionic suggestions by default. Currently forces deprecated Ionic v1 suggestions in .html files while typing. Fixes #53324 * cleanup deps * debug issues back to andre * update electron for smoketest * Fix #55757 - prevent settings tabs from overflowing * Fix #53897 - revert setting menu defaults to old editor * Add enum descriptions to `typescript.preferences.importModuleSpecifier` * Fix #55767 - leaking style elements from settings editor * Fix #55521 - prevent flashing when clicking in exclude control * Update Git modified color for contrast ratio, fixes #53140 * Revert "Merge branch 'master' of github.com:Microsoft/vscode" This reverts commit bf46b6bfbae0cab99c2863e1244a916181fa9fbc, reversing changes made to e275a424483dfb4ed33b428c97d5e2c441d6b917. * Revert "Revert "Merge branch 'master' of github.com:Microsoft/vscode"" This reverts commit 53949d963f39e40757557c6526332354a31d9154. * don't ask to install an incomplete menu * Fix NPE in terminal AccessibilityManager Fixes #55744 * don't display fallback menu unless we've closed the last window * fixes #55547 * Fix smoke tests for extension search box * Update OSSREADME.json for Electron 2.0.5 * Update distro Includes Chromium license changes * fix #55455 * fix #55865 * fixes #55893 * Fix bug causing workspace recommendations to go away upon ignoring a recommendation (#55805) * Fix bug causing workspace recommendations to go away upon ignoring a recommendation * ONly show on @recommended or @recommended:workspace * Make more consistant * Fix #55911 * Understand json activity (#55926) * Understand json file activity * Refactoring * adding composer.json * Distro update for experiments * use terminal.processId for auto-attach; fixes #55918 * Reject invalid URI with vscode.openFolder (for #55891) * improve win32 setup system vs user detection fixes #55840 fixes #55840 delay winreg import related to #55840 show notification earlier related to #55840 fix #55840 update inno setup message related to #55840 * Fix #55593 - this code only operates on local paths, so use fsPath and Uri.file instead * Bring back the old menu due to electron 2.0 issues (#55913) * add the old menu back for native menus * make menu labels match * `vscode.openFolder`: treat missing URI schema gracefully (for #55891) * delay EH reattach; fixes #55955 * Mark all json files under appSettingsHome as settings * Use localized strings for telemetry opt-out * Exception when saving file editor opened from remote file provider (fixes #55051) * Remove terminal menu from stable Fixes 56003 * VSCode Insiders crashes on open with TypeError: Cannot read property 'lastIndexOf' of undefined. Fixes #54933 * improve fix for #55891 * fix #55916 * Improve #55891 * increase EH debugging restart delay; fixes #55955 * Revert "Don't include non-resource entries in history quick pick" This reverts commit 37209a838e9f7e9abe6dc53ed73cdf1e03b72060. * Diff editor: horizontal scrollbar height is smaller (fixes #56062) * improve openFolder uri fix (correctly treat backslashes) * fixes #56116 repair ipc for native menubar keybindings * Fix #56240 - Open the JSON settings editor instead of the UI editor * Fix #55536 * uriDisplay: if no formatter is registered fall back to getPathlabel fixes #56104 * VSCode hangs when opening python file. Fixes #56377 * VS Code Hangs When Opening Specific PowerShell File. Fixes #56430 * Fix #56433 - search extraFileResources even when no folders open * Workaround #55649 * Fix in master #56371 * Fix tests #56371 * Fix in master #56317 * increase version to 1.26.1 * Fixes #56387: Handle SIGPIPE in extension host * fixes #56185 * Fix merge issues (part 1) * Fix build breaks (part 1) * Build breaks (part 2) * Build breaks (part 3) * More build breaks (part 4) * Fix build breaks (part 5) * WIP * Fix menus * Render query result and message panels (#2363) * Put back query editor hot exit changes * Fix grid changes that broke profiler (#2365) * Update APIs for saving query editor state * Fix restore view state for profiler and edit data * Updating custom default themes to support 4.5:1 contrast ratio * Test updates * Fix Extension Manager and Windows Setup * Update license headers * Add appveyor and travis files back * Fix hidden modal dropdown issue
This commit is contained in:
@@ -157,8 +157,19 @@ export const isSafari = (userAgent.indexOf('Chrome') === -1) && (userAgent.index
|
||||
export const isIPad = (userAgent.indexOf('iPad') >= 0);
|
||||
export const isEdgeWebView = isEdge && (userAgent.indexOf('WebView/') >= 0);
|
||||
|
||||
export const isChromev56 = (
|
||||
userAgent.indexOf('Chrome/56.') >= 0
|
||||
// Edge likes to impersonate Chrome sometimes
|
||||
&& userAgent.indexOf('Edge/') === -1
|
||||
);
|
||||
export function hasClipboardSupport() {
|
||||
if (isIE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isEdge) {
|
||||
let index = userAgent.indexOf('Edge/');
|
||||
let version = parseInt(userAgent.substring(index + 5, userAgent.indexOf('.', index)), 10);
|
||||
|
||||
if (!version || (version >= 12 && version <= 16)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -5,9 +5,8 @@
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./builder';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import * as types from 'vs/base/common/types';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
|
||||
import * as strings from 'vs/base/common/strings';
|
||||
import * as assert from 'vs/base/common/assert';
|
||||
import * as DOM from 'vs/base/browser/dom';
|
||||
@@ -70,8 +69,8 @@ export class Builder implements IDisposable {
|
||||
private offdom: boolean;
|
||||
private container: HTMLElement;
|
||||
private createdElements: HTMLElement[];
|
||||
private toUnbind: { [type: string]: IDisposable[]; };
|
||||
private captureToUnbind: { [type: string]: IDisposable[]; };
|
||||
private toDispose: { [type: string]: IDisposable[]; };
|
||||
private captureToDispose: { [type: string]: IDisposable[]; };
|
||||
|
||||
constructor(element?: HTMLElement, offdom?: boolean) {
|
||||
this.offdom = offdom;
|
||||
@@ -81,27 +80,27 @@ export class Builder implements IDisposable {
|
||||
this.currentElement = element;
|
||||
this.createdElements = [];
|
||||
|
||||
this.toUnbind = {};
|
||||
this.captureToUnbind = {};
|
||||
this.toDispose = {};
|
||||
this.captureToDispose = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new builder that lets the current HTML Element of this builder be the container
|
||||
* for future additions on the builder.
|
||||
*/
|
||||
public asContainer(): Builder {
|
||||
asContainer(): Builder {
|
||||
return withBuilder(this, this.offdom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones the builder providing the same properties as this one.
|
||||
*/
|
||||
public clone(): Builder {
|
||||
clone(): Builder {
|
||||
let builder = new Builder(this.container, this.offdom);
|
||||
builder.currentElement = this.currentElement;
|
||||
builder.createdElements = this.createdElements;
|
||||
builder.captureToUnbind = this.captureToUnbind;
|
||||
builder.toUnbind = this.toUnbind;
|
||||
builder.captureToDispose = this.captureToDispose;
|
||||
builder.toDispose = this.toDispose;
|
||||
|
||||
return builder;
|
||||
}
|
||||
@@ -113,9 +112,9 @@ export class Builder implements IDisposable {
|
||||
* at the end.
|
||||
* This method is a no-op unless the builder was created with the offdom option to be true.
|
||||
*/
|
||||
public build(container?: Builder, index?: number): Builder;
|
||||
public build(container?: HTMLElement, index?: number): Builder;
|
||||
public build(container?: any, index?: number): Builder {
|
||||
build(container?: Builder, index?: number): Builder;
|
||||
build(container?: HTMLElement, index?: number): Builder;
|
||||
build(container?: any, index?: number): Builder {
|
||||
assert.ok(this.offdom, 'This builder was not created off-dom, so build() can not be called.');
|
||||
|
||||
// Use builders own container if present
|
||||
@@ -154,9 +153,9 @@ export class Builder implements IDisposable {
|
||||
* attached the current element. If the current element has a parent, it will be
|
||||
* detached from that parent.
|
||||
*/
|
||||
public appendTo(container?: Builder, index?: number): Builder;
|
||||
public appendTo(container?: HTMLElement, index?: number): Builder;
|
||||
public appendTo(container?: any, index?: number): Builder {
|
||||
appendTo(container?: Builder, index?: number): Builder;
|
||||
appendTo(container?: HTMLElement, index?: number): Builder;
|
||||
appendTo(container?: any, index?: number): Builder {
|
||||
|
||||
// Use builders own container if present
|
||||
if (!container) {
|
||||
@@ -194,9 +193,9 @@ export class Builder implements IDisposable {
|
||||
* of the return value being the builder which called the operation (`a` in the
|
||||
* first case; `b` in the second case).
|
||||
*/
|
||||
public append(child: HTMLElement, index?: number): Builder;
|
||||
public append(child: Builder, index?: number): Builder;
|
||||
public append(child: any, index?: number): Builder {
|
||||
append(child: HTMLElement, index?: number): Builder;
|
||||
append(child: Builder, index?: number): Builder;
|
||||
append(child: any, index?: number): Builder {
|
||||
assert.ok(child, 'Need a child to append');
|
||||
|
||||
if (DOM.isHTMLElement(child)) {
|
||||
@@ -213,7 +212,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Removes the current element of this builder from its parent node.
|
||||
*/
|
||||
public offDOM(): Builder {
|
||||
offDOM(): Builder {
|
||||
if (this.currentElement.parentNode) {
|
||||
this.currentElement.parentNode.removeChild(this.currentElement);
|
||||
}
|
||||
@@ -224,14 +223,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Returns the HTML Element the builder is currently active on.
|
||||
*/
|
||||
public getHTMLElement(): HTMLElement {
|
||||
getHTMLElement(): HTMLElement {
|
||||
return this.currentElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the HTML Element the builder is building in.
|
||||
*/
|
||||
public getContainer(): HTMLElement {
|
||||
getContainer(): HTMLElement {
|
||||
return this.container;
|
||||
}
|
||||
|
||||
@@ -245,7 +244,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public div(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
div(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('div', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -257,7 +256,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public p(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
p(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('p', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -269,7 +268,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public ul(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
ul(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('ul', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -281,7 +280,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public li(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
li(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('li', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -293,7 +292,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public span(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
span(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('span', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -305,7 +304,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public img(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
img(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('img', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -317,7 +316,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public a(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
a(attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement('a', attributes, fn);
|
||||
}
|
||||
|
||||
@@ -329,7 +328,7 @@ export class Builder implements IDisposable {
|
||||
* of the element. The function will be called with a new builder created with the
|
||||
* provided element.
|
||||
*/
|
||||
public element(name: string, attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
element(name: string, attributes?: any, fn?: (builder: Builder) => void): Builder {
|
||||
return this.doElement(name, attributes, fn);
|
||||
}
|
||||
|
||||
@@ -371,7 +370,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Calls focus() on the current HTML element;
|
||||
*/
|
||||
public domFocus(): Builder {
|
||||
domFocus(): Builder {
|
||||
this.currentElement.focus();
|
||||
|
||||
return this;
|
||||
@@ -380,7 +379,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Calls blur() on the current HTML element;
|
||||
*/
|
||||
public domBlur(): Builder {
|
||||
domBlur(): Builder {
|
||||
this.currentElement.blur();
|
||||
|
||||
return this;
|
||||
@@ -389,14 +388,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Registers listener on event types on the current element.
|
||||
*/
|
||||
public on<E extends Event = Event>(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
public on<E extends Event = Event>(typeArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
public on<E extends Event = Event>(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder {
|
||||
on<E extends Event = Event>(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
on<E extends Event = Event>(typeArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
on<E extends Event = Event>(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder {
|
||||
|
||||
// Event Type Array
|
||||
if (types.isArray(arg1)) {
|
||||
arg1.forEach((type: string) => {
|
||||
this.on(type, fn, listenerToUnbindContainer, useCapture);
|
||||
this.on(type, fn, listenerToDisposeContainer, useCapture);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -411,15 +410,15 @@ export class Builder implements IDisposable {
|
||||
|
||||
// Remember for off() use
|
||||
if (useCapture) {
|
||||
if (!this.captureToUnbind[type]) {
|
||||
this.captureToUnbind[type] = [];
|
||||
if (!this.captureToDispose[type]) {
|
||||
this.captureToDispose[type] = [];
|
||||
}
|
||||
this.captureToUnbind[type].push(unbind);
|
||||
this.captureToDispose[type].push(unbind);
|
||||
} else {
|
||||
if (!this.toUnbind[type]) {
|
||||
this.toUnbind[type] = [];
|
||||
if (!this.toDispose[type]) {
|
||||
this.toDispose[type] = [];
|
||||
}
|
||||
this.toUnbind[type].push(unbind);
|
||||
this.toDispose[type].push(unbind);
|
||||
}
|
||||
|
||||
// Bind to Element
|
||||
@@ -428,8 +427,8 @@ export class Builder implements IDisposable {
|
||||
this.setProperty(LISTENER_BINDING_ID, listenerBinding);
|
||||
|
||||
// Add to Array if passed in
|
||||
if (listenerToUnbindContainer && types.isArray(listenerToUnbindContainer)) {
|
||||
listenerToUnbindContainer.push(unbind);
|
||||
if (listenerToDisposeContainer && types.isArray(listenerToDisposeContainer)) {
|
||||
listenerToDisposeContainer.push(unbind);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,9 +438,9 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Removes all listeners from all elements created by the builder for the given event type.
|
||||
*/
|
||||
public off(type: string, useCapture?: boolean): Builder;
|
||||
public off(typeArray: string[], useCapture?: boolean): Builder;
|
||||
public off(arg1: any, useCapture?: boolean): Builder {
|
||||
off(type: string, useCapture?: boolean): Builder;
|
||||
off(typeArray: string[], useCapture?: boolean): Builder;
|
||||
off(arg1: any, useCapture?: boolean): Builder {
|
||||
|
||||
// Event Type Array
|
||||
if (types.isArray(arg1)) {
|
||||
@@ -454,12 +453,12 @@ export class Builder implements IDisposable {
|
||||
else {
|
||||
let type = arg1;
|
||||
if (useCapture) {
|
||||
if (this.captureToUnbind[type]) {
|
||||
this.captureToUnbind[type] = dispose(this.captureToUnbind[type]);
|
||||
if (this.captureToDispose[type]) {
|
||||
this.captureToDispose[type] = dispose(this.captureToDispose[type]);
|
||||
}
|
||||
} else {
|
||||
if (this.toUnbind[type]) {
|
||||
this.toUnbind[type] = dispose(this.toUnbind[type]);
|
||||
if (this.toDispose[type]) {
|
||||
this.toDispose[type] = dispose(this.toDispose[type]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -481,9 +480,9 @@ export class Builder implements IDisposable {
|
||||
* Registers listener on event types on the current element and removes
|
||||
* them after first invocation.
|
||||
*/
|
||||
public once<E extends Event = Event>(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
public once<E extends Event = Event>(typesArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
public once<E extends Event = Event>(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder {
|
||||
once<E extends Event = Event>(type: string, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
once<E extends Event = Event>(typesArray: string[], fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder;
|
||||
once<E extends Event = Event>(arg1: any, fn: (e: E, builder: Builder, unbind: IDisposable) => void, listenerToDisposeContainer?: IDisposable[], useCapture?: boolean): Builder {
|
||||
|
||||
// Event Type Array
|
||||
if (types.isArray(arg1)) {
|
||||
@@ -503,8 +502,8 @@ export class Builder implements IDisposable {
|
||||
}, useCapture || false);
|
||||
|
||||
// Add to Array if passed in
|
||||
if (listenerToUnbindContainer && types.isArray(listenerToUnbindContainer)) {
|
||||
listenerToUnbindContainer.push(unbind);
|
||||
if (listenerToDisposeContainer && types.isArray(listenerToDisposeContainer)) {
|
||||
listenerToDisposeContainer.push(unbind);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,12 +519,12 @@ export class Builder implements IDisposable {
|
||||
* c) an object literal passed in will apply the properties of the literal as attributes
|
||||
* to the current element of the builder.
|
||||
*/
|
||||
public attr(name: string): string;
|
||||
public attr(name: string, value: string): Builder;
|
||||
public attr(name: string, value: boolean): Builder;
|
||||
public attr(name: string, value: number): Builder;
|
||||
public attr(attributes: any): Builder;
|
||||
public attr(firstP: any, secondP?: any): any {
|
||||
attr(name: string): string;
|
||||
attr(name: string, value: string): Builder;
|
||||
attr(name: string, value: boolean): Builder;
|
||||
attr(name: string, value: number): Builder;
|
||||
attr(attributes: any): Builder;
|
||||
attr(firstP: any, secondP?: any): any {
|
||||
|
||||
// Apply Object Literal to Attributes of Element
|
||||
if (types.isObject(firstP)) {
|
||||
@@ -574,14 +573,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Removes an attribute by the given name.
|
||||
*/
|
||||
public removeAttribute(prop: string): void {
|
||||
removeAttribute(prop: string): void {
|
||||
this.currentElement.removeAttribute(prop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the id attribute to the value provided for the current HTML element of the builder.
|
||||
*/
|
||||
public id(id: string): Builder {
|
||||
id(id: string): Builder {
|
||||
this.currentElement.setAttribute('id', id);
|
||||
|
||||
return this;
|
||||
@@ -590,7 +589,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the title attribute to the value provided for the current HTML element of the builder.
|
||||
*/
|
||||
public title(title: string): Builder {
|
||||
title(title: string): Builder {
|
||||
this.currentElement.setAttribute('title', title);
|
||||
|
||||
return this;
|
||||
@@ -599,7 +598,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the type attribute to the value provided for the current HTML element of the builder.
|
||||
*/
|
||||
public type(type: string): Builder {
|
||||
type(type: string): Builder {
|
||||
this.currentElement.setAttribute('type', type);
|
||||
|
||||
return this;
|
||||
@@ -608,7 +607,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the value attribute to the value provided for the current HTML element of the builder.
|
||||
*/
|
||||
public value(value: string): Builder {
|
||||
value(value: string): Builder {
|
||||
this.currentElement.setAttribute('value', value);
|
||||
|
||||
return this;
|
||||
@@ -617,7 +616,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the tabindex attribute to the value provided for the current HTML element of the builder.
|
||||
*/
|
||||
public tabindex(index: number): Builder {
|
||||
tabindex(index: number): Builder {
|
||||
this.currentElement.setAttribute('tabindex', index.toString());
|
||||
|
||||
return this;
|
||||
@@ -633,10 +632,10 @@ export class Builder implements IDisposable {
|
||||
* c) an object literal passed in will apply the properties of the literal as styles
|
||||
* to the current element of the builder.
|
||||
*/
|
||||
public style(name: string): string;
|
||||
public style(name: string, value: string): Builder;
|
||||
public style(attributes: any): Builder;
|
||||
public style(firstP: any, secondP?: any): any {
|
||||
style(name: string): string;
|
||||
style(name: string, value: string): Builder;
|
||||
style(attributes: any): Builder;
|
||||
style(firstP: any, secondP?: any): any {
|
||||
|
||||
// Apply Object Literal to Styles of Element
|
||||
if (types.isObject(firstP)) {
|
||||
@@ -702,14 +701,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Returns the computed CSS style for the current HTML element of the builder.
|
||||
*/
|
||||
public getComputedStyle(): CSSStyleDeclaration {
|
||||
getComputedStyle(): CSSStyleDeclaration {
|
||||
return DOM.getComputedStyle(this.currentElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the variable list of arguments as class names to the current HTML element of the builder.
|
||||
*/
|
||||
public addClass(...classes: string[]): Builder {
|
||||
addClass(...classes: string[]): Builder {
|
||||
classes.forEach((nameValue: string) => {
|
||||
let names = nameValue.split(' ');
|
||||
names.forEach((name: string) => {
|
||||
@@ -724,7 +723,7 @@ export class Builder implements IDisposable {
|
||||
* Sets the class name of the current HTML element of the builder to the provided className.
|
||||
* If shouldAddClass is provided - for true class is added, for false class is removed.
|
||||
*/
|
||||
public setClass(className: string, shouldAddClass: boolean = null): Builder {
|
||||
setClass(className: string, shouldAddClass: boolean = null): Builder {
|
||||
if (shouldAddClass === null) {
|
||||
this.currentElement.className = className;
|
||||
} else if (shouldAddClass) {
|
||||
@@ -739,14 +738,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Returns whether the current HTML element of the builder has the provided class assigned.
|
||||
*/
|
||||
public hasClass(className: string): boolean {
|
||||
hasClass(className: string): boolean {
|
||||
return DOM.hasClass(this.currentElement, className);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the variable list of arguments as class names from the current HTML element of the builder.
|
||||
*/
|
||||
public removeClass(...classes: string[]): Builder {
|
||||
removeClass(...classes: string[]): Builder {
|
||||
classes.forEach((nameValue: string) => {
|
||||
let names = nameValue.split(' ');
|
||||
names.forEach((name: string) => {
|
||||
@@ -760,7 +759,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Adds or removes the provided className for the current HTML element of the builder.
|
||||
*/
|
||||
public toggleClass(className: string): Builder {
|
||||
toggleClass(className: string): Builder {
|
||||
if (this.hasClass(className)) {
|
||||
this.removeClass(className);
|
||||
} else {
|
||||
@@ -773,7 +772,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the CSS property color.
|
||||
*/
|
||||
public color(color: string): Builder {
|
||||
color(color: string): Builder {
|
||||
this.currentElement.style.color = color;
|
||||
|
||||
return this;
|
||||
@@ -782,10 +781,10 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the CSS property padding.
|
||||
*/
|
||||
public padding(padding: string): Builder;
|
||||
public padding(top: number, right?: number, bottom?: number, left?: number): Builder;
|
||||
public padding(top: string, right?: string, bottom?: string, left?: string): Builder;
|
||||
public padding(top: any, right?: any, bottom?: any, left?: any): Builder {
|
||||
padding(padding: string): Builder;
|
||||
padding(top: number, right?: number, bottom?: number, left?: number): Builder;
|
||||
padding(top: string, right?: string, bottom?: string, left?: string): Builder;
|
||||
padding(top: any, right?: any, bottom?: any, left?: any): Builder {
|
||||
if (types.isString(top) && top.indexOf(' ') >= 0) {
|
||||
return this.padding.apply(this, top.split(' '));
|
||||
}
|
||||
@@ -812,10 +811,10 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the CSS property margin.
|
||||
*/
|
||||
public margin(margin: string): Builder;
|
||||
public margin(top: number, right?: number, bottom?: number, left?: number): Builder;
|
||||
public margin(top: string, right?: string, bottom?: string, left?: string): Builder;
|
||||
public margin(top: any, right?: any, bottom?: any, left?: any): Builder {
|
||||
margin(margin: string): Builder;
|
||||
margin(top: number, right?: number, bottom?: number, left?: number): Builder;
|
||||
margin(top: string, right?: string, bottom?: string, left?: string): Builder;
|
||||
margin(top: any, right?: any, bottom?: any, left?: any): Builder {
|
||||
if (types.isString(top) && top.indexOf(' ') >= 0) {
|
||||
return this.margin.apply(this, top.split(' '));
|
||||
}
|
||||
@@ -842,10 +841,10 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the CSS property position.
|
||||
*/
|
||||
public position(position: string): Builder;
|
||||
public position(top: number, right?: number, bottom?: number, left?: number, position?: string): Builder;
|
||||
public position(top: string, right?: string, bottom?: string, left?: string, position?: string): Builder;
|
||||
public position(top: any, right?: any, bottom?: any, left?: any, position?: string): Builder {
|
||||
position(position: string): Builder;
|
||||
position(top: number, right?: number, bottom?: number, left?: number, position?: string): Builder;
|
||||
position(top: string, right?: string, bottom?: string, left?: string, position?: string): Builder;
|
||||
position(top: any, right?: any, bottom?: any, left?: any, position?: string): Builder {
|
||||
if (types.isString(top) && top.indexOf(' ') >= 0) {
|
||||
return this.position.apply(this, top.split(' '));
|
||||
}
|
||||
@@ -878,10 +877,10 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the CSS property size.
|
||||
*/
|
||||
public size(size: string): Builder;
|
||||
public size(width: number, height?: number): Builder;
|
||||
public size(width: string, height?: string): Builder;
|
||||
public size(width: any, height?: any): Builder {
|
||||
size(size: string): Builder;
|
||||
size(width: number, height?: number): Builder;
|
||||
size(width: string, height?: string): Builder;
|
||||
size(width: any, height?: any): Builder {
|
||||
if (types.isString(width) && width.indexOf(' ') >= 0) {
|
||||
return this.size.apply(this, width.split(' '));
|
||||
}
|
||||
@@ -900,7 +899,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the CSS property display.
|
||||
*/
|
||||
public display(display: string): Builder {
|
||||
display(display: string): Builder {
|
||||
this.currentElement.style.display = display;
|
||||
|
||||
return this;
|
||||
@@ -909,7 +908,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Shows the current element of the builder.
|
||||
*/
|
||||
public show(): Builder {
|
||||
show(): Builder {
|
||||
if (this.hasClass('monaco-builder-hidden')) {
|
||||
this.removeClass('monaco-builder-hidden');
|
||||
}
|
||||
@@ -917,7 +916,7 @@ export class Builder implements IDisposable {
|
||||
this.attr('aria-hidden', 'false');
|
||||
|
||||
// Cancel any pending showDelayed() invocation
|
||||
this.cancelVisibilityPromise();
|
||||
this.cancelVisibilityTimeout();
|
||||
|
||||
return this;
|
||||
}
|
||||
@@ -929,18 +928,18 @@ export class Builder implements IDisposable {
|
||||
* only show the element when a specific delay is reached (e.g. for a long running
|
||||
* operation.
|
||||
*/
|
||||
public showDelayed(delay: number): Builder {
|
||||
showDelayed(delay: number): Builder {
|
||||
|
||||
// Cancel any pending showDelayed() invocation
|
||||
this.cancelVisibilityPromise();
|
||||
this.cancelVisibilityTimeout();
|
||||
|
||||
let promise = TPromise.timeout(delay);
|
||||
this.setProperty(VISIBILITY_BINDING_ID, promise);
|
||||
|
||||
promise.done(() => {
|
||||
// Install new delay for showing
|
||||
const handle = setTimeout(() => {
|
||||
this.removeProperty(VISIBILITY_BINDING_ID);
|
||||
this.show();
|
||||
});
|
||||
}, delay);
|
||||
|
||||
this.setProperty(VISIBILITY_BINDING_ID, toDisposable(() => clearTimeout(handle)));
|
||||
|
||||
return this;
|
||||
}
|
||||
@@ -948,14 +947,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Hides the current element of the builder.
|
||||
*/
|
||||
public hide(): Builder {
|
||||
hide(): Builder {
|
||||
if (!this.hasClass('monaco-builder-hidden')) {
|
||||
this.addClass('monaco-builder-hidden');
|
||||
}
|
||||
this.attr('aria-hidden', 'true');
|
||||
|
||||
// Cancel any pending showDelayed() invocation
|
||||
this.cancelVisibilityPromise();
|
||||
this.cancelVisibilityTimeout();
|
||||
|
||||
return this;
|
||||
}
|
||||
@@ -963,14 +962,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Returns true if the current element of the builder is hidden.
|
||||
*/
|
||||
public isHidden(): boolean {
|
||||
isHidden(): boolean {
|
||||
return this.hasClass('monaco-builder-hidden') || this.currentElement.style.display === 'none';
|
||||
}
|
||||
|
||||
private cancelVisibilityPromise(): void {
|
||||
let promise: TPromise<void> = this.getProperty(VISIBILITY_BINDING_ID);
|
||||
if (promise) {
|
||||
promise.cancel();
|
||||
private cancelVisibilityTimeout(): void {
|
||||
const visibilityDisposable = this.getProperty(VISIBILITY_BINDING_ID) as IDisposable;
|
||||
if (visibilityDisposable) {
|
||||
visibilityDisposable.dispose();
|
||||
this.removeProperty(VISIBILITY_BINDING_ID);
|
||||
}
|
||||
}
|
||||
@@ -986,7 +985,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the innerHTML attribute.
|
||||
*/
|
||||
public innerHtml(html: string, append?: boolean): Builder {
|
||||
innerHtml(html: string, append?: boolean): Builder {
|
||||
if (append) {
|
||||
this.currentElement.innerHTML += html;
|
||||
} else {
|
||||
@@ -1000,7 +999,7 @@ export class Builder implements IDisposable {
|
||||
* Sets the textContent property of the element.
|
||||
* All HTML special characters will be escaped.
|
||||
*/
|
||||
public text(text: string, append?: boolean): Builder {
|
||||
text(text: string, append?: boolean): Builder {
|
||||
if (append) {
|
||||
// children is child Elements versus childNodes includes textNodes
|
||||
if (this.currentElement.children.length === 0) {
|
||||
@@ -1021,14 +1020,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Sets the innerHTML attribute in escaped form.
|
||||
*/
|
||||
public safeInnerHtml(html: string, append?: boolean): Builder {
|
||||
safeInnerHtml(html: string, append?: boolean): Builder {
|
||||
return this.innerHtml(strings.escape(html), append);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to store arbritary data into the current element.
|
||||
*/
|
||||
public setProperty(key: string, value: any): Builder {
|
||||
setProperty(key: string, value: any): Builder {
|
||||
setPropertyOnElement(this.currentElement, key, value);
|
||||
|
||||
return this;
|
||||
@@ -1037,14 +1036,14 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Allows to get arbritary data from the current element.
|
||||
*/
|
||||
public getProperty(key: string, fallback?: any): any {
|
||||
getProperty(key: string, fallback?: any): any {
|
||||
return getPropertyFromElement(this.currentElement, key, fallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a property from the current element that is stored under the given key.
|
||||
*/
|
||||
public removeProperty(key: string): Builder {
|
||||
removeProperty(key: string): Builder {
|
||||
if (hasData(this.currentElement)) {
|
||||
delete data(this.currentElement)[key];
|
||||
}
|
||||
@@ -1055,7 +1054,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Returns a new builder with the child at the given index.
|
||||
*/
|
||||
public child(index = 0): Builder {
|
||||
child(index = 0): Builder {
|
||||
let children = this.currentElement.children;
|
||||
|
||||
return withElement(<HTMLElement>children.item(index));
|
||||
@@ -1095,7 +1094,7 @@ export class Builder implements IDisposable {
|
||||
* event listners registered and also clear any data binding and properties stored
|
||||
* to any child element.
|
||||
*/
|
||||
public empty(): Builder {
|
||||
empty(): Builder {
|
||||
this.unbindDescendants(this.currentElement);
|
||||
|
||||
this.clearChildren();
|
||||
@@ -1110,7 +1109,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Removes all HTML elements from the current element of the builder.
|
||||
*/
|
||||
public clearChildren(): Builder {
|
||||
clearChildren(): Builder {
|
||||
|
||||
// Remove Elements
|
||||
if (this.currentElement) {
|
||||
@@ -1124,7 +1123,7 @@ export class Builder implements IDisposable {
|
||||
* Removes the current HTML element and all its children from its parent and unbinds
|
||||
* all listeners and properties set to the data slots.
|
||||
*/
|
||||
public destroy(): void {
|
||||
destroy(): void {
|
||||
|
||||
if (this.currentElement) {
|
||||
|
||||
@@ -1154,15 +1153,15 @@ export class Builder implements IDisposable {
|
||||
|
||||
let type: string;
|
||||
|
||||
for (type in this.toUnbind) {
|
||||
if (this.toUnbind.hasOwnProperty(type) && types.isArray(this.toUnbind[type])) {
|
||||
this.toUnbind[type] = dispose(this.toUnbind[type]);
|
||||
for (type in this.toDispose) {
|
||||
if (this.toDispose.hasOwnProperty(type) && types.isArray(this.toDispose[type])) {
|
||||
this.toDispose[type] = dispose(this.toDispose[type]);
|
||||
}
|
||||
}
|
||||
|
||||
for (type in this.captureToUnbind) {
|
||||
if (this.captureToUnbind.hasOwnProperty(type) && types.isArray(this.captureToUnbind[type])) {
|
||||
this.captureToUnbind[type] = dispose(this.captureToUnbind[type]);
|
||||
for (type in this.captureToDispose) {
|
||||
if (this.captureToDispose.hasOwnProperty(type) && types.isArray(this.captureToDispose[type])) {
|
||||
this.captureToDispose[type] = dispose(this.captureToDispose[type]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1171,22 +1170,22 @@ export class Builder implements IDisposable {
|
||||
this.container = null;
|
||||
this.offdom = null;
|
||||
this.createdElements = null;
|
||||
this.captureToUnbind = null;
|
||||
this.toUnbind = null;
|
||||
this.captureToDispose = null;
|
||||
this.toDispose = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the current HTML element and all its children from its parent and unbinds
|
||||
* all listeners and properties set to the data slots.
|
||||
*/
|
||||
public dispose(): void {
|
||||
dispose(): void {
|
||||
this.destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the size (in pixels) of an element, including the margin.
|
||||
*/
|
||||
public getTotalSize(): DOM.Dimension {
|
||||
getTotalSize(): DOM.Dimension {
|
||||
let totalWidth = DOM.getTotalWidth(this.currentElement);
|
||||
let totalHeight = DOM.getTotalHeight(this.currentElement);
|
||||
|
||||
@@ -1196,7 +1195,7 @@ export class Builder implements IDisposable {
|
||||
/**
|
||||
* Another variant of getting the inner dimensions of an element.
|
||||
*/
|
||||
public getClientArea(): DOM.Dimension {
|
||||
getClientArea(): DOM.Dimension {
|
||||
return DOM.getClientArea(this.currentElement);
|
||||
}
|
||||
}
|
||||
@@ -1207,7 +1206,7 @@ export class Builder implements IDisposable {
|
||||
*/
|
||||
export class MultiBuilder extends Builder {
|
||||
|
||||
public length: number;
|
||||
length: number;
|
||||
|
||||
private builders: Builder[];
|
||||
|
||||
@@ -1288,11 +1287,11 @@ export class MultiBuilder extends Builder {
|
||||
}
|
||||
}
|
||||
|
||||
public item(i: number): Builder {
|
||||
item(i: number): Builder {
|
||||
return this.builders[i];
|
||||
}
|
||||
|
||||
public push(...items: Builder[]): void {
|
||||
push(...items: Builder[]): void {
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
this.builders.push(items[i]);
|
||||
}
|
||||
@@ -1300,7 +1299,7 @@ export class MultiBuilder extends Builder {
|
||||
this.length = this.builders.length;
|
||||
}
|
||||
|
||||
public clone(): MultiBuilder {
|
||||
clone(): MultiBuilder {
|
||||
return new MultiBuilder(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { IAction, IActionRunner, Action } from 'vs/base/common/actions';
|
||||
import { IAction, IActionRunner } from 'vs/base/common/actions';
|
||||
import { IActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
|
||||
import { SubmenuAction } from 'vs/base/browser/ui/menu/menu';
|
||||
|
||||
export interface IEvent {
|
||||
shiftKey?: boolean;
|
||||
@@ -16,9 +17,9 @@ export interface IEvent {
|
||||
metaKey?: boolean;
|
||||
}
|
||||
|
||||
export class ContextSubMenu extends Action {
|
||||
export class ContextSubMenu extends SubmenuAction {
|
||||
constructor(label: string, public entries: (ContextSubMenu | IAction)[]) {
|
||||
super('contextsubmenu', label, '', true);
|
||||
super(label, entries, 'contextsubmenu');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,19 +5,20 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Disposable } from 'vs/base/common/lifecycle';
|
||||
import { addDisposableListener } from 'vs/base/browser/dom';
|
||||
|
||||
/**
|
||||
* A helper that will execute a provided function when the provided HTMLElement receives
|
||||
* dragover event for 800ms. If the drag is aborted before, the callback will not be triggered.
|
||||
*/
|
||||
export class DelayedDragHandler {
|
||||
private toDispose: IDisposable[] = [];
|
||||
export class DelayedDragHandler extends Disposable {
|
||||
private timeout: number;
|
||||
|
||||
constructor(container: HTMLElement, callback: () => void) {
|
||||
this.toDispose.push(addDisposableListener(container, 'dragover', () => {
|
||||
super();
|
||||
|
||||
this._register(addDisposableListener(container, 'dragover', () => {
|
||||
if (!this.timeout) {
|
||||
this.timeout = setTimeout(() => {
|
||||
callback();
|
||||
@@ -28,7 +29,7 @@ export class DelayedDragHandler {
|
||||
}));
|
||||
|
||||
['dragleave', 'drop', 'dragend'].forEach(type => {
|
||||
this.toDispose.push(addDisposableListener(container, type, () => {
|
||||
this._register(addDisposableListener(container, type, () => {
|
||||
this.clearDragTimeout();
|
||||
}));
|
||||
});
|
||||
@@ -41,8 +42,9 @@ export class DelayedDragHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this.toDispose = dispose(this.toDispose);
|
||||
dispose(): void {
|
||||
super.dispose();
|
||||
|
||||
this.clearDragTimeout();
|
||||
}
|
||||
}
|
||||
@@ -70,3 +72,15 @@ export const DataTransfers = {
|
||||
*/
|
||||
TEXT: 'text/plain'
|
||||
};
|
||||
|
||||
export function applyDragImage(event: DragEvent, label: string, clazz: string): void {
|
||||
const dragImage = document.createElement('div');
|
||||
dragImage.className = clazz;
|
||||
dragImage.textContent = label;
|
||||
|
||||
document.body.appendChild(dragImage);
|
||||
event.dataTransfer.setDragImage(dragImage, -10, -10);
|
||||
|
||||
// Removes the element when the DND operation is done
|
||||
setTimeout(() => document.body.removeChild(dragImage), 0);
|
||||
}
|
||||
@@ -539,7 +539,6 @@ const sizeUtils = {
|
||||
getMarginBottom: function (element: HTMLElement): number {
|
||||
return getDimension(element, 'margin-bottom', 'marginBottom');
|
||||
},
|
||||
|
||||
__commaSentinel: false
|
||||
};
|
||||
|
||||
@@ -635,11 +634,11 @@ export function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePositi
|
||||
}
|
||||
|
||||
export interface IStandardWindow {
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
readonly scrollX: number;
|
||||
readonly scrollY: number;
|
||||
}
|
||||
|
||||
export const StandardWindow: IStandardWindow = new class {
|
||||
export const StandardWindow: IStandardWindow = new class implements IStandardWindow {
|
||||
get scrollX(): number {
|
||||
if (typeof window.scrollX === 'number') {
|
||||
// modern browsers
|
||||
@@ -724,14 +723,22 @@ export function isAncestor(testChild: Node, testAncestor: Node): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazz?: string): HTMLElement {
|
||||
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement {
|
||||
while (node) {
|
||||
if (hasClass(node, clazz)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (stopAtClazz && hasClass(node, stopAtClazz)) {
|
||||
return null;
|
||||
if (stopAtClazzOrNode) {
|
||||
if (typeof stopAtClazzOrNode === 'string') {
|
||||
if (hasClass(node, stopAtClazzOrNode)) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
if (node === stopAtClazzOrNode) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
node = <HTMLElement>node.parentNode;
|
||||
@@ -812,6 +819,8 @@ export const EventType = {
|
||||
MOUSE_OVER: 'mouseover',
|
||||
MOUSE_MOVE: 'mousemove',
|
||||
MOUSE_OUT: 'mouseout',
|
||||
MOUSE_ENTER: 'mouseenter',
|
||||
MOUSE_LEAVE: 'mouseleave',
|
||||
CONTEXT_MENU: 'contextmenu',
|
||||
WHEEL: 'wheel',
|
||||
// Keyboard
|
||||
@@ -831,6 +840,8 @@ export const EventType = {
|
||||
SUBMIT: 'submit',
|
||||
RESET: 'reset',
|
||||
FOCUS: 'focus',
|
||||
FOCUS_IN: 'focusin',
|
||||
FOCUS_OUT: 'focusout',
|
||||
BLUR: 'blur',
|
||||
INPUT: 'input',
|
||||
// Local Storage
|
||||
@@ -979,7 +990,7 @@ export function $<T extends HTMLElement>(description: string, attrs?: { [key: st
|
||||
|
||||
Object.keys(attrs || {}).forEach(name => {
|
||||
if (/^on\w+$/.test(name)) {
|
||||
result[name] = attrs[name];
|
||||
(<any>result)[name] = attrs[name];
|
||||
} else if (name === 'selected') {
|
||||
const value = attrs[name];
|
||||
if (value) {
|
||||
|
||||
@@ -2,113 +2,14 @@
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { Event as _Event, Emitter, mapEvent } from 'vs/base/common/event';
|
||||
import { Event, Emitter, mapEvent } from 'vs/base/common/event';
|
||||
|
||||
export type EventHandler = HTMLElement | HTMLDocument | Window;
|
||||
|
||||
export interface IDomEvent {
|
||||
(element: EventHandler, type: 'MSContentZoom', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'MSGestureChange', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSGestureDoubleTap', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSGestureEnd', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSGestureHold', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSGestureStart', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSGestureTap', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSGotPointerCapture', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSInertiaStart', useCapture?: boolean): _Event<MSGestureEvent>;
|
||||
(element: EventHandler, type: 'MSLostPointerCapture', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerCancel', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerDown', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerEnter', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerLeave', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerMove', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerOut', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerOver', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'MSPointerUp', useCapture?: boolean): _Event<MSPointerEvent>;
|
||||
(element: EventHandler, type: 'abort', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'activate', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'beforeactivate', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'beforecopy', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'beforecut', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'beforedeactivate', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'beforepaste', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'blur', useCapture?: boolean): _Event<FocusEvent>;
|
||||
(element: EventHandler, type: 'canplay', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'canplaythrough', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'change', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'click', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'contextmenu', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'copy', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'cuechange', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'cut', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'dblclick', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'deactivate', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'drag', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'dragend', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'dragenter', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'dragleave', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'dragover', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'dragstart', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'drop', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'durationchange', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'emptied', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'ended', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'error', useCapture?: boolean): _Event<ErrorEvent>;
|
||||
(element: EventHandler, type: 'focus', useCapture?: boolean): _Event<FocusEvent>;
|
||||
(element: EventHandler, type: 'gotpointercapture', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'input', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'keydown', useCapture?: boolean): _Event<KeyboardEvent>;
|
||||
(element: EventHandler, type: 'keypress', useCapture?: boolean): _Event<KeyboardEvent>;
|
||||
(element: EventHandler, type: 'keyup', useCapture?: boolean): _Event<KeyboardEvent>;
|
||||
(element: EventHandler, type: 'load', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'loadeddata', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'loadedmetadata', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'loadstart', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'lostpointercapture', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'mousedown', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mouseenter', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mouseleave', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mousemove', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mouseout', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mouseover', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mouseup', useCapture?: boolean): _Event<MouseEvent>;
|
||||
(element: EventHandler, type: 'mousewheel', useCapture?: boolean): _Event<MouseWheelEvent>;
|
||||
(element: EventHandler, type: 'paste', useCapture?: boolean): _Event<DragEvent>;
|
||||
(element: EventHandler, type: 'pause', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'play', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'playing', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'pointercancel', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointerdown', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointerenter', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointerleave', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointermove', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointerout', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointerover', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'pointerup', useCapture?: boolean): _Event<PointerEvent>;
|
||||
(element: EventHandler, type: 'progress', useCapture?: boolean): _Event<ProgressEvent>;
|
||||
(element: EventHandler, type: 'ratechange', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'reset', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'scroll', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'seeked', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'seeking', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'select', useCapture?: boolean): _Event<UIEvent>;
|
||||
(element: EventHandler, type: 'selectstart', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'stalled', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'submit', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'suspend', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'timeupdate', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'touchcancel', useCapture?: boolean): _Event<TouchEvent>;
|
||||
(element: EventHandler, type: 'touchend', useCapture?: boolean): _Event<TouchEvent>;
|
||||
(element: EventHandler, type: 'touchmove', useCapture?: boolean): _Event<TouchEvent>;
|
||||
(element: EventHandler, type: 'touchstart', useCapture?: boolean): _Event<TouchEvent>;
|
||||
(element: EventHandler, type: 'volumechange', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'waiting', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'webkitfullscreenchange', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'webkitfullscreenerror', useCapture?: boolean): _Event<Event>;
|
||||
(element: EventHandler, type: 'wheel', useCapture?: boolean): _Event<WheelEvent>;
|
||||
(element: EventHandler, type: string, useCapture?: boolean): _Event<any>;
|
||||
<K extends keyof HTMLElementEventMap>(element: EventHandler, type: K, useCapture?: boolean): Event<HTMLElementEventMap[K]>;
|
||||
(element: EventHandler, type: string, useCapture?: boolean): Event<any>;
|
||||
}
|
||||
|
||||
export const domEvent: IDomEvent = (element: EventHandler, type: string, useCapture?: boolean) => {
|
||||
@@ -130,7 +31,7 @@ export interface CancellableEvent {
|
||||
stopPropagation();
|
||||
}
|
||||
|
||||
export function stop<T extends CancellableEvent>(event: _Event<T>): _Event<T> {
|
||||
export function stop<T extends CancellableEvent>(event: Event<T>): Event<T> {
|
||||
return mapEvent(event, e => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
12
src/vs/base/browser/history.ts
Normal file
12
src/vs/base/browser/history.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
export interface IHistoryNavigationWidget {
|
||||
|
||||
showPreviousValue();
|
||||
|
||||
showNextValue();
|
||||
|
||||
}
|
||||
@@ -53,8 +53,8 @@
|
||||
}
|
||||
|
||||
.monaco-action-bar .action-label {
|
||||
font-size: 12px;
|
||||
margin-right: 0.3em;
|
||||
font-size: 11px;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.monaco-action-bar .action-label.octicon {
|
||||
@@ -104,5 +104,7 @@
|
||||
flex: 1;
|
||||
max-width: 170px;
|
||||
min-width: 60px;
|
||||
margin-right: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import * as nls from 'vs/nls';
|
||||
import * as lifecycle from 'vs/base/common/lifecycle';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { Builder, $ } from 'vs/base/browser/builder';
|
||||
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
|
||||
import { SelectBox, ISelectBoxOptions } from 'vs/base/browser/ui/selectBox/selectBox';
|
||||
import { IAction, IActionRunner, Action, IActionChangeEvent, ActionRunner, IRunEvent } from 'vs/base/common/actions';
|
||||
import * as DOM from 'vs/base/browser/dom';
|
||||
import * as types from 'vs/base/common/types';
|
||||
@@ -154,7 +154,7 @@ export class BaseActionItem implements IActionItem {
|
||||
DOM.EventHelper.stop(event, true);
|
||||
|
||||
let context: any;
|
||||
if (types.isUndefinedOrNull(this._context)) {
|
||||
if (types.isUndefinedOrNull(this._context) || !types.isObject(this._context)) {
|
||||
context = event;
|
||||
} else {
|
||||
context = this._context;
|
||||
@@ -167,12 +167,14 @@ export class BaseActionItem implements IActionItem {
|
||||
public focus(): void {
|
||||
if (this.builder) {
|
||||
this.builder.domFocus();
|
||||
this.builder.addClass('focused');
|
||||
}
|
||||
}
|
||||
|
||||
public blur(): void {
|
||||
if (this.builder) {
|
||||
this.builder.domBlur();
|
||||
this.builder.removeClass('focused');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,7 +374,6 @@ export class ActionBar implements IActionRunner {
|
||||
|
||||
// Items
|
||||
public items: IActionItem[];
|
||||
|
||||
private focusedItem: number;
|
||||
private focusTracker: DOM.IFocusTracker;
|
||||
|
||||
@@ -487,7 +488,7 @@ export class ActionBar implements IActionRunner {
|
||||
this.actionsList = document.createElement('ul');
|
||||
this.actionsList.className = 'actions-container';
|
||||
if (this.options.isMenu) {
|
||||
this.actionsList.setAttribute('role', 'menubar');
|
||||
this.actionsList.setAttribute('role', 'menu');
|
||||
} else {
|
||||
this.actionsList.setAttribute('role', 'toolbar');
|
||||
}
|
||||
@@ -495,6 +496,39 @@ export class ActionBar implements IActionRunner {
|
||||
this.actionsList.setAttribute('aria-label', this.options.ariaLabel);
|
||||
}
|
||||
|
||||
if (this.options.isMenu) {
|
||||
this.domNode.tabIndex = 0;
|
||||
|
||||
$(this.domNode).on(DOM.EventType.MOUSE_OUT, (e) => {
|
||||
let relatedTarget = (e as MouseEvent).relatedTarget as HTMLElement;
|
||||
if (!DOM.isAncestor(relatedTarget, this.domNode)) {
|
||||
this.focusedItem = undefined;
|
||||
this.updateFocus();
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
|
||||
$(this.actionsList).on(DOM.EventType.MOUSE_OVER, (e) => {
|
||||
let target = e.target as HTMLElement;
|
||||
if (!target || !DOM.isAncestor(target, this.actionsList) || target === this.actionsList) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (target.parentElement !== this.actionsList) {
|
||||
target = target.parentElement;
|
||||
}
|
||||
|
||||
if (DOM.hasClass(target, 'action-item')) {
|
||||
const lastFocusedItem = this.focusedItem;
|
||||
this.setFocusedItem(target);
|
||||
|
||||
if (lastFocusedItem !== this.focusedItem) {
|
||||
this.updateFocus();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
this.domNode.appendChild(this.actionsList);
|
||||
|
||||
container.appendChild(this.domNode);
|
||||
@@ -524,6 +558,16 @@ export class ActionBar implements IActionRunner {
|
||||
}
|
||||
}
|
||||
|
||||
private setFocusedItem(element: HTMLElement): void {
|
||||
for (let i = 0; i < this.actionsList.children.length; i++) {
|
||||
let elem = this.actionsList.children[i];
|
||||
if (element === elem) {
|
||||
this.focusedItem = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private updateFocusedItem(): void {
|
||||
for (let i = 0; i < this.actionsList.children.length; i++) {
|
||||
let elem = this.actionsList.children[i];
|
||||
@@ -591,11 +635,13 @@ export class ActionBar implements IActionRunner {
|
||||
|
||||
if (index === null || index < 0 || index >= this.actionsList.children.length) {
|
||||
this.actionsList.appendChild(actionItemElement);
|
||||
this.items.push(item);
|
||||
} else {
|
||||
this.actionsList.insertBefore(actionItemElement, this.actionsList.children[index++]);
|
||||
this.actionsList.insertBefore(actionItemElement, this.actionsList.children[index]);
|
||||
this.items.splice(index, 0, item);
|
||||
index++;
|
||||
}
|
||||
|
||||
this.items.push(item);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -637,10 +683,12 @@ export class ActionBar implements IActionRunner {
|
||||
|
||||
public focus(selectFirst?: boolean): void {
|
||||
if (selectFirst && typeof this.focusedItem === 'undefined') {
|
||||
this.focusedItem = 0;
|
||||
// Focus the first enabled item
|
||||
this.focusedItem = this.items.length - 1;
|
||||
this.focusNext();
|
||||
} else {
|
||||
this.updateFocus();
|
||||
}
|
||||
|
||||
this.updateFocus();
|
||||
}
|
||||
|
||||
private focusNext(): void {
|
||||
@@ -691,7 +739,6 @@ export class ActionBar implements IActionRunner {
|
||||
private updateFocus(fromRight?: boolean): void {
|
||||
if (typeof this.focusedItem === 'undefined') {
|
||||
this.domNode.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < this.items.length; i++) {
|
||||
@@ -700,8 +747,12 @@ export class ActionBar implements IActionRunner {
|
||||
let actionItem = <any>item;
|
||||
|
||||
if (i === this.focusedItem) {
|
||||
if (types.isFunction(actionItem.focus)) {
|
||||
actionItem.focus(fromRight);
|
||||
if (types.isFunction(actionItem.isEnabled)) {
|
||||
if (actionItem.isEnabled() && types.isFunction(actionItem.focus)) {
|
||||
actionItem.focus(fromRight);
|
||||
} else {
|
||||
this.domNode.focus();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (types.isFunction(actionItem.blur)) {
|
||||
@@ -757,10 +808,10 @@ export class SelectActionItem extends BaseActionItem {
|
||||
protected selectBox: SelectBox;
|
||||
protected toDispose: lifecycle.IDisposable[];
|
||||
|
||||
constructor(ctx: any, action: IAction, options: string[], selected: number, contextViewProvider: IContextViewProvider
|
||||
constructor(ctx: any, action: IAction, options: string[], selected: number, contextViewProvider: IContextViewProvider, selectBoxOptions?: ISelectBoxOptions
|
||||
) {
|
||||
super(ctx, action);
|
||||
this.selectBox = new SelectBox(options, selected, contextViewProvider);
|
||||
this.selectBox = new SelectBox(options, selected, contextViewProvider, null, selectBoxOptions);
|
||||
|
||||
this.toDispose = [];
|
||||
this.toDispose.push(this.selectBox);
|
||||
@@ -806,4 +857,4 @@ export class SelectActionItem extends BaseActionItem {
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,13 +50,27 @@ export function status(msg: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
let repeatedTimes = 0;
|
||||
let prevText: string | undefined = undefined;
|
||||
function insertMessage(target: HTMLElement, msg: string): void {
|
||||
if (!ariaContainer) {
|
||||
// console.warn('ARIA support needs a container. Call setARIAContainer() first.');
|
||||
return;
|
||||
}
|
||||
if (target.textContent === msg) {
|
||||
msg = nls.localize('repeated', "{0} (occurred again)", msg);
|
||||
|
||||
if (prevText === msg) {
|
||||
repeatedTimes++;
|
||||
}
|
||||
else {
|
||||
prevText = msg;
|
||||
repeatedTimes = 0;
|
||||
}
|
||||
|
||||
|
||||
switch (repeatedTimes) {
|
||||
case 0: break;
|
||||
case 1: msg = nls.localize('repeated', "{0} (occurred again)", msg); break;
|
||||
default: msg = nls.localize('repeatedNtimes', "{0} (occurred {1} times)", msg, repeatedTimes); break;
|
||||
}
|
||||
|
||||
dom.clearNode(target);
|
||||
|
||||
40
src/vs/base/browser/ui/breadcrumbs/breadcrumbsWidget.css
Normal file
40
src/vs/base/browser/ui/breadcrumbs/breadcrumbsWidget.css
Normal file
@@ -0,0 +1,40 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
.monaco-breadcrumbs {
|
||||
user-select: none;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: nowrap;
|
||||
justify-content: flex-start;
|
||||
outline-style: none;
|
||||
}
|
||||
|
||||
.monaco-breadcrumbs .monaco-breadcrumb-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 0 1 auto;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
align-self: center;
|
||||
height: 100%;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.monaco-breadcrumbs .monaco-breadcrumb-item:not(:first-child)::before {
|
||||
background-image: url(./collapsed.svg);
|
||||
opacity: .7;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: inline-block;
|
||||
background-size: 16px;
|
||||
background-position: 50% 50%;
|
||||
content: ' ';
|
||||
}
|
||||
|
||||
.vs-dark .monaco-breadcrumbs .monaco-breadcrumb-item:not(:first-child)::before {
|
||||
background-image: url(./collpased-dark.svg);
|
||||
}
|
||||
|
||||
304
src/vs/base/browser/ui/breadcrumbs/breadcrumbsWidget.ts
Normal file
304
src/vs/base/browser/ui/breadcrumbs/breadcrumbsWidget.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./breadcrumbsWidget';
|
||||
import * as dom from 'vs/base/browser/dom';
|
||||
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
|
||||
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
|
||||
import { Event, Emitter } from 'vs/base/common/event';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { commonPrefixLength } from 'vs/base/common/arrays';
|
||||
|
||||
export abstract class BreadcrumbsItem {
|
||||
dispose(): void { }
|
||||
abstract equals(other: BreadcrumbsItem): boolean;
|
||||
abstract render(container: HTMLElement): void;
|
||||
}
|
||||
|
||||
export class SimpleBreadcrumbsItem extends BreadcrumbsItem {
|
||||
|
||||
constructor(
|
||||
readonly text: string,
|
||||
readonly title: string = text
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
equals(other: this) {
|
||||
return other === this || other instanceof SimpleBreadcrumbsItem && other.text === this.text && other.title === this.title;
|
||||
}
|
||||
|
||||
render(container: HTMLElement): void {
|
||||
let node = document.createElement('div');
|
||||
node.title = this.title;
|
||||
node.innerText = this.text;
|
||||
container.appendChild(node);
|
||||
}
|
||||
}
|
||||
|
||||
export interface IBreadcrumbsWidgetStyles {
|
||||
breadcrumbsBackground?: Color;
|
||||
breadcrumbsForeground?: Color;
|
||||
breadcrumbsHoverBackground?: Color;
|
||||
breadcrumbsHoverForeground?: Color;
|
||||
breadcrumbsFocusForeground?: Color;
|
||||
breadcrumbsFocusAndSelectionBackground?: Color;
|
||||
breadcrumbsFocusAndSelectionForeground?: Color;
|
||||
}
|
||||
|
||||
export interface IBreadcrumbsItemEvent {
|
||||
type: 'select' | 'focus';
|
||||
item: BreadcrumbsItem;
|
||||
node: HTMLElement;
|
||||
payload: any;
|
||||
}
|
||||
|
||||
export class BreadcrumbsWidget {
|
||||
|
||||
private readonly _disposables = new Array<IDisposable>();
|
||||
private readonly _domNode: HTMLDivElement;
|
||||
private readonly _styleElement: HTMLStyleElement;
|
||||
private readonly _scrollable: DomScrollableElement;
|
||||
|
||||
private readonly _onDidSelectItem = new Emitter<IBreadcrumbsItemEvent>();
|
||||
private readonly _onDidFocusItem = new Emitter<IBreadcrumbsItemEvent>();
|
||||
private readonly _onDidChangeFocus = new Emitter<boolean>();
|
||||
|
||||
readonly onDidSelectItem: Event<IBreadcrumbsItemEvent> = this._onDidSelectItem.event;
|
||||
readonly onDidFocusItem: Event<IBreadcrumbsItemEvent> = this._onDidFocusItem.event;
|
||||
readonly onDidChangeFocus: Event<boolean> = this._onDidChangeFocus.event;
|
||||
|
||||
private readonly _items = new Array<BreadcrumbsItem>();
|
||||
private readonly _nodes = new Array<HTMLDivElement>();
|
||||
private readonly _freeNodes = new Array<HTMLDivElement>();
|
||||
|
||||
private _focusedItemIdx: number = -1;
|
||||
private _selectedItemIdx: number = -1;
|
||||
|
||||
constructor(
|
||||
container: HTMLElement
|
||||
) {
|
||||
this._domNode = document.createElement('div');
|
||||
this._domNode.className = 'monaco-breadcrumbs';
|
||||
this._domNode.tabIndex = 0;
|
||||
this._domNode.setAttribute('role', 'list');
|
||||
this._scrollable = new DomScrollableElement(this._domNode, {
|
||||
vertical: ScrollbarVisibility.Hidden,
|
||||
horizontal: ScrollbarVisibility.Auto,
|
||||
horizontalScrollbarSize: 3,
|
||||
useShadows: false
|
||||
});
|
||||
this._disposables.push(this._scrollable);
|
||||
this._disposables.push(dom.addStandardDisposableListener(this._domNode, 'click', e => this._onClick(e)));
|
||||
container.appendChild(this._scrollable.getDomNode());
|
||||
|
||||
this._styleElement = dom.createStyleSheet(this._domNode);
|
||||
|
||||
let focusTracker = dom.trackFocus(this._domNode);
|
||||
this._disposables.push(focusTracker);
|
||||
this._disposables.push(focusTracker.onDidBlur(_ => this._onDidChangeFocus.fire(false)));
|
||||
this._disposables.push(focusTracker.onDidFocus(_ => this._onDidChangeFocus.fire(true)));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
dispose(this._disposables);
|
||||
this._domNode.remove();
|
||||
this._disposables.length = 0;
|
||||
this._nodes.length = 0;
|
||||
this._freeNodes.length = 0;
|
||||
}
|
||||
|
||||
layout(dim: dom.Dimension): void {
|
||||
if (dim) {
|
||||
this._domNode.style.width = `${dim.width}px`;
|
||||
this._domNode.style.height = `${dim.height}px`;
|
||||
}
|
||||
this._scrollable.setRevealOnScroll(false);
|
||||
this._scrollable.scanDomNode();
|
||||
this._scrollable.setRevealOnScroll(true);
|
||||
}
|
||||
|
||||
style(style: IBreadcrumbsWidgetStyles): void {
|
||||
let content = '';
|
||||
if (style.breadcrumbsBackground) {
|
||||
content += `.monaco-breadcrumbs { background-color: ${style.breadcrumbsBackground}}`;
|
||||
}
|
||||
if (style.breadcrumbsForeground) {
|
||||
content += `.monaco-breadcrumbs .monaco-breadcrumb-item { color: ${style.breadcrumbsForeground}}\n`;
|
||||
}
|
||||
if (style.breadcrumbsFocusForeground) {
|
||||
content += `.monaco-breadcrumbs .monaco-breadcrumb-item.focused { color: ${style.breadcrumbsFocusForeground}}\n`;
|
||||
}
|
||||
if (style.breadcrumbsFocusAndSelectionBackground) {
|
||||
content += `.monaco-breadcrumbs .monaco-breadcrumb-item.focused.selected { background-color: ${style.breadcrumbsFocusAndSelectionBackground}}\n`;
|
||||
}
|
||||
if (style.breadcrumbsFocusAndSelectionForeground) {
|
||||
content += `.monaco-breadcrumbs .monaco-breadcrumb-item.focused.selected { color: ${style.breadcrumbsFocusAndSelectionForeground}}\n`;
|
||||
}
|
||||
if (style.breadcrumbsHoverBackground) {
|
||||
content += `.monaco-breadcrumbs .monaco-breadcrumb-item:hover:not(.focused):not(.selected) { background-color: ${style.breadcrumbsHoverBackground}}\n`;
|
||||
}
|
||||
if (style.breadcrumbsHoverForeground) {
|
||||
content += `.monaco-breadcrumbs .monaco-breadcrumb-item:hover:not(.focused):not(.selected) { color: ${style.breadcrumbsHoverForeground}}\n`;
|
||||
}
|
||||
if (this._styleElement.innerHTML !== content) {
|
||||
this._styleElement.innerHTML = content;
|
||||
}
|
||||
}
|
||||
|
||||
domFocus(): void {
|
||||
let idx = this._focusedItemIdx >= 0 ? this._focusedItemIdx : this._items.length - 1;
|
||||
if (idx >= 0 && idx < this._items.length) {
|
||||
this._focus(idx, undefined);
|
||||
} else {
|
||||
this._domNode.focus();
|
||||
}
|
||||
}
|
||||
|
||||
isDOMFocused(): boolean {
|
||||
let candidate = document.activeElement;
|
||||
while (candidate) {
|
||||
if (this._domNode === candidate) {
|
||||
return true;
|
||||
}
|
||||
candidate = candidate.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
getFocused(): BreadcrumbsItem {
|
||||
return this._items[this._focusedItemIdx];
|
||||
}
|
||||
|
||||
setFocused(item: BreadcrumbsItem, payload?: any): void {
|
||||
this._focus(this._items.indexOf(item), payload);
|
||||
}
|
||||
|
||||
focusPrev(payload?: any): any {
|
||||
if (this._focusedItemIdx > 0) {
|
||||
this._focus(this._focusedItemIdx - 1, payload);
|
||||
}
|
||||
}
|
||||
|
||||
focusNext(payload?: any): any {
|
||||
if (this._focusedItemIdx + 1 < this._nodes.length) {
|
||||
this._focus(this._focusedItemIdx + 1, payload);
|
||||
}
|
||||
}
|
||||
|
||||
private _focus(nth: number, payload: any): void {
|
||||
this._focusedItemIdx = -1;
|
||||
for (let i = 0; i < this._nodes.length; i++) {
|
||||
const node = this._nodes[i];
|
||||
if (i !== nth) {
|
||||
dom.removeClass(node, 'focused');
|
||||
} else {
|
||||
this._focusedItemIdx = i;
|
||||
dom.addClass(node, 'focused');
|
||||
node.focus();
|
||||
}
|
||||
}
|
||||
this._reveal(this._focusedItemIdx);
|
||||
this._onDidFocusItem.fire({ type: 'focus', item: this._items[this._focusedItemIdx], node: this._nodes[this._focusedItemIdx], payload });
|
||||
}
|
||||
|
||||
reveal(item: BreadcrumbsItem): void {
|
||||
let idx = this._items.indexOf(item);
|
||||
if (idx >= 0) {
|
||||
this._reveal(idx);
|
||||
}
|
||||
}
|
||||
|
||||
private _reveal(nth: number): void {
|
||||
const node = this._nodes[nth];
|
||||
if (node) {
|
||||
this._scrollable.setRevealOnScroll(false);
|
||||
this._scrollable.setScrollPosition({ scrollLeft: node.offsetLeft });
|
||||
this._scrollable.setRevealOnScroll(true);
|
||||
}
|
||||
}
|
||||
|
||||
getSelection(): BreadcrumbsItem {
|
||||
return this._items[this._selectedItemIdx];
|
||||
}
|
||||
|
||||
setSelection(item: BreadcrumbsItem, payload?: any): void {
|
||||
this._select(this._items.indexOf(item), payload);
|
||||
}
|
||||
|
||||
private _select(nth: number, payload: any): void {
|
||||
this._selectedItemIdx = -1;
|
||||
for (let i = 0; i < this._nodes.length; i++) {
|
||||
const node = this._nodes[i];
|
||||
if (i !== nth) {
|
||||
dom.removeClass(node, 'selected');
|
||||
} else {
|
||||
this._selectedItemIdx = i;
|
||||
dom.addClass(node, 'selected');
|
||||
}
|
||||
}
|
||||
this._onDidSelectItem.fire({ type: 'select', item: this._items[this._selectedItemIdx], node: this._nodes[this._selectedItemIdx], payload });
|
||||
}
|
||||
|
||||
getItems(): ReadonlyArray<BreadcrumbsItem> {
|
||||
return this._items;
|
||||
}
|
||||
|
||||
setItems(items: BreadcrumbsItem[]): void {
|
||||
let prefix = commonPrefixLength(this._items, items, (a, b) => a.equals(b));
|
||||
let removed = this._items.splice(prefix, this._items.length - prefix, ...items.slice(prefix));
|
||||
this._render(prefix);
|
||||
dispose(removed);
|
||||
this._focus(-1, undefined);
|
||||
}
|
||||
|
||||
private _render(start: number): void {
|
||||
for (; start < this._items.length && start < this._nodes.length; start++) {
|
||||
let item = this._items[start];
|
||||
let node = this._nodes[start];
|
||||
this._renderItem(item, node);
|
||||
}
|
||||
// case a: more nodes -> remove them
|
||||
for (; start < this._nodes.length; start++) {
|
||||
this._nodes[start].remove();
|
||||
this._freeNodes.push(this._nodes[start]);
|
||||
}
|
||||
this._nodes.length = this._items.length;
|
||||
|
||||
// case b: more items -> render them
|
||||
for (; start < this._items.length; start++) {
|
||||
let item = this._items[start];
|
||||
let node = this._freeNodes.length > 0 ? this._freeNodes.pop() : document.createElement('div');
|
||||
this._renderItem(item, node);
|
||||
this._domNode.appendChild(node);
|
||||
this._nodes[start] = node;
|
||||
}
|
||||
this.layout(undefined);
|
||||
}
|
||||
|
||||
private _renderItem(item: BreadcrumbsItem, container: HTMLDivElement): void {
|
||||
dom.clearNode(container);
|
||||
container.className = '';
|
||||
item.render(container);
|
||||
container.tabIndex = -1;
|
||||
container.setAttribute('role', 'listitem');
|
||||
dom.addClass(container, 'monaco-breadcrumb-item');
|
||||
}
|
||||
|
||||
private _onClick(event: IMouseEvent): void {
|
||||
for (let el = event.target; el; el = el.parentElement) {
|
||||
let idx = this._nodes.indexOf(el as any);
|
||||
if (idx >= 0) {
|
||||
this._focus(idx, event);
|
||||
this._select(idx, event);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1
src/vs/base/browser/ui/breadcrumbs/collapsed.svg
Executable file
1
src/vs/base/browser/ui/breadcrumbs/collapsed.svg
Executable file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#646465" d="M6 4v8l4-4-4-4zm1 2.414L8.586 8 7 9.586V6.414z"/></svg>
|
||||
|
After Width: | Height: | Size: 139 B |
1
src/vs/base/browser/ui/breadcrumbs/collpased-dark.svg
Executable file
1
src/vs/base/browser/ui/breadcrumbs/collpased-dark.svg
Executable file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#E8E8E8" d="M6 4v8l4-4-4-4zm1 2.414L8.586 8 7 9.586V6.414z"/></svg>
|
||||
|
After Width: | Height: | Size: 139 B |
@@ -13,7 +13,7 @@ import { KeyCode } from 'vs/base/common/keyCodes';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { mixin } from 'vs/base/common/objects';
|
||||
import { Event as BaseEvent, Emitter } from 'vs/base/common/event';
|
||||
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { Disposable } from 'vs/base/common/lifecycle';
|
||||
import { Gesture, EventType } from 'vs/base/browser/touch';
|
||||
|
||||
export interface IButtonOptions extends IButtonStyles {
|
||||
@@ -33,7 +33,7 @@ const defaultOptions: IButtonStyles = {
|
||||
buttonForeground: Color.white
|
||||
};
|
||||
|
||||
export class Button {
|
||||
export class Button extends Disposable {
|
||||
|
||||
// {{SQL CARBON EDIT}} -- changed access modifier to protected
|
||||
protected $el: Builder;
|
||||
@@ -44,12 +44,14 @@ export class Button {
|
||||
private buttonForeground: Color;
|
||||
private buttonBorder: Color;
|
||||
|
||||
private _onDidClick = new Emitter<any>();
|
||||
readonly onDidClick: BaseEvent<Event> = this._onDidClick.event;
|
||||
private _onDidClick = this._register(new Emitter<any>());
|
||||
get onDidClick(): BaseEvent<Event> { return this._onDidClick.event; }
|
||||
|
||||
private focusTracker: DOM.IFocusTracker;
|
||||
|
||||
constructor(container: HTMLElement, options?: IButtonOptions) {
|
||||
super();
|
||||
|
||||
this.options = options || Object.create(null);
|
||||
mixin(this.options, defaultOptions, false);
|
||||
|
||||
@@ -58,10 +60,10 @@ export class Button {
|
||||
this.buttonForeground = this.options.buttonForeground;
|
||||
this.buttonBorder = this.options.buttonBorder;
|
||||
|
||||
this.$el = $('a.monaco-button').attr({
|
||||
this.$el = this._register($('a.monaco-button').attr({
|
||||
'tabIndex': '0',
|
||||
'role': 'button'
|
||||
}).appendTo(container);
|
||||
}).appendTo(container));
|
||||
|
||||
Gesture.addTarget(this.$el.getHTMLElement());
|
||||
|
||||
@@ -75,7 +77,7 @@ export class Button {
|
||||
});
|
||||
|
||||
this.$el.on(DOM.EventType.KEY_DOWN, e => {
|
||||
let event = new StandardKeyboardEvent(e as KeyboardEvent);
|
||||
const event = new StandardKeyboardEvent(e as KeyboardEvent);
|
||||
let eventHandled = false;
|
||||
if (this.enabled && event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
|
||||
this._onDidClick.fire(e);
|
||||
@@ -101,9 +103,9 @@ export class Button {
|
||||
});
|
||||
|
||||
// Also set hover background when button is focused for feedback
|
||||
this.focusTracker = DOM.trackFocus(this.$el.getHTMLElement());
|
||||
this.focusTracker.onDidFocus(() => this.setHoverBackground());
|
||||
this.focusTracker.onDidBlur(() => this.applyStyles()); // restore standard styles
|
||||
this.focusTracker = this._register(DOM.trackFocus(this.$el.getHTMLElement()));
|
||||
this._register(this.focusTracker.onDidFocus(() => this.setHoverBackground()));
|
||||
this._register(this.focusTracker.onDidBlur(() => this.applyStyles())); // restore standard styles
|
||||
|
||||
this.applyStyles();
|
||||
}
|
||||
@@ -179,27 +181,13 @@ export class Button {
|
||||
focus(): void {
|
||||
this.$el.domFocus();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.$el) {
|
||||
this.$el.dispose();
|
||||
this.$el = null;
|
||||
|
||||
this.focusTracker.dispose();
|
||||
this.focusTracker = null;
|
||||
}
|
||||
|
||||
this._onDidClick.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export class ButtonGroup {
|
||||
private _buttons: Button[];
|
||||
private toDispose: IDisposable[];
|
||||
export class ButtonGroup extends Disposable {
|
||||
private _buttons: Button[] = [];
|
||||
|
||||
constructor(container: HTMLElement, count: number, options?: IButtonOptions) {
|
||||
this._buttons = [];
|
||||
this.toDispose = [];
|
||||
super();
|
||||
|
||||
this.create(container, count, options);
|
||||
}
|
||||
@@ -210,9 +198,8 @@ export class ButtonGroup {
|
||||
|
||||
private create(container: HTMLElement, count: number, options?: IButtonOptions): void {
|
||||
for (let index = 0; index < count; index++) {
|
||||
const button = new Button(container, options);
|
||||
const button = this._register(new Button(container, options));
|
||||
this._buttons.push(button);
|
||||
this.toDispose.push(button);
|
||||
|
||||
// Implement keyboard access in buttons if there are multiple
|
||||
if (count > 1) {
|
||||
@@ -238,8 +225,4 @@ export class ButtonGroup {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.toDispose = dispose(this.toDispose);
|
||||
}
|
||||
}
|
||||
150
src/vs/base/browser/ui/centered/centeredViewLayout.ts
Normal file
150
src/vs/base/browser/ui/centered/centeredViewLayout.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { SplitView, Orientation, ISplitViewStyles, IView as ISplitViewView } from 'vs/base/browser/ui/splitview/splitview';
|
||||
import { $ } from 'vs/base/browser/dom';
|
||||
import { Event, mapEvent } from 'vs/base/common/event';
|
||||
import { IView } from 'vs/base/browser/ui/grid/gridview';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
|
||||
export interface CenteredViewState {
|
||||
leftMarginRatio: number;
|
||||
rightMarginRatio: number;
|
||||
}
|
||||
|
||||
const GOLDEN_RATIO = {
|
||||
leftMarginRatio: 0.1909,
|
||||
rightMarginRatio: 0.1909
|
||||
};
|
||||
|
||||
function createEmptyView(background: Color): ISplitViewView {
|
||||
const element = $('.centered-layout-margin');
|
||||
element.style.height = '100%';
|
||||
element.style.backgroundColor = background.toString();
|
||||
|
||||
return {
|
||||
element,
|
||||
layout: () => undefined,
|
||||
minimumSize: 60,
|
||||
maximumSize: Number.POSITIVE_INFINITY,
|
||||
onDidChange: Event.None
|
||||
};
|
||||
}
|
||||
|
||||
function toSplitViewView(view: IView, getHeight: () => number): ISplitViewView {
|
||||
return {
|
||||
element: view.element,
|
||||
get maximumSize() { return view.maximumWidth; },
|
||||
get minimumSize() { return view.minimumWidth; },
|
||||
onDidChange: mapEvent(view.onDidChange, e => e && e.width),
|
||||
layout: size => view.layout(size, getHeight())
|
||||
};
|
||||
}
|
||||
|
||||
export interface ICenteredViewStyles extends ISplitViewStyles {
|
||||
background: Color;
|
||||
}
|
||||
|
||||
export class CenteredViewLayout {
|
||||
|
||||
private splitView: SplitView;
|
||||
private width: number = 0;
|
||||
private height: number = 0;
|
||||
private style: ICenteredViewStyles;
|
||||
private didLayout = false;
|
||||
private emptyViews: ISplitViewView[];
|
||||
private splitViewDisposables: IDisposable[] = [];
|
||||
|
||||
constructor(private container: HTMLElement, private view: IView, public readonly state: CenteredViewState = GOLDEN_RATIO) {
|
||||
this.container.appendChild(this.view.element);
|
||||
// Make sure to hide the split view overflow like sashes #52892
|
||||
this.container.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
get minimumWidth(): number { return this.splitView ? this.splitView.minimumSize : this.view.minimumWidth; }
|
||||
get maximumWidth(): number { return this.splitView ? this.splitView.maximumSize : this.view.maximumWidth; }
|
||||
get minimumHeight(): number { return this.view.minimumHeight; }
|
||||
get maximumHeight(): number { return this.view.maximumHeight; }
|
||||
|
||||
layout(width: number, height: number): void {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
if (this.splitView) {
|
||||
this.splitView.layout(width);
|
||||
if (!this.didLayout) {
|
||||
this.resizeMargins();
|
||||
}
|
||||
} else {
|
||||
this.view.layout(width, height);
|
||||
}
|
||||
this.didLayout = true;
|
||||
}
|
||||
|
||||
private resizeMargins(): void {
|
||||
this.splitView.resizeView(0, this.state.leftMarginRatio * this.width);
|
||||
this.splitView.resizeView(2, this.state.rightMarginRatio * this.width);
|
||||
}
|
||||
|
||||
isActive(): boolean {
|
||||
return !!this.splitView;
|
||||
}
|
||||
|
||||
styles(style: ICenteredViewStyles): void {
|
||||
this.style = style;
|
||||
if (this.splitView) {
|
||||
this.splitView.style(this.style);
|
||||
this.emptyViews[0].element.style.backgroundColor = this.style.background.toString();
|
||||
this.emptyViews[1].element.style.backgroundColor = this.style.background.toString();
|
||||
}
|
||||
}
|
||||
|
||||
activate(active: boolean): void {
|
||||
if (active === this.isActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (active) {
|
||||
this.container.removeChild(this.view.element);
|
||||
this.splitView = new SplitView(this.container, {
|
||||
inverseAltBehavior: true,
|
||||
orientation: Orientation.HORIZONTAL,
|
||||
styles: this.style
|
||||
});
|
||||
|
||||
this.splitViewDisposables.push(this.splitView.onDidSashChange(() => {
|
||||
this.state.leftMarginRatio = this.splitView.getViewSize(0) / this.width;
|
||||
this.state.rightMarginRatio = this.splitView.getViewSize(2) / this.width;
|
||||
}));
|
||||
this.splitViewDisposables.push(this.splitView.onDidSashReset(() => {
|
||||
this.state.leftMarginRatio = GOLDEN_RATIO.leftMarginRatio;
|
||||
this.state.rightMarginRatio = GOLDEN_RATIO.rightMarginRatio;
|
||||
this.resizeMargins();
|
||||
}));
|
||||
|
||||
this.splitView.layout(this.width);
|
||||
this.splitView.addView(toSplitViewView(this.view, () => this.height), 0);
|
||||
this.emptyViews = [createEmptyView(this.style.background), createEmptyView(this.style.background)];
|
||||
this.splitView.addView(this.emptyViews[0], this.state.leftMarginRatio * this.width, 0);
|
||||
this.splitView.addView(this.emptyViews[1], this.state.rightMarginRatio * this.width, 2);
|
||||
} else {
|
||||
this.container.removeChild(this.splitView.el);
|
||||
this.splitViewDisposables = dispose(this.splitViewDisposables);
|
||||
this.splitView.dispose();
|
||||
this.splitView = undefined;
|
||||
this.emptyViews = undefined;
|
||||
this.container.appendChild(this.view.element);
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.splitViewDisposables = dispose(this.splitViewDisposables);
|
||||
|
||||
if (this.splitView) {
|
||||
this.splitView.dispose();
|
||||
this.splitView = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,20 +6,18 @@
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./checkbox';
|
||||
|
||||
import * as DOM from 'vs/base/browser/dom';
|
||||
import * as objects from 'vs/base/common/objects';
|
||||
import { KeyCode } from 'vs/base/common/keyCodes';
|
||||
import { Widget } from 'vs/base/browser/ui/widget';
|
||||
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import { Widget } from 'vs/base/browser/ui/widget';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { Emitter, Event } from 'vs/base/common/event';
|
||||
import { KeyCode } from 'vs/base/common/keyCodes';
|
||||
import * as objects from 'vs/base/common/objects';
|
||||
|
||||
export interface ICheckboxOpts extends ICheckboxStyles {
|
||||
readonly actionClassName: string;
|
||||
readonly title: string;
|
||||
readonly isChecked: boolean;
|
||||
readonly onChange: (viaKeyboard: boolean) => void;
|
||||
readonly onKeyDown?: (e: IKeyboardEvent) => void;
|
||||
}
|
||||
|
||||
export interface ICheckboxStyles {
|
||||
@@ -32,13 +30,20 @@ const defaultOpts = {
|
||||
|
||||
export class Checkbox extends Widget {
|
||||
|
||||
private readonly _onChange = this._register(new Emitter<boolean>());
|
||||
get onChange(): Event<boolean /* via keyboard */> { return this._onChange.event; }
|
||||
|
||||
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
|
||||
get onKeyDown(): Event<IKeyboardEvent> { return this._onKeyDown.event; }
|
||||
|
||||
private readonly _opts: ICheckboxOpts;
|
||||
public readonly domNode: HTMLElement;
|
||||
readonly domNode: HTMLElement;
|
||||
|
||||
private _checked: boolean;
|
||||
|
||||
constructor(opts: ICheckboxOpts) {
|
||||
super();
|
||||
|
||||
this._opts = objects.deepClone(opts);
|
||||
objects.mixin(this._opts, defaultOpts, false);
|
||||
this._checked = this._opts.isChecked;
|
||||
@@ -55,37 +60,35 @@ export class Checkbox extends Widget {
|
||||
|
||||
this.onclick(this.domNode, (ev) => {
|
||||
this.checked = !this._checked;
|
||||
this._opts.onChange(false);
|
||||
this._onChange.fire(false);
|
||||
ev.preventDefault();
|
||||
});
|
||||
|
||||
this.onkeydown(this.domNode, (keyboardEvent) => {
|
||||
if (keyboardEvent.keyCode === KeyCode.Space || keyboardEvent.keyCode === KeyCode.Enter) {
|
||||
this.checked = !this._checked;
|
||||
this._opts.onChange(true);
|
||||
this._onChange.fire(true);
|
||||
keyboardEvent.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._opts.onKeyDown) {
|
||||
this._opts.onKeyDown(keyboardEvent);
|
||||
}
|
||||
this._onKeyDown.fire(keyboardEvent);
|
||||
});
|
||||
}
|
||||
|
||||
public get enabled(): boolean {
|
||||
get enabled(): boolean {
|
||||
return this.domNode.getAttribute('aria-disabled') !== 'true';
|
||||
}
|
||||
|
||||
public focus(): void {
|
||||
focus(): void {
|
||||
this.domNode.focus();
|
||||
}
|
||||
|
||||
public get checked(): boolean {
|
||||
get checked(): boolean {
|
||||
return this._checked;
|
||||
}
|
||||
|
||||
public set checked(newIsChecked: boolean) {
|
||||
set checked(newIsChecked: boolean) {
|
||||
this._checked = newIsChecked;
|
||||
this.domNode.setAttribute('aria-checked', String(this._checked));
|
||||
if (this._checked) {
|
||||
@@ -97,11 +100,11 @@ export class Checkbox extends Widget {
|
||||
this.applyStyles();
|
||||
}
|
||||
|
||||
public width(): number {
|
||||
width(): number {
|
||||
return 2 /*marginleft*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */;
|
||||
}
|
||||
|
||||
public style(styles: ICheckboxStyles): void {
|
||||
style(styles: ICheckboxStyles): void {
|
||||
if (styles.inputActiveOptionBorder) {
|
||||
this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder;
|
||||
}
|
||||
@@ -114,12 +117,12 @@ export class Checkbox extends Widget {
|
||||
}
|
||||
}
|
||||
|
||||
public enable(): void {
|
||||
enable(): void {
|
||||
this.domNode.tabIndex = 0;
|
||||
this.domNode.setAttribute('aria-disabled', String(false));
|
||||
}
|
||||
|
||||
public disable(): void {
|
||||
disable(): void {
|
||||
DOM.removeTabIndexAndUpdateFocus(this.domNode);
|
||||
this.domNode.setAttribute('aria-disabled', String(true));
|
||||
}
|
||||
|
||||
@@ -5,5 +5,5 @@
|
||||
|
||||
.context-view {
|
||||
position: absolute;
|
||||
z-index: 1000;
|
||||
z-index: 2000;
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
import 'vs/css!./contextview';
|
||||
import { Builder, $ } from 'vs/base/browser/builder';
|
||||
import * as DOM from 'vs/base/browser/dom';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
|
||||
|
||||
export interface IAnchor {
|
||||
x: number;
|
||||
@@ -54,51 +54,46 @@ export interface ISize {
|
||||
|
||||
export interface IView extends IPosition, ISize { }
|
||||
|
||||
function layout(view: ISize, around: IView, viewport: IView, anchorPosition: AnchorPosition, anchorAlignment: AnchorAlignment): IPosition {
|
||||
export enum LayoutAnchorPosition {
|
||||
Before,
|
||||
After
|
||||
}
|
||||
|
||||
let chooseBiased = (a: number, aIsGood: boolean, b: number, bIsGood: boolean) => {
|
||||
if (aIsGood) {
|
||||
return a;
|
||||
export interface ILayoutAnchor {
|
||||
offset: number;
|
||||
size: number;
|
||||
position: LayoutAnchorPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays out a one dimensional view next to an anchor in a viewport.
|
||||
*
|
||||
* @returns The view offset within the viewport.
|
||||
*/
|
||||
export function layout(viewportSize: number, viewSize: number, anchor: ILayoutAnchor): number {
|
||||
const anchorEnd = anchor.offset + anchor.size;
|
||||
|
||||
if (anchor.position === LayoutAnchorPosition.Before) {
|
||||
if (viewSize <= viewportSize - anchorEnd) {
|
||||
return anchorEnd; // happy case, lay it out after the anchor
|
||||
}
|
||||
if (bIsGood) {
|
||||
return b;
|
||||
|
||||
if (viewSize <= anchor.offset) {
|
||||
return anchor.offset - viewSize; // ok case, lay it out before the anchor
|
||||
}
|
||||
return a;
|
||||
};
|
||||
|
||||
let chooseOne = (a: number, aIsGood: boolean, b: number, bIsGood: boolean, aIsPreferred: boolean) => {
|
||||
if (aIsPreferred) {
|
||||
return chooseBiased(a, aIsGood, b, bIsGood);
|
||||
} else {
|
||||
return chooseBiased(b, bIsGood, a, aIsGood);
|
||||
return Math.max(viewportSize - viewSize, 0); // sad case, lay it over the anchor
|
||||
} else {
|
||||
if (viewSize <= anchor.offset) {
|
||||
return anchor.offset - viewSize; // happy case, lay it out before the anchor
|
||||
}
|
||||
};
|
||||
|
||||
let top = (() => {
|
||||
// Compute both options (putting the segment above and below)
|
||||
let posAbove = around.top - view.height;
|
||||
let posBelow = around.top + around.height;
|
||||
if (viewSize <= viewportSize - anchorEnd) {
|
||||
return anchorEnd; // ok case, lay it out after the anchor
|
||||
}
|
||||
|
||||
// Check for both options if they are good
|
||||
let aboveIsGood = (posAbove >= viewport.top && posAbove + view.height <= viewport.top + viewport.height);
|
||||
let belowIsGood = (posBelow >= viewport.top && posBelow + view.height <= viewport.top + viewport.height);
|
||||
|
||||
return chooseOne(posAbove, aboveIsGood, posBelow, belowIsGood, anchorPosition === AnchorPosition.ABOVE);
|
||||
})();
|
||||
|
||||
let left = (() => {
|
||||
// Compute both options (aligning left and right)
|
||||
let posLeft = around.left;
|
||||
let posRight = around.left + around.width - view.width;
|
||||
|
||||
// Check for both options if they are good
|
||||
let leftIsGood = (posLeft >= viewport.left && posLeft + view.width <= viewport.left + viewport.width);
|
||||
let rightIsGood = (posRight >= viewport.left && posRight + view.width <= viewport.left + viewport.width);
|
||||
|
||||
return chooseOne(posLeft, leftIsGood, posRight, rightIsGood, anchorAlignment === AnchorAlignment.LEFT);
|
||||
})();
|
||||
|
||||
return { top: top, left: left };
|
||||
return 0; // sad case, lay it over the anchor
|
||||
}
|
||||
}
|
||||
|
||||
export class ContextView {
|
||||
@@ -116,11 +111,9 @@ export class ContextView {
|
||||
this.$view = $('.context-view').hide();
|
||||
this.setContainer(container);
|
||||
|
||||
this.toDispose = [{
|
||||
dispose: () => {
|
||||
this.setContainer(null);
|
||||
}
|
||||
}];
|
||||
this.toDispose = [toDisposable(() => {
|
||||
this.setContainer(null);
|
||||
})];
|
||||
|
||||
this.toDisposeOnClean = null;
|
||||
}
|
||||
@@ -207,30 +200,28 @@ export class ContextView {
|
||||
};
|
||||
}
|
||||
|
||||
let viewport = {
|
||||
top: DOM.StandardWindow.scrollY,
|
||||
left: DOM.StandardWindow.scrollX,
|
||||
height: window.innerHeight,
|
||||
width: window.innerWidth
|
||||
};
|
||||
const viewSize = this.$view.getTotalSize();
|
||||
const anchorPosition = this.delegate.anchorPosition || AnchorPosition.BELOW;
|
||||
const anchorAlignment = this.delegate.anchorAlignment || AnchorAlignment.LEFT;
|
||||
|
||||
// Get the view's size
|
||||
let viewSize = this.$view.getTotalSize();
|
||||
let view = { width: viewSize.width, height: viewSize.height };
|
||||
const verticalAnchor: ILayoutAnchor = { offset: around.top, size: around.height, position: anchorPosition === AnchorPosition.BELOW ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After };
|
||||
|
||||
let anchorPosition = this.delegate.anchorPosition || AnchorPosition.BELOW;
|
||||
let anchorAlignment = this.delegate.anchorAlignment || AnchorAlignment.LEFT;
|
||||
let horizontalAnchor: ILayoutAnchor;
|
||||
|
||||
let result = layout(view, around, viewport, anchorPosition, anchorAlignment);
|
||||
if (anchorAlignment === AnchorAlignment.LEFT) {
|
||||
horizontalAnchor = { offset: around.left, size: 0, position: LayoutAnchorPosition.Before };
|
||||
} else {
|
||||
horizontalAnchor = { offset: around.left + around.width, size: 0, position: LayoutAnchorPosition.After };
|
||||
}
|
||||
|
||||
let containerPosition = DOM.getDomNodePagePosition(this.$container.getHTMLElement());
|
||||
result.top -= containerPosition.top;
|
||||
result.left -= containerPosition.left;
|
||||
const containerPosition = DOM.getDomNodePagePosition(this.$container.getHTMLElement());
|
||||
const top = layout(window.innerHeight, viewSize.height, verticalAnchor) - containerPosition.top;
|
||||
const left = layout(window.innerWidth, viewSize.width, horizontalAnchor) - containerPosition.left;
|
||||
|
||||
this.$view.removeClass('top', 'bottom', 'left', 'right');
|
||||
this.$view.addClass(anchorPosition === AnchorPosition.BELOW ? 'bottom' : 'top');
|
||||
this.$view.addClass(anchorAlignment === AnchorAlignment.LEFT ? 'left' : 'right');
|
||||
this.$view.style({ top: result.top + 'px', left: result.left + 'px', width: 'initial' });
|
||||
this.$view.style({ top: `${top}px`, left: `${left}px`, width: 'initial' });
|
||||
}
|
||||
|
||||
public hide(data?: any): void {
|
||||
|
||||
@@ -4,10 +4,13 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
.monaco-count-badge {
|
||||
padding: 0.2em 0.5em;
|
||||
padding: 0.3em 0.5em;
|
||||
border-radius: 1em;
|
||||
font-size: 85%;
|
||||
min-width: 1.6em;
|
||||
line-height: 1em;
|
||||
font-weight: normal;
|
||||
text-align: center;
|
||||
display: inline;
|
||||
display: inline-block;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@@ -28,7 +28,8 @@ export interface IBaseDropdownOptions {
|
||||
}
|
||||
|
||||
export class BaseDropdown extends ActionRunner {
|
||||
private _toDispose: IDisposable[];
|
||||
private _toDispose: IDisposable[] = [];
|
||||
|
||||
private $el: Builder;
|
||||
private $boxContainer: Builder;
|
||||
private $label: Builder;
|
||||
@@ -38,8 +39,6 @@ export class BaseDropdown extends ActionRunner {
|
||||
constructor(container: HTMLElement, options: IBaseDropdownOptions) {
|
||||
super();
|
||||
|
||||
this._toDispose = [];
|
||||
|
||||
this.$el = $('.monaco-dropdown').appendTo(container);
|
||||
|
||||
this.$label = $('.dropdown-label');
|
||||
@@ -66,8 +65,7 @@ export class BaseDropdown extends ActionRunner {
|
||||
}
|
||||
}).appendTo(this.$el);
|
||||
|
||||
let cleanupFn = labelRenderer(this.$label.getHTMLElement());
|
||||
|
||||
const cleanupFn = labelRenderer(this.$label.getHTMLElement());
|
||||
if (cleanupFn) {
|
||||
this._toDispose.push(cleanupFn);
|
||||
}
|
||||
@@ -75,27 +73,27 @@ export class BaseDropdown extends ActionRunner {
|
||||
Gesture.addTarget(this.$label.getHTMLElement());
|
||||
}
|
||||
|
||||
public get toDispose(): IDisposable[] {
|
||||
get toDispose(): IDisposable[] {
|
||||
return this._toDispose;
|
||||
}
|
||||
|
||||
public get element(): HTMLElement {
|
||||
get element(): HTMLElement {
|
||||
return this.$el.getHTMLElement();
|
||||
}
|
||||
|
||||
public get label(): HTMLElement {
|
||||
get label(): HTMLElement {
|
||||
return this.$label.getHTMLElement();
|
||||
}
|
||||
|
||||
public set tooltip(tooltip: string) {
|
||||
set tooltip(tooltip: string) {
|
||||
this.$label.title(tooltip);
|
||||
}
|
||||
|
||||
public show(): void {
|
||||
show(): void {
|
||||
this.visible = true;
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
hide(): void {
|
||||
this.visible = false;
|
||||
}
|
||||
|
||||
@@ -103,7 +101,7 @@ export class BaseDropdown extends ActionRunner {
|
||||
this.hide();
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
dispose(): void {
|
||||
super.dispose();
|
||||
this.hide();
|
||||
|
||||
@@ -139,7 +137,7 @@ export class Dropdown extends BaseDropdown {
|
||||
this.contextViewProvider = options.contextViewProvider;
|
||||
}
|
||||
|
||||
public show(): void {
|
||||
show(): void {
|
||||
super.show();
|
||||
|
||||
addClass(this.element, 'active');
|
||||
@@ -167,7 +165,7 @@ export class Dropdown extends BaseDropdown {
|
||||
removeClass(this.element, 'active');
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
hide(): void {
|
||||
super.hide();
|
||||
|
||||
if (this.contextViewProvider) {
|
||||
@@ -211,11 +209,11 @@ export class DropdownMenu extends BaseDropdown {
|
||||
this.menuClassName = options.menuClassName || '';
|
||||
}
|
||||
|
||||
public set menuOptions(options: IMenuOptions) {
|
||||
set menuOptions(options: IMenuOptions) {
|
||||
this._menuOptions = options;
|
||||
}
|
||||
|
||||
public get menuOptions(): IMenuOptions {
|
||||
get menuOptions(): IMenuOptions {
|
||||
return this._menuOptions;
|
||||
}
|
||||
|
||||
@@ -231,7 +229,7 @@ export class DropdownMenu extends BaseDropdown {
|
||||
this._actions = actions;
|
||||
}
|
||||
|
||||
public show(): void {
|
||||
show(): void {
|
||||
super.show();
|
||||
|
||||
addClass(this.element, 'active');
|
||||
@@ -243,14 +241,19 @@ export class DropdownMenu extends BaseDropdown {
|
||||
getActionItem: (action) => this.menuOptions && this.menuOptions.actionItemProvider ? this.menuOptions.actionItemProvider(action) : null,
|
||||
getKeyBinding: (action: IAction) => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : null,
|
||||
getMenuClassName: () => this.menuClassName,
|
||||
onHide: () => removeClass(this.element, 'active'),
|
||||
onHide: () => this.onHide(),
|
||||
actionRunner: this.menuOptions ? this.menuOptions.actionRunner : null
|
||||
});
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
hide(): void {
|
||||
super.hide();
|
||||
}
|
||||
|
||||
private onHide(): void {
|
||||
this.hide();
|
||||
removeClass(this.element, 'active');
|
||||
}
|
||||
}
|
||||
|
||||
export class DropdownMenuActionItem extends BaseActionItem {
|
||||
@@ -274,8 +277,8 @@ export class DropdownMenuActionItem extends BaseActionItem {
|
||||
this.clazz = clazz;
|
||||
}
|
||||
|
||||
public render(container: HTMLElement): void {
|
||||
let labelRenderer: ILabelRenderer = (el: HTMLElement): IDisposable => {
|
||||
render(container: HTMLElement): void {
|
||||
const labelRenderer: ILabelRenderer = (el: HTMLElement): IDisposable => {
|
||||
this.builder = $('a.action-label').attr({
|
||||
tabIndex: '0',
|
||||
role: 'button',
|
||||
@@ -289,7 +292,7 @@ export class DropdownMenuActionItem extends BaseActionItem {
|
||||
return null;
|
||||
};
|
||||
|
||||
let options: IDropdownMenuOptions = {
|
||||
const options: IDropdownMenuOptions = {
|
||||
contextMenuProvider: this.contextMenuProvider,
|
||||
labelRenderer: labelRenderer
|
||||
};
|
||||
@@ -311,7 +314,7 @@ export class DropdownMenuActionItem extends BaseActionItem {
|
||||
};
|
||||
}
|
||||
|
||||
public setActionContext(newContext: any): void {
|
||||
setActionContext(newContext: any): void {
|
||||
super.setActionContext(newContext);
|
||||
|
||||
if (this.dropdownMenu) {
|
||||
@@ -319,13 +322,13 @@ export class DropdownMenuActionItem extends BaseActionItem {
|
||||
}
|
||||
}
|
||||
|
||||
public show(): void {
|
||||
show(): void {
|
||||
if (this.dropdownMenu) {
|
||||
this.dropdownMenu.show();
|
||||
}
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
dispose(): void {
|
||||
this.dropdownMenu.dispose();
|
||||
|
||||
super.dispose();
|
||||
|
||||
@@ -8,7 +8,7 @@ import 'vs/css!./findInput';
|
||||
|
||||
import * as nls from 'vs/nls';
|
||||
import * as dom from 'vs/base/browser/dom';
|
||||
import { IMessage as InputBoxMessage, IInputValidator, InputBox, IInputBoxStyles } from 'vs/base/browser/ui/inputbox/inputBox';
|
||||
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
|
||||
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
|
||||
import { Widget } from 'vs/base/browser/ui/widget';
|
||||
import { Event, Emitter } from 'vs/base/common/event';
|
||||
@@ -28,6 +28,7 @@ export interface IFindInputOptions extends IFindInputStyles {
|
||||
readonly appendCaseSensitiveLabel?: string;
|
||||
readonly appendWholeWordsLabel?: string;
|
||||
readonly appendRegexLabel?: string;
|
||||
readonly history?: string[];
|
||||
}
|
||||
|
||||
export interface IFindInputStyles extends IInputBoxStyles {
|
||||
@@ -62,7 +63,7 @@ export class FindInput extends Widget {
|
||||
private wholeWords: WholeWordsCheckbox;
|
||||
private caseSensitive: CaseSensitiveCheckbox;
|
||||
public domNode: HTMLElement;
|
||||
public inputBox: InputBox;
|
||||
public inputBox: HistoryInputBox;
|
||||
|
||||
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
|
||||
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
|
||||
@@ -82,6 +83,9 @@ export class FindInput extends Widget {
|
||||
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
|
||||
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
|
||||
|
||||
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
|
||||
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
|
||||
|
||||
constructor(parent: HTMLElement, contextViewProvider: IContextViewProvider, options?: IFindInputOptions) {
|
||||
super();
|
||||
this.contextViewProvider = contextViewProvider;
|
||||
@@ -108,7 +112,7 @@ export class FindInput extends Widget {
|
||||
this.domNode = null;
|
||||
this.inputBox = null;
|
||||
|
||||
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '');
|
||||
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history);
|
||||
|
||||
if (Boolean(parent)) {
|
||||
parent.appendChild(this.domNode);
|
||||
@@ -247,6 +251,10 @@ export class FindInput extends Widget {
|
||||
this.caseSensitive.focus();
|
||||
}
|
||||
|
||||
public focusOnRegex(): void {
|
||||
this.regex.focus();
|
||||
}
|
||||
|
||||
private _lastHighlightFindOptions: number = 0;
|
||||
public highlightFindOptions(): void {
|
||||
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
|
||||
@@ -259,12 +267,12 @@ export class FindInput extends Widget {
|
||||
this.inputBox.width = w;
|
||||
}
|
||||
|
||||
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string): void {
|
||||
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[]): void {
|
||||
this.domNode = document.createElement('div');
|
||||
this.domNode.style.width = this.width + 'px';
|
||||
dom.addClass(this.domNode, 'monaco-findInput');
|
||||
|
||||
this.inputBox = this._register(new InputBox(this.domNode, this.contextViewProvider, {
|
||||
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
|
||||
placeholder: this.placeholder || '',
|
||||
ariaLabel: this.label || '',
|
||||
validationOptions: {
|
||||
@@ -278,51 +286,57 @@ export class FindInput extends Widget {
|
||||
inputValidationWarningBackground: this.inputValidationWarningBackground,
|
||||
inputValidationWarningBorder: this.inputValidationWarningBorder,
|
||||
inputValidationErrorBackground: this.inputValidationErrorBackground,
|
||||
inputValidationErrorBorder: this.inputValidationErrorBorder
|
||||
inputValidationErrorBorder: this.inputValidationErrorBorder,
|
||||
history
|
||||
}));
|
||||
|
||||
this.regex = this._register(new RegexCheckbox({
|
||||
appendTitle: appendRegexLabel,
|
||||
isChecked: false,
|
||||
onChange: (viaKeyboard) => {
|
||||
this._onDidOptionChange.fire(viaKeyboard);
|
||||
if (!viaKeyboard) {
|
||||
this.inputBox.focus();
|
||||
}
|
||||
this.setInputWidth();
|
||||
this.validate();
|
||||
},
|
||||
inputActiveOptionBorder: this.inputActiveOptionBorder
|
||||
}));
|
||||
this._register(this.regex.onChange(viaKeyboard => {
|
||||
this._onDidOptionChange.fire(viaKeyboard);
|
||||
if (!viaKeyboard) {
|
||||
this.inputBox.focus();
|
||||
}
|
||||
this.setInputWidth();
|
||||
this.validate();
|
||||
}));
|
||||
this._register(this.regex.onKeyDown(e => {
|
||||
this._onRegexKeyDown.fire(e);
|
||||
}));
|
||||
|
||||
this.wholeWords = this._register(new WholeWordsCheckbox({
|
||||
appendTitle: appendWholeWordsLabel,
|
||||
isChecked: false,
|
||||
onChange: (viaKeyboard) => {
|
||||
this._onDidOptionChange.fire(viaKeyboard);
|
||||
if (!viaKeyboard) {
|
||||
this.inputBox.focus();
|
||||
}
|
||||
this.setInputWidth();
|
||||
this.validate();
|
||||
},
|
||||
inputActiveOptionBorder: this.inputActiveOptionBorder
|
||||
}));
|
||||
this._register(this.wholeWords.onChange(viaKeyboard => {
|
||||
this._onDidOptionChange.fire(viaKeyboard);
|
||||
if (!viaKeyboard) {
|
||||
this.inputBox.focus();
|
||||
}
|
||||
this.setInputWidth();
|
||||
this.validate();
|
||||
}));
|
||||
|
||||
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
|
||||
appendTitle: appendCaseSensitiveLabel,
|
||||
isChecked: false,
|
||||
onChange: (viaKeyboard) => {
|
||||
this._onDidOptionChange.fire(viaKeyboard);
|
||||
if (!viaKeyboard) {
|
||||
this.inputBox.focus();
|
||||
}
|
||||
this.setInputWidth();
|
||||
this.validate();
|
||||
},
|
||||
onKeyDown: (e) => {
|
||||
this._onCaseSensitiveKeyDown.fire(e);
|
||||
},
|
||||
inputActiveOptionBorder: this.inputActiveOptionBorder
|
||||
}));
|
||||
this._register(this.caseSensitive.onChange(viaKeyboard => {
|
||||
this._onDidOptionChange.fire(viaKeyboard);
|
||||
if (!viaKeyboard) {
|
||||
this.inputBox.focus();
|
||||
}
|
||||
this.setInputWidth();
|
||||
this.validate();
|
||||
}));
|
||||
this._register(this.caseSensitive.onKeyDown(e => {
|
||||
this._onCaseSensitiveKeyDown.fire(e);
|
||||
}));
|
||||
|
||||
// Arrow-Key support to navigate between options
|
||||
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
|
||||
|
||||
@@ -4,18 +4,14 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./findInputCheckboxes';
|
||||
|
||||
import * as nls from 'vs/nls';
|
||||
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
|
||||
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import 'vs/css!./findInputCheckboxes';
|
||||
import * as nls from 'vs/nls';
|
||||
|
||||
export interface IFindInputCheckboxOpts {
|
||||
readonly appendTitle: string;
|
||||
readonly isChecked: boolean;
|
||||
readonly onChange: (viaKeyboard: boolean) => void;
|
||||
readonly onKeyDown?: (e: IKeyboardEvent) => void;
|
||||
readonly inputActiveOptionBorder?: Color;
|
||||
}
|
||||
|
||||
@@ -29,8 +25,6 @@ export class CaseSensitiveCheckbox extends Checkbox {
|
||||
actionClassName: 'monaco-case-sensitive',
|
||||
title: NLS_CASE_SENSITIVE_CHECKBOX_LABEL + opts.appendTitle,
|
||||
isChecked: opts.isChecked,
|
||||
onChange: opts.onChange,
|
||||
onKeyDown: opts.onKeyDown,
|
||||
inputActiveOptionBorder: opts.inputActiveOptionBorder
|
||||
});
|
||||
}
|
||||
@@ -42,8 +36,6 @@ export class WholeWordsCheckbox extends Checkbox {
|
||||
actionClassName: 'monaco-whole-word',
|
||||
title: NLS_WHOLE_WORD_CHECKBOX_LABEL + opts.appendTitle,
|
||||
isChecked: opts.isChecked,
|
||||
onChange: opts.onChange,
|
||||
onKeyDown: opts.onKeyDown,
|
||||
inputActiveOptionBorder: opts.inputActiveOptionBorder
|
||||
});
|
||||
}
|
||||
@@ -55,8 +47,6 @@ export class RegexCheckbox extends Checkbox {
|
||||
actionClassName: 'monaco-regex',
|
||||
title: NLS_REGEX_CHECKBOX_LABEL + opts.appendTitle,
|
||||
isChecked: opts.isChecked,
|
||||
onChange: opts.onChange,
|
||||
onKeyDown: opts.onKeyDown,
|
||||
inputActiveOptionBorder: opts.inputActiveOptionBorder
|
||||
});
|
||||
}
|
||||
|
||||
630
src/vs/base/browser/ui/grid/grid.ts
Normal file
630
src/vs/base/browser/ui/grid/grid.ts
Normal file
@@ -0,0 +1,630 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./gridview';
|
||||
import { Orientation } from 'vs/base/browser/ui/sash/sash';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { tail2 as tail } from 'vs/base/common/arrays';
|
||||
import { orthogonal, IView, GridView, Sizing as GridViewSizing, Box, IGridViewStyles } from './gridview';
|
||||
import { Event } from 'vs/base/common/event';
|
||||
|
||||
export { Orientation } from './gridview';
|
||||
|
||||
export enum Direction {
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right
|
||||
}
|
||||
|
||||
function oppositeDirection(direction: Direction): Direction {
|
||||
switch (direction) {
|
||||
case Direction.Up: return Direction.Down;
|
||||
case Direction.Down: return Direction.Up;
|
||||
case Direction.Left: return Direction.Right;
|
||||
case Direction.Right: return Direction.Left;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GridLeafNode<T extends IView> {
|
||||
readonly view: T;
|
||||
readonly box: Box;
|
||||
}
|
||||
|
||||
export interface GridBranchNode<T extends IView> {
|
||||
readonly children: GridNode<T>[];
|
||||
readonly box: Box;
|
||||
}
|
||||
|
||||
export type GridNode<T extends IView> = GridLeafNode<T> | GridBranchNode<T>;
|
||||
|
||||
export function isGridBranchNode<T extends IView>(node: GridNode<T>): node is GridBranchNode<T> {
|
||||
return !!(node as any).children;
|
||||
}
|
||||
|
||||
function getGridNode<T extends IView>(node: GridNode<T>, location: number[]): GridNode<T> {
|
||||
if (location.length === 0) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (!isGridBranchNode(node)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
const [index, ...rest] = location;
|
||||
return getGridNode(node.children[index], rest);
|
||||
}
|
||||
|
||||
interface Range {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
}
|
||||
|
||||
function intersects(one: Range, other: Range): boolean {
|
||||
return !(one.start >= other.end || other.start >= one.end);
|
||||
}
|
||||
|
||||
interface Boundary {
|
||||
readonly offset: number;
|
||||
readonly range: Range;
|
||||
}
|
||||
|
||||
function getBoxBoundary(box: Box, direction: Direction): Boundary {
|
||||
const orientation = getDirectionOrientation(direction);
|
||||
const offset = direction === Direction.Up ? box.top :
|
||||
direction === Direction.Right ? box.left + box.width :
|
||||
direction === Direction.Down ? box.top + box.height :
|
||||
box.left;
|
||||
|
||||
const range = {
|
||||
start: orientation === Orientation.HORIZONTAL ? box.top : box.left,
|
||||
end: orientation === Orientation.HORIZONTAL ? box.top + box.height : box.left + box.width
|
||||
};
|
||||
|
||||
return { offset, range };
|
||||
}
|
||||
|
||||
function findAdjacentBoxLeafNodes<T extends IView>(boxNode: GridNode<T>, direction: Direction, boundary: Boundary): GridLeafNode<T>[] {
|
||||
const result: GridLeafNode<T>[] = [];
|
||||
|
||||
function _(boxNode: GridNode<T>, direction: Direction, boundary: Boundary): void {
|
||||
if (isGridBranchNode(boxNode)) {
|
||||
for (const child of boxNode.children) {
|
||||
_(child, direction, boundary);
|
||||
}
|
||||
} else {
|
||||
const { offset, range } = getBoxBoundary(boxNode.box, direction);
|
||||
|
||||
if (offset === boundary.offset && intersects(range, boundary.range)) {
|
||||
result.push(boxNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_(boxNode, direction, boundary);
|
||||
return result;
|
||||
}
|
||||
|
||||
function getLocationOrientation(rootOrientation: Orientation, location: number[]): Orientation {
|
||||
return location.length % 2 === 0 ? orthogonal(rootOrientation) : rootOrientation;
|
||||
}
|
||||
|
||||
function getDirectionOrientation(direction: Direction): Orientation {
|
||||
return direction === Direction.Up || direction === Direction.Down ? Orientation.VERTICAL : Orientation.HORIZONTAL;
|
||||
}
|
||||
|
||||
function getSize(dimensions: { width: number; height: number; }, orientation: Orientation) {
|
||||
return orientation === Orientation.HORIZONTAL ? dimensions.width : dimensions.height;
|
||||
}
|
||||
|
||||
export function getRelativeLocation(rootOrientation: Orientation, location: number[], direction: Direction): number[] {
|
||||
const orientation = getLocationOrientation(rootOrientation, location);
|
||||
const directionOrientation = getDirectionOrientation(direction);
|
||||
|
||||
if (orientation === directionOrientation) {
|
||||
let [rest, index] = tail(location);
|
||||
|
||||
if (direction === Direction.Right || direction === Direction.Down) {
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return [...rest, index];
|
||||
} else {
|
||||
const index = (direction === Direction.Right || direction === Direction.Down) ? 1 : 0;
|
||||
return [...location, index];
|
||||
}
|
||||
}
|
||||
|
||||
function indexInParent(element: HTMLElement): number {
|
||||
const parentElement = element.parentElement;
|
||||
let el = parentElement.firstElementChild;
|
||||
let index = 0;
|
||||
|
||||
while (el !== element && el !== parentElement.lastElementChild) {
|
||||
el = el.nextElementSibling;
|
||||
index++;
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the grid location of a specific DOM element by traversing the parent
|
||||
* chain and finding each child index on the way.
|
||||
*
|
||||
* This will break as soon as DOM structures of the Splitview or Gridview change.
|
||||
*/
|
||||
function getGridLocation(element: HTMLElement): number[] {
|
||||
if (/\bmonaco-grid-view\b/.test(element.parentElement.className)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const index = indexInParent(element.parentElement);
|
||||
const ancestor = element.parentElement.parentElement.parentElement.parentElement;
|
||||
return [...getGridLocation(ancestor), index];
|
||||
}
|
||||
|
||||
export enum Sizing {
|
||||
Distribute = 'distribute',
|
||||
Split = 'split'
|
||||
}
|
||||
|
||||
export interface IGridStyles extends IGridViewStyles { }
|
||||
|
||||
export interface IGridOptions {
|
||||
styles?: IGridStyles;
|
||||
}
|
||||
|
||||
export class Grid<T extends IView> implements IDisposable {
|
||||
|
||||
protected gridview: GridView;
|
||||
private views = new Map<T, HTMLElement>();
|
||||
private disposables: IDisposable[] = [];
|
||||
|
||||
get orientation(): Orientation { return this.gridview.orientation; }
|
||||
set orientation(orientation: Orientation) { this.gridview.orientation = orientation; }
|
||||
|
||||
get width(): number { return this.gridview.width; }
|
||||
get height(): number { return this.gridview.height; }
|
||||
|
||||
get minimumWidth(): number { return this.gridview.minimumWidth; }
|
||||
get minimumHeight(): number { return this.gridview.minimumHeight; }
|
||||
get maximumWidth(): number { return this.gridview.maximumWidth; }
|
||||
get maximumHeight(): number { return this.gridview.maximumHeight; }
|
||||
get onDidChange(): Event<{ width: number; height: number; }> { return this.gridview.onDidChange; }
|
||||
|
||||
get element(): HTMLElement { return this.gridview.element; }
|
||||
|
||||
sashResetSizing: Sizing = Sizing.Distribute;
|
||||
|
||||
constructor(view: T, options: IGridOptions = {}) {
|
||||
this.gridview = new GridView(options);
|
||||
this.disposables.push(this.gridview);
|
||||
|
||||
this.gridview.onDidSashReset(this.doResetViewSize, this, this.disposables);
|
||||
|
||||
this._addView(view, 0, [0]);
|
||||
}
|
||||
|
||||
style(styles: IGridStyles): void {
|
||||
this.gridview.style(styles);
|
||||
}
|
||||
|
||||
layout(width: number, height: number): void {
|
||||
this.gridview.layout(width, height);
|
||||
}
|
||||
|
||||
addView(newView: T, size: number | Sizing, referenceView: T, direction: Direction): void {
|
||||
if (this.views.has(newView)) {
|
||||
throw new Error('Can\'t add same view twice');
|
||||
}
|
||||
|
||||
const orientation = getDirectionOrientation(direction);
|
||||
|
||||
if (this.views.size === 1 && this.orientation !== orientation) {
|
||||
this.orientation = orientation;
|
||||
}
|
||||
|
||||
const referenceLocation = this.getViewLocation(referenceView);
|
||||
const location = getRelativeLocation(this.gridview.orientation, referenceLocation, direction);
|
||||
|
||||
let viewSize: number | GridViewSizing;
|
||||
|
||||
if (size === Sizing.Split) {
|
||||
const [, index] = tail(referenceLocation);
|
||||
viewSize = GridViewSizing.Split(index);
|
||||
} else if (size === Sizing.Distribute) {
|
||||
viewSize = GridViewSizing.Distribute;
|
||||
} else {
|
||||
viewSize = size;
|
||||
}
|
||||
|
||||
this._addView(newView, viewSize, location);
|
||||
}
|
||||
|
||||
protected _addView(newView: T, size: number | GridViewSizing, location): void {
|
||||
this.views.set(newView, newView.element);
|
||||
this.gridview.addView(newView, size, location);
|
||||
}
|
||||
|
||||
removeView(view: T, sizing?: Sizing): void {
|
||||
if (this.views.size === 1) {
|
||||
throw new Error('Can\'t remove last view');
|
||||
}
|
||||
|
||||
if (!this.views.has(view)) {
|
||||
throw new Error('View not found');
|
||||
}
|
||||
|
||||
const location = this.getViewLocation(view);
|
||||
this.gridview.removeView(location, sizing === Sizing.Distribute ? GridViewSizing.Distribute : undefined);
|
||||
this.views.delete(view);
|
||||
}
|
||||
|
||||
swapViews(from: T, to: T): void {
|
||||
const fromLocation = this.getViewLocation(from);
|
||||
const toLocation = this.getViewLocation(to);
|
||||
return this.gridview.swapViews(fromLocation, toLocation);
|
||||
}
|
||||
|
||||
resizeView(view: T, size: number): void {
|
||||
const location = this.getViewLocation(view);
|
||||
return this.gridview.resizeView(location, size);
|
||||
}
|
||||
|
||||
getViewSize(view: T): number {
|
||||
const location = this.getViewLocation(view);
|
||||
const viewSize = this.gridview.getViewSize(location);
|
||||
return getLocationOrientation(this.orientation, location) === Orientation.HORIZONTAL ? viewSize.width : viewSize.height;
|
||||
}
|
||||
|
||||
// TODO@joao cleanup
|
||||
getViewSize2(view: T): { width: number; height: number; } {
|
||||
const location = this.getViewLocation(view);
|
||||
return this.gridview.getViewSize(location);
|
||||
}
|
||||
|
||||
maximizeViewSize(view: T): void {
|
||||
const location = this.getViewLocation(view);
|
||||
this.gridview.maximizeViewSize(location);
|
||||
}
|
||||
|
||||
distributeViewSizes(): void {
|
||||
this.gridview.distributeViewSizes();
|
||||
}
|
||||
|
||||
getViews(): GridBranchNode<T> {
|
||||
return this.gridview.getViews() as GridBranchNode<T>;
|
||||
}
|
||||
|
||||
getNeighborViews(view: T, direction: Direction, wrap: boolean = false): T[] {
|
||||
const location = this.getViewLocation(view);
|
||||
const root = this.getViews();
|
||||
const node = getGridNode(root, location);
|
||||
let boundary = getBoxBoundary(node.box, direction);
|
||||
|
||||
if (wrap) {
|
||||
if (direction === Direction.Up && node.box.top === 0) {
|
||||
boundary = { offset: root.box.top + root.box.height, range: boundary.range };
|
||||
} else if (direction === Direction.Right && node.box.left + node.box.width === root.box.width) {
|
||||
boundary = { offset: 0, range: boundary.range };
|
||||
} else if (direction === Direction.Down && node.box.top + node.box.height === root.box.height) {
|
||||
boundary = { offset: 0, range: boundary.range };
|
||||
} else if (direction === Direction.Left && node.box.left === 0) {
|
||||
boundary = { offset: root.box.left + root.box.width, range: boundary.range };
|
||||
}
|
||||
}
|
||||
|
||||
return findAdjacentBoxLeafNodes(root, oppositeDirection(direction), boundary)
|
||||
.map(node => node.view);
|
||||
}
|
||||
|
||||
private getViewLocation(view: T): number[] {
|
||||
const element = this.views.get(view);
|
||||
|
||||
if (!element) {
|
||||
throw new Error('View not found');
|
||||
}
|
||||
|
||||
return getGridLocation(element);
|
||||
}
|
||||
|
||||
private doResetViewSize(location: number[]): void {
|
||||
if (this.sashResetSizing === Sizing.Split) {
|
||||
const orientation = getLocationOrientation(this.orientation, location);
|
||||
const firstViewSize = getSize(this.gridview.getViewSize(location), orientation);
|
||||
const [parentLocation, index] = tail(location);
|
||||
const secondViewSize = getSize(this.gridview.getViewSize([...parentLocation, index + 1]), orientation);
|
||||
const totalSize = firstViewSize + secondViewSize;
|
||||
this.gridview.resizeView(location, Math.floor(totalSize / 2));
|
||||
|
||||
} else {
|
||||
const [parentLocation,] = tail(location);
|
||||
this.gridview.distributeViewSizes(parentLocation);
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposables = dispose(this.disposables);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ISerializableView extends IView {
|
||||
toJSON(): object;
|
||||
}
|
||||
|
||||
export interface IViewDeserializer<T extends ISerializableView> {
|
||||
fromJSON(json: object): T;
|
||||
}
|
||||
|
||||
interface InitialLayoutContext<T extends ISerializableView> {
|
||||
width: number;
|
||||
height: number;
|
||||
root: GridBranchNode<T>;
|
||||
}
|
||||
|
||||
export interface ISerializedLeafNode {
|
||||
type: 'leaf';
|
||||
data: object;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface ISerializedBranchNode {
|
||||
type: 'branch';
|
||||
data: ISerializedNode[];
|
||||
size: number;
|
||||
}
|
||||
|
||||
export type ISerializedNode = ISerializedLeafNode | ISerializedBranchNode;
|
||||
|
||||
export interface ISerializedGrid {
|
||||
root: ISerializedNode;
|
||||
orientation: Orientation;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export class SerializableGrid<T extends ISerializableView> extends Grid<T> {
|
||||
|
||||
private static serializeNode<T extends ISerializableView>(node: GridNode<T>, orientation: Orientation): ISerializedNode {
|
||||
const size = orientation === Orientation.VERTICAL ? node.box.width : node.box.height;
|
||||
|
||||
if (!isGridBranchNode(node)) {
|
||||
return { type: 'leaf', data: node.view.toJSON(), size };
|
||||
}
|
||||
|
||||
return { type: 'branch', data: node.children.map(c => SerializableGrid.serializeNode(c, orthogonal(orientation))), size };
|
||||
}
|
||||
|
||||
private static deserializeNode<T extends ISerializableView>(json: ISerializedNode, orientation: Orientation, box: Box, deserializer: IViewDeserializer<T>): GridNode<T> {
|
||||
if (!json || typeof json !== 'object') {
|
||||
throw new Error('Invalid JSON');
|
||||
}
|
||||
|
||||
const type = json.type;
|
||||
const data = json.data;
|
||||
|
||||
if (type === 'branch') {
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error('Invalid JSON: \'data\' property of branch must be an array.');
|
||||
}
|
||||
|
||||
const children: GridNode<T>[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const child of data) {
|
||||
if (typeof child.size !== 'number') {
|
||||
throw new Error('Invalid JSON: \'size\' property of node must be a number.');
|
||||
}
|
||||
|
||||
const childBox: Box = orientation === Orientation.HORIZONTAL
|
||||
? { top: box.top, left: box.left + offset, width: child.size, height: box.height }
|
||||
: { top: box.top + offset, left: box.left, width: box.width, height: child.size };
|
||||
|
||||
children.push(SerializableGrid.deserializeNode(child, orthogonal(orientation), childBox, deserializer));
|
||||
offset += child.size;
|
||||
}
|
||||
|
||||
return { children, box };
|
||||
|
||||
} else if (type === 'leaf') {
|
||||
const view = deserializer.fromJSON(data) as T;
|
||||
return { view, box };
|
||||
}
|
||||
|
||||
throw new Error('Invalid JSON: \'type\' property must be either \'branch\' or \'leaf\'.');
|
||||
}
|
||||
|
||||
private static getFirstLeaf<T extends IView>(node: GridNode<T>): GridLeafNode<T> | undefined {
|
||||
if (!isGridBranchNode(node)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
return SerializableGrid.getFirstLeaf(node.children[0]);
|
||||
}
|
||||
|
||||
static deserialize<T extends ISerializableView>(json: ISerializedGrid, deserializer: IViewDeserializer<T>, options: IGridOptions = {}): SerializableGrid<T> {
|
||||
if (typeof json.orientation !== 'number') {
|
||||
throw new Error('Invalid JSON: \'orientation\' property must be a number.');
|
||||
} else if (typeof json.width !== 'number') {
|
||||
throw new Error('Invalid JSON: \'width\' property must be a number.');
|
||||
} else if (typeof json.height !== 'number') {
|
||||
throw new Error('Invalid JSON: \'height\' property must be a number.');
|
||||
}
|
||||
|
||||
const orientation = json.orientation as Orientation;
|
||||
const width = json.width as number;
|
||||
const height = json.height as number;
|
||||
const box: Box = { top: 0, left: 0, width, height };
|
||||
|
||||
const root = SerializableGrid.deserializeNode(json.root, orientation, box, deserializer) as GridBranchNode<T>;
|
||||
const firstLeaf = SerializableGrid.getFirstLeaf(root);
|
||||
|
||||
if (!firstLeaf) {
|
||||
throw new Error('Invalid serialized state, first leaf not found');
|
||||
}
|
||||
|
||||
const result = new SerializableGrid<T>(firstLeaf.view, options);
|
||||
result.orientation = orientation;
|
||||
result.restoreViews(firstLeaf.view, orientation, root);
|
||||
result.initialLayoutContext = { width, height, root };
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Useful information in order to proportionally restore view sizes
|
||||
* upon the very first layout call.
|
||||
*/
|
||||
private initialLayoutContext: InitialLayoutContext<T> | undefined;
|
||||
|
||||
serialize(): ISerializedGrid {
|
||||
return {
|
||||
root: SerializableGrid.serializeNode(this.getViews(), this.orientation),
|
||||
orientation: this.orientation,
|
||||
width: this.width,
|
||||
height: this.height
|
||||
};
|
||||
}
|
||||
|
||||
layout(width: number, height: number): void {
|
||||
super.layout(width, height);
|
||||
|
||||
if (this.initialLayoutContext) {
|
||||
const widthScale = width / this.initialLayoutContext.width;
|
||||
const heightScale = height / this.initialLayoutContext.height;
|
||||
|
||||
this.restoreViewsSize([], this.initialLayoutContext.root, this.orientation, widthScale, heightScale);
|
||||
this.initialLayoutContext = undefined;
|
||||
|
||||
this.gridview.trySet2x2();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively restores views which were just deserialized.
|
||||
*/
|
||||
private restoreViews(referenceView: T, orientation: Orientation, node: GridNode<T>): void {
|
||||
if (!isGridBranchNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const direction = orientation === Orientation.VERTICAL ? Direction.Down : Direction.Right;
|
||||
const firstLeaves = node.children.map(c => SerializableGrid.getFirstLeaf(c));
|
||||
|
||||
for (let i = 1; i < firstLeaves.length; i++) {
|
||||
const size = orientation === Orientation.VERTICAL ? firstLeaves[i].box.height : firstLeaves[i].box.width;
|
||||
this.addView(firstLeaves[i].view, size, referenceView, direction);
|
||||
referenceView = firstLeaves[i].view;
|
||||
}
|
||||
|
||||
for (let i = 0; i < node.children.length; i++) {
|
||||
this.restoreViews(firstLeaves[i].view, orthogonal(orientation), node.children[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively restores view sizes.
|
||||
* This should be called only after the very first layout call.
|
||||
*/
|
||||
private restoreViewsSize(location: number[], node: GridNode<T>, orientation: Orientation, widthScale: number, heightScale: number): void {
|
||||
if (!isGridBranchNode(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scale = orientation === Orientation.VERTICAL ? heightScale : widthScale;
|
||||
|
||||
for (let i = 0; i < node.children.length; i++) {
|
||||
const child = node.children[i];
|
||||
const childLocation = [...location, i];
|
||||
|
||||
if (i < node.children.length - 1) {
|
||||
const size = orientation === Orientation.VERTICAL ? child.box.height : child.box.width;
|
||||
this.gridview.resizeView(childLocation, Math.floor(size * scale));
|
||||
}
|
||||
|
||||
this.restoreViewsSize(childLocation, child, orthogonal(orientation), widthScale, heightScale);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type GridNodeDescriptor = { size?: number, groups?: GridNodeDescriptor[] };
|
||||
export type GridDescriptor = { orientation: Orientation, groups?: GridNodeDescriptor[] };
|
||||
|
||||
export function sanitizeGridNodeDescriptor(nodeDescriptor: GridNodeDescriptor): void {
|
||||
if (nodeDescriptor.groups && nodeDescriptor.groups.length === 0) {
|
||||
nodeDescriptor.groups = undefined;
|
||||
}
|
||||
|
||||
if (!nodeDescriptor.groups) {
|
||||
return;
|
||||
}
|
||||
|
||||
let totalDefinedSize = 0;
|
||||
let totalDefinedSizeCount = 0;
|
||||
|
||||
for (const child of nodeDescriptor.groups) {
|
||||
sanitizeGridNodeDescriptor(child);
|
||||
|
||||
if (child.size) {
|
||||
totalDefinedSize += child.size;
|
||||
totalDefinedSizeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const totalUndefinedSize = totalDefinedSizeCount > 0 ? totalDefinedSize : 1;
|
||||
const totalUndefinedSizeCount = nodeDescriptor.groups.length - totalDefinedSizeCount;
|
||||
const eachUndefinedSize = totalUndefinedSize / totalUndefinedSizeCount;
|
||||
|
||||
for (const child of nodeDescriptor.groups) {
|
||||
if (!child.size) {
|
||||
child.size = eachUndefinedSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createSerializedNode(nodeDescriptor: GridNodeDescriptor): ISerializedNode {
|
||||
if (nodeDescriptor.groups) {
|
||||
return { type: 'branch', data: nodeDescriptor.groups.map(c => createSerializedNode(c)), size: nodeDescriptor.size! };
|
||||
} else {
|
||||
return { type: 'leaf', data: null, size: nodeDescriptor.size! };
|
||||
}
|
||||
}
|
||||
|
||||
function getDimensions(node: ISerializedNode, orientation: Orientation): { width?: number, height?: number } {
|
||||
if (node.type === 'branch') {
|
||||
const childrenDimensions = node.data.map(c => getDimensions(c, orthogonal(orientation)));
|
||||
|
||||
if (orientation === Orientation.VERTICAL) {
|
||||
const width = node.size || (childrenDimensions.length === 0 ? undefined : Math.max(...childrenDimensions.map(d => d.width || 0)));
|
||||
const height = childrenDimensions.length === 0 ? undefined : childrenDimensions.reduce((r, d) => r + d.height, 0);
|
||||
return { width, height };
|
||||
} else {
|
||||
const width = childrenDimensions.length === 0 ? undefined : childrenDimensions.reduce((r, d) => r + d.width, 0);
|
||||
const height = node.size || (childrenDimensions.length === 0 ? undefined : Math.max(...childrenDimensions.map(d => d.height || 0)));
|
||||
return { width, height };
|
||||
}
|
||||
} else {
|
||||
const width = orientation === Orientation.VERTICAL ? node.size : undefined;
|
||||
const height = orientation === Orientation.VERTICAL ? undefined : node.size;
|
||||
return { width, height };
|
||||
}
|
||||
}
|
||||
|
||||
export function createSerializedGrid(gridDescriptor: GridDescriptor): ISerializedGrid {
|
||||
sanitizeGridNodeDescriptor(gridDescriptor);
|
||||
|
||||
const root = createSerializedNode(gridDescriptor);
|
||||
const { width, height } = getDimensions(root, gridDescriptor.orientation);
|
||||
|
||||
return {
|
||||
root,
|
||||
orientation: gridDescriptor.orientation,
|
||||
width: width || 1,
|
||||
height: height || 1
|
||||
};
|
||||
}
|
||||
16
src/vs/base/browser/ui/grid/gridview.css
Normal file
16
src/vs/base/browser/ui/grid/gridview.css
Normal file
@@ -0,0 +1,16 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
.monaco-grid-view {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.monaco-grid-branch-node {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
809
src/vs/base/browser/ui/grid/gridview.ts
Normal file
809
src/vs/base/browser/ui/grid/gridview.ts
Normal file
@@ -0,0 +1,809 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./gridview';
|
||||
import { Event, anyEvent, Emitter, mapEvent, Relay } from 'vs/base/common/event';
|
||||
import { Orientation, Sash } from 'vs/base/browser/ui/sash/sash';
|
||||
import { SplitView, IView as ISplitView, Sizing, ISplitViewStyles } from 'vs/base/browser/ui/splitview/splitview';
|
||||
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
|
||||
import { $ } from 'vs/base/browser/dom';
|
||||
import { tail2 as tail } from 'vs/base/common/arrays';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
|
||||
export { Sizing } from 'vs/base/browser/ui/splitview/splitview';
|
||||
export { Orientation } from 'vs/base/browser/ui/sash/sash';
|
||||
|
||||
export interface IView {
|
||||
readonly element: HTMLElement;
|
||||
readonly minimumWidth: number;
|
||||
readonly maximumWidth: number;
|
||||
readonly minimumHeight: number;
|
||||
readonly maximumHeight: number;
|
||||
readonly onDidChange: Event<{ width: number; height: number; }>;
|
||||
layout(width: number, height: number): void;
|
||||
}
|
||||
|
||||
export function orthogonal(orientation: Orientation): Orientation {
|
||||
return orientation === Orientation.VERTICAL ? Orientation.HORIZONTAL : Orientation.VERTICAL;
|
||||
}
|
||||
|
||||
export interface Box {
|
||||
top: number;
|
||||
left: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface GridLeafNode {
|
||||
readonly view: IView;
|
||||
readonly box: Box;
|
||||
}
|
||||
|
||||
export interface GridBranchNode {
|
||||
readonly children: GridNode[];
|
||||
readonly box: Box;
|
||||
}
|
||||
|
||||
export type GridNode = GridLeafNode | GridBranchNode;
|
||||
|
||||
export function isGridBranchNode(node: GridNode): node is GridBranchNode {
|
||||
return !!(node as any).children;
|
||||
}
|
||||
|
||||
export interface IGridViewStyles extends ISplitViewStyles { }
|
||||
|
||||
const defaultStyles: IGridViewStyles = {
|
||||
separatorBorder: Color.transparent
|
||||
};
|
||||
|
||||
export interface IGridViewOptions {
|
||||
styles?: IGridViewStyles;
|
||||
}
|
||||
|
||||
class BranchNode implements ISplitView, IDisposable {
|
||||
|
||||
readonly element: HTMLElement;
|
||||
readonly children: Node[] = [];
|
||||
private splitview: SplitView;
|
||||
|
||||
private _size: number;
|
||||
get size(): number { return this._size; }
|
||||
|
||||
private _orthogonalSize: number;
|
||||
get orthogonalSize(): number { return this._orthogonalSize; }
|
||||
|
||||
private _styles: IGridViewStyles;
|
||||
get styles(): IGridViewStyles { return this._styles; }
|
||||
|
||||
get width(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.size : this.orthogonalSize;
|
||||
}
|
||||
|
||||
get height(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.orthogonalSize : this.size;
|
||||
}
|
||||
|
||||
get minimumSize(): number {
|
||||
return this.children.length === 0 ? 0 : Math.max(...this.children.map(c => c.minimumOrthogonalSize));
|
||||
}
|
||||
|
||||
get maximumSize(): number {
|
||||
return Math.min(...this.children.map(c => c.maximumOrthogonalSize));
|
||||
}
|
||||
|
||||
get minimumOrthogonalSize(): number {
|
||||
return this.splitview.minimumSize;
|
||||
}
|
||||
|
||||
get maximumOrthogonalSize(): number {
|
||||
return this.splitview.maximumSize;
|
||||
}
|
||||
|
||||
get minimumWidth(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.minimumOrthogonalSize : this.minimumSize;
|
||||
}
|
||||
|
||||
get minimumHeight(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.minimumSize : this.minimumOrthogonalSize;
|
||||
}
|
||||
|
||||
get maximumWidth(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.maximumOrthogonalSize : this.maximumSize;
|
||||
}
|
||||
|
||||
get maximumHeight(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.maximumSize : this.maximumOrthogonalSize;
|
||||
}
|
||||
|
||||
private _onDidChange = new Emitter<number | undefined>();
|
||||
readonly onDidChange: Event<number | undefined> = this._onDidChange.event;
|
||||
|
||||
private childrenChangeDisposable: IDisposable = Disposable.None;
|
||||
|
||||
private _onDidSashReset = new Emitter<number[]>();
|
||||
readonly onDidSashReset: Event<number[]> = this._onDidSashReset.event;
|
||||
private splitviewSashResetDisposable: IDisposable = Disposable.None;
|
||||
private childrenSashResetDisposable: IDisposable = Disposable.None;
|
||||
|
||||
get orthogonalStartSash(): Sash | undefined { return this.splitview.orthogonalStartSash; }
|
||||
set orthogonalStartSash(sash: Sash | undefined) { this.splitview.orthogonalStartSash = sash; }
|
||||
get orthogonalEndSash(): Sash | undefined { return this.splitview.orthogonalEndSash; }
|
||||
set orthogonalEndSash(sash: Sash | undefined) { this.splitview.orthogonalEndSash = sash; }
|
||||
|
||||
constructor(
|
||||
readonly orientation: Orientation,
|
||||
styles: IGridViewStyles,
|
||||
size: number = 0,
|
||||
orthogonalSize: number = 0
|
||||
) {
|
||||
this._styles = styles;
|
||||
this._size = size;
|
||||
this._orthogonalSize = orthogonalSize;
|
||||
|
||||
this.element = $('.monaco-grid-branch-node');
|
||||
this.splitview = new SplitView(this.element, { orientation, styles });
|
||||
this.splitview.layout(size);
|
||||
|
||||
const onDidSashReset = mapEvent(this.splitview.onDidSashReset, i => [i]);
|
||||
this.splitviewSashResetDisposable = onDidSashReset(this._onDidSashReset.fire, this._onDidSashReset);
|
||||
}
|
||||
|
||||
style(styles: IGridViewStyles): void {
|
||||
this._styles = styles;
|
||||
this.splitview.style(styles);
|
||||
|
||||
for (const child of this.children) {
|
||||
if (child instanceof BranchNode) {
|
||||
child.style(styles);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
layout(size: number): void {
|
||||
this._orthogonalSize = size;
|
||||
|
||||
for (const child of this.children) {
|
||||
child.orthogonalLayout(size);
|
||||
}
|
||||
}
|
||||
|
||||
orthogonalLayout(size: number): void {
|
||||
this._size = size;
|
||||
this.splitview.layout(size);
|
||||
}
|
||||
|
||||
addChild(node: Node, size: number | Sizing, index: number): void {
|
||||
if (index < 0 || index > this.children.length) {
|
||||
throw new Error('Invalid index');
|
||||
}
|
||||
|
||||
const first = index === 0;
|
||||
const last = index === this.splitview.length;
|
||||
this.splitview.addView(node, size, index);
|
||||
this.children.splice(index, 0, node);
|
||||
node.orthogonalStartSash = this.splitview.sashes[index - 1];
|
||||
node.orthogonalEndSash = this.splitview.sashes[index];
|
||||
|
||||
if (!first) {
|
||||
this.children[index - 1].orthogonalEndSash = this.splitview.sashes[index - 1];
|
||||
}
|
||||
|
||||
if (!last) {
|
||||
this.children[index + 1].orthogonalStartSash = this.splitview.sashes[index];
|
||||
}
|
||||
|
||||
this.onDidChildrenChange();
|
||||
}
|
||||
|
||||
removeChild(index: number, sizing?: Sizing): void {
|
||||
if (index < 0 || index >= this.children.length) {
|
||||
throw new Error('Invalid index');
|
||||
}
|
||||
|
||||
const first = index === 0;
|
||||
const last = index === this.splitview.length - 1;
|
||||
this.splitview.removeView(index, sizing);
|
||||
this.children.splice(index, 1);
|
||||
|
||||
if (!first) {
|
||||
this.children[index - 1].orthogonalEndSash = this.splitview.sashes[index - 1];
|
||||
}
|
||||
|
||||
if (!last) { // [0,1,2,3] (2) => [0,1,3]
|
||||
this.children[index].orthogonalStartSash = this.splitview.sashes[Math.max(index - 1, 0)];
|
||||
}
|
||||
|
||||
this.onDidChildrenChange();
|
||||
}
|
||||
|
||||
swapChildren(from: number, to: number): void {
|
||||
if (from === to) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (from < 0 || from >= this.children.length) {
|
||||
throw new Error('Invalid from index');
|
||||
}
|
||||
|
||||
if (to < 0 || to >= this.children.length) {
|
||||
throw new Error('Invalid to index');
|
||||
}
|
||||
|
||||
this.splitview.swapViews(from, to);
|
||||
[this.children[from].orthogonalStartSash, this.children[from].orthogonalEndSash, this.children[to].orthogonalStartSash, this.children[to].orthogonalEndSash] = [this.children[to].orthogonalStartSash, this.children[to].orthogonalEndSash, this.children[from].orthogonalStartSash, this.children[from].orthogonalEndSash];
|
||||
[this.children[from], this.children[to]] = [this.children[to], this.children[from]];
|
||||
}
|
||||
|
||||
resizeChild(index: number, size: number): void {
|
||||
if (index < 0 || index >= this.children.length) {
|
||||
throw new Error('Invalid index');
|
||||
}
|
||||
|
||||
this.splitview.resizeView(index, size);
|
||||
}
|
||||
|
||||
distributeViewSizes(recursive = false): void {
|
||||
this.splitview.distributeViewSizes();
|
||||
|
||||
if (recursive) {
|
||||
for (const child of this.children) {
|
||||
if (child instanceof BranchNode) {
|
||||
child.distributeViewSizes(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getChildSize(index: number): number {
|
||||
if (index < 0 || index >= this.children.length) {
|
||||
throw new Error('Invalid index');
|
||||
}
|
||||
|
||||
return this.splitview.getViewSize(index);
|
||||
}
|
||||
|
||||
private onDidChildrenChange(): void {
|
||||
const onDidChildrenChange = anyEvent(...this.children.map(c => c.onDidChange));
|
||||
this.childrenChangeDisposable.dispose();
|
||||
this.childrenChangeDisposable = onDidChildrenChange(this._onDidChange.fire, this._onDidChange);
|
||||
|
||||
const onDidChildrenSashReset = anyEvent(...this.children.map((c, i) => mapEvent(c.onDidSashReset, location => [i, ...location])));
|
||||
this.childrenSashResetDisposable.dispose();
|
||||
this.childrenSashResetDisposable = onDidChildrenSashReset(this._onDidSashReset.fire, this._onDidSashReset);
|
||||
|
||||
this._onDidChange.fire();
|
||||
}
|
||||
|
||||
trySet2x2(other: BranchNode): IDisposable {
|
||||
if (this.children.length !== 2 || other.children.length !== 2) {
|
||||
return Disposable.None;
|
||||
}
|
||||
|
||||
if (this.getChildSize(0) !== other.getChildSize(0)) {
|
||||
return Disposable.None;
|
||||
}
|
||||
|
||||
const [firstChild, secondChild] = this.children;
|
||||
const [otherFirstChild, otherSecondChild] = other.children;
|
||||
|
||||
if (!(firstChild instanceof LeafNode) || !(secondChild instanceof LeafNode)) {
|
||||
return Disposable.None;
|
||||
}
|
||||
|
||||
if (!(otherFirstChild instanceof LeafNode) || !(otherSecondChild instanceof LeafNode)) {
|
||||
return Disposable.None;
|
||||
}
|
||||
|
||||
if (this.orientation === Orientation.VERTICAL) {
|
||||
secondChild.linkedWidthNode = otherFirstChild.linkedHeightNode = firstChild;
|
||||
firstChild.linkedWidthNode = otherSecondChild.linkedHeightNode = secondChild;
|
||||
otherSecondChild.linkedWidthNode = firstChild.linkedHeightNode = otherFirstChild;
|
||||
otherFirstChild.linkedWidthNode = secondChild.linkedHeightNode = otherSecondChild;
|
||||
} else {
|
||||
otherFirstChild.linkedWidthNode = secondChild.linkedHeightNode = firstChild;
|
||||
otherSecondChild.linkedWidthNode = firstChild.linkedHeightNode = secondChild;
|
||||
firstChild.linkedWidthNode = otherSecondChild.linkedHeightNode = otherFirstChild;
|
||||
secondChild.linkedWidthNode = otherFirstChild.linkedHeightNode = otherSecondChild;
|
||||
}
|
||||
|
||||
const mySash = this.splitview.sashes[0];
|
||||
const otherSash = other.splitview.sashes[0];
|
||||
mySash.linkedSash = otherSash;
|
||||
otherSash.linkedSash = mySash;
|
||||
|
||||
this._onDidChange.fire();
|
||||
other._onDidChange.fire();
|
||||
|
||||
return toDisposable(() => {
|
||||
mySash.linkedSash = otherSash.linkedSash = undefined;
|
||||
firstChild.linkedHeightNode = firstChild.linkedWidthNode = undefined;
|
||||
secondChild.linkedHeightNode = secondChild.linkedWidthNode = undefined;
|
||||
otherFirstChild.linkedHeightNode = otherFirstChild.linkedWidthNode = undefined;
|
||||
otherSecondChild.linkedHeightNode = otherSecondChild.linkedWidthNode = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const child of this.children) {
|
||||
child.dispose();
|
||||
}
|
||||
|
||||
this.splitviewSashResetDisposable.dispose();
|
||||
this.childrenSashResetDisposable.dispose();
|
||||
this.childrenChangeDisposable.dispose();
|
||||
this.splitview.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class LeafNode implements ISplitView, IDisposable {
|
||||
|
||||
private _size: number = 0;
|
||||
get size(): number { return this._size; }
|
||||
|
||||
private _orthogonalSize: number;
|
||||
get orthogonalSize(): number { return this._orthogonalSize; }
|
||||
|
||||
readonly onDidSashReset: Event<number[]> = Event.None;
|
||||
|
||||
private _onDidLinkedWidthNodeChange = new Relay<number | undefined>();
|
||||
private _linkedWidthNode: LeafNode | undefined = undefined;
|
||||
get linkedWidthNode(): LeafNode | undefined { return this._linkedWidthNode; }
|
||||
set linkedWidthNode(node: LeafNode | undefined) {
|
||||
this._onDidLinkedWidthNodeChange.input = node ? node._onDidViewChange : Event.None;
|
||||
this._linkedWidthNode = node;
|
||||
this._onDidSetLinkedNode.fire();
|
||||
}
|
||||
|
||||
private _onDidLinkedHeightNodeChange = new Relay<number | undefined>();
|
||||
private _linkedHeightNode: LeafNode | undefined = undefined;
|
||||
get linkedHeightNode(): LeafNode | undefined { return this._linkedHeightNode; }
|
||||
set linkedHeightNode(node: LeafNode | undefined) {
|
||||
this._onDidLinkedHeightNodeChange.input = node ? node._onDidViewChange : Event.None;
|
||||
this._linkedHeightNode = node;
|
||||
this._onDidSetLinkedNode.fire();
|
||||
}
|
||||
|
||||
private _onDidSetLinkedNode = new Emitter<number | undefined>();
|
||||
private _onDidViewChange: Event<number | undefined>;
|
||||
readonly onDidChange: Event<number | undefined>;
|
||||
|
||||
constructor(
|
||||
readonly view: IView,
|
||||
readonly orientation: Orientation,
|
||||
orthogonalSize: number = 0
|
||||
) {
|
||||
this._orthogonalSize = orthogonalSize;
|
||||
|
||||
this._onDidViewChange = mapEvent(this.view.onDidChange, this.orientation === Orientation.HORIZONTAL ? e => e && e.width : e => e && e.height);
|
||||
this.onDidChange = anyEvent(this._onDidViewChange, this._onDidSetLinkedNode.event, this._onDidLinkedWidthNodeChange.event, this._onDidLinkedHeightNodeChange.event);
|
||||
}
|
||||
|
||||
get width(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.orthogonalSize : this.size;
|
||||
}
|
||||
|
||||
get height(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.size : this.orthogonalSize;
|
||||
}
|
||||
|
||||
get element(): HTMLElement {
|
||||
return this.view.element;
|
||||
}
|
||||
|
||||
private get minimumWidth(): number {
|
||||
return this.linkedWidthNode ? Math.max(this.linkedWidthNode.view.minimumWidth, this.view.minimumWidth) : this.view.minimumWidth;
|
||||
}
|
||||
|
||||
private get maximumWidth(): number {
|
||||
return this.linkedWidthNode ? Math.min(this.linkedWidthNode.view.maximumWidth, this.view.maximumWidth) : this.view.maximumWidth;
|
||||
}
|
||||
|
||||
private get minimumHeight(): number {
|
||||
return this.linkedHeightNode ? Math.max(this.linkedHeightNode.view.minimumHeight, this.view.minimumHeight) : this.view.minimumHeight;
|
||||
}
|
||||
|
||||
private get maximumHeight(): number {
|
||||
return this.linkedHeightNode ? Math.min(this.linkedHeightNode.view.maximumHeight, this.view.maximumHeight) : this.view.maximumHeight;
|
||||
}
|
||||
|
||||
get minimumSize(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.minimumHeight : this.minimumWidth;
|
||||
}
|
||||
|
||||
get maximumSize(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.maximumHeight : this.maximumWidth;
|
||||
}
|
||||
|
||||
get minimumOrthogonalSize(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.minimumWidth : this.minimumHeight;
|
||||
}
|
||||
|
||||
get maximumOrthogonalSize(): number {
|
||||
return this.orientation === Orientation.HORIZONTAL ? this.maximumWidth : this.maximumHeight;
|
||||
}
|
||||
|
||||
set orthogonalStartSash(sash: Sash) {
|
||||
// noop
|
||||
}
|
||||
|
||||
set orthogonalEndSash(sash: Sash) {
|
||||
// noop
|
||||
}
|
||||
|
||||
layout(size: number): void {
|
||||
this._size = size;
|
||||
return this.view.layout(this.width, this.height);
|
||||
}
|
||||
|
||||
orthogonalLayout(size: number): void {
|
||||
this._orthogonalSize = size;
|
||||
return this.view.layout(this.width, this.height);
|
||||
}
|
||||
|
||||
dispose(): void { }
|
||||
}
|
||||
|
||||
type Node = BranchNode | LeafNode;
|
||||
|
||||
function flipNode<T extends Node>(node: T, size: number, orthogonalSize: number): T {
|
||||
if (node instanceof BranchNode) {
|
||||
const result = new BranchNode(orthogonal(node.orientation), node.styles, size, orthogonalSize);
|
||||
|
||||
let totalSize = 0;
|
||||
|
||||
for (let i = node.children.length - 1; i >= 0; i--) {
|
||||
const child = node.children[i];
|
||||
const childSize = child instanceof BranchNode ? child.orthogonalSize : child.size;
|
||||
|
||||
let newSize = node.size === 0 ? 0 : Math.round((size * childSize) / node.size);
|
||||
totalSize += newSize;
|
||||
|
||||
// The last view to add should adjust to rounding errors
|
||||
if (i === 0) {
|
||||
newSize += size - totalSize;
|
||||
}
|
||||
|
||||
result.addChild(flipNode(child, orthogonalSize, newSize), newSize, 0);
|
||||
}
|
||||
|
||||
return result as T;
|
||||
} else {
|
||||
return new LeafNode((node as LeafNode).view, orthogonal(node.orientation), orthogonalSize) as T;
|
||||
}
|
||||
}
|
||||
|
||||
export class GridView implements IDisposable {
|
||||
|
||||
readonly element: HTMLElement;
|
||||
private styles: IGridViewStyles;
|
||||
|
||||
private _root: BranchNode;
|
||||
private onDidSashResetRelay = new Relay<number[]>();
|
||||
readonly onDidSashReset: Event<number[]> = this.onDidSashResetRelay.event;
|
||||
|
||||
private disposable2x2: IDisposable = Disposable.None;
|
||||
|
||||
private get root(): BranchNode {
|
||||
return this._root;
|
||||
}
|
||||
|
||||
private set root(root: BranchNode) {
|
||||
const oldRoot = this._root;
|
||||
|
||||
if (oldRoot) {
|
||||
this.element.removeChild(oldRoot.element);
|
||||
oldRoot.dispose();
|
||||
}
|
||||
|
||||
this._root = root;
|
||||
this.element.appendChild(root.element);
|
||||
this.onDidSashResetRelay.input = root.onDidSashReset;
|
||||
this._onDidChange.input = mapEvent(root.onDidChange, () => undefined); // TODO
|
||||
}
|
||||
|
||||
get orientation(): Orientation {
|
||||
return this._root.orientation;
|
||||
}
|
||||
|
||||
set orientation(orientation: Orientation) {
|
||||
if (this._root.orientation === orientation) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { size, orthogonalSize } = this._root;
|
||||
this.root = flipNode(this._root, orthogonalSize, size);
|
||||
this.root.layout(size);
|
||||
this.root.orthogonalLayout(orthogonalSize);
|
||||
}
|
||||
|
||||
get width(): number { return this.root.width; }
|
||||
get height(): number { return this.root.height; }
|
||||
|
||||
get minimumWidth(): number { return this.root.minimumWidth; }
|
||||
get minimumHeight(): number { return this.root.minimumHeight; }
|
||||
get maximumWidth(): number { return this.root.maximumHeight; }
|
||||
get maximumHeight(): number { return this.root.maximumHeight; }
|
||||
|
||||
private _onDidChange = new Relay<{ width: number; height: number; }>();
|
||||
readonly onDidChange = this._onDidChange.event;
|
||||
|
||||
constructor(options: IGridViewOptions = {}) {
|
||||
this.element = $('.monaco-grid-view');
|
||||
this.styles = options.styles || defaultStyles;
|
||||
this.root = new BranchNode(Orientation.VERTICAL, this.styles);
|
||||
}
|
||||
|
||||
style(styles: IGridViewStyles): void {
|
||||
this.styles = styles;
|
||||
this.root.style(styles);
|
||||
}
|
||||
|
||||
layout(width: number, height: number): void {
|
||||
const [size, orthogonalSize] = this.root.orientation === Orientation.HORIZONTAL ? [height, width] : [width, height];
|
||||
this.root.layout(size);
|
||||
this.root.orthogonalLayout(orthogonalSize);
|
||||
}
|
||||
|
||||
addView(view: IView, size: number | Sizing, location: number[]): void {
|
||||
this.disposable2x2.dispose();
|
||||
this.disposable2x2 = Disposable.None;
|
||||
|
||||
const [rest, index] = tail(location);
|
||||
const [pathToParent, parent] = this.getNode(rest);
|
||||
|
||||
if (parent instanceof BranchNode) {
|
||||
const node = new LeafNode(view, orthogonal(parent.orientation), parent.orthogonalSize);
|
||||
parent.addChild(node, size, index);
|
||||
|
||||
} else {
|
||||
const [, grandParent] = tail(pathToParent);
|
||||
const [, parentIndex] = tail(rest);
|
||||
grandParent.removeChild(parentIndex);
|
||||
|
||||
const newParent = new BranchNode(parent.orientation, this.styles, parent.size, parent.orthogonalSize);
|
||||
grandParent.addChild(newParent, parent.size, parentIndex);
|
||||
newParent.orthogonalLayout(parent.orthogonalSize);
|
||||
|
||||
const newSibling = new LeafNode(parent.view, grandParent.orientation, parent.size);
|
||||
newParent.addChild(newSibling, 0, 0);
|
||||
|
||||
if (typeof size !== 'number' && size.type === 'split') {
|
||||
size = Sizing.Split(0);
|
||||
}
|
||||
|
||||
const node = new LeafNode(view, grandParent.orientation, parent.size);
|
||||
newParent.addChild(node, size, index);
|
||||
}
|
||||
}
|
||||
|
||||
removeView(location: number[], sizing?: Sizing): IView {
|
||||
this.disposable2x2.dispose();
|
||||
this.disposable2x2 = Disposable.None;
|
||||
|
||||
const [rest, index] = tail(location);
|
||||
const [pathToParent, parent] = this.getNode(rest);
|
||||
|
||||
if (!(parent instanceof BranchNode)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
const node = parent.children[index];
|
||||
|
||||
if (!(node instanceof LeafNode)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
parent.removeChild(index, sizing);
|
||||
|
||||
if (parent.children.length === 0) {
|
||||
throw new Error('Invalid grid state');
|
||||
}
|
||||
|
||||
if (parent.children.length > 1) {
|
||||
return node.view;
|
||||
}
|
||||
|
||||
if (pathToParent.length === 0) { // parent is root
|
||||
const sibling = parent.children[0];
|
||||
|
||||
if (sibling instanceof LeafNode) {
|
||||
return node.view;
|
||||
}
|
||||
|
||||
// we must promote sibling to be the new root
|
||||
parent.removeChild(0);
|
||||
this.root = sibling;
|
||||
return node.view;
|
||||
}
|
||||
|
||||
const [, grandParent] = tail(pathToParent);
|
||||
const [, parentIndex] = tail(rest);
|
||||
|
||||
const sibling = parent.children[0];
|
||||
parent.removeChild(0);
|
||||
|
||||
const sizes = grandParent.children.map((_, i) => grandParent.getChildSize(i));
|
||||
grandParent.removeChild(parentIndex, sizing);
|
||||
|
||||
if (sibling instanceof BranchNode) {
|
||||
sizes.splice(parentIndex, 1, ...sibling.children.map(c => c.size));
|
||||
|
||||
for (let i = 0; i < sibling.children.length; i++) {
|
||||
const child = sibling.children[i];
|
||||
grandParent.addChild(child, child.size, parentIndex + i);
|
||||
}
|
||||
} else {
|
||||
const newSibling = new LeafNode(sibling.view, orthogonal(sibling.orientation), sibling.size);
|
||||
grandParent.addChild(newSibling, sibling.orthogonalSize, parentIndex);
|
||||
}
|
||||
|
||||
for (let i = 0; i < sizes.length; i++) {
|
||||
grandParent.resizeChild(i, sizes[i]);
|
||||
}
|
||||
|
||||
return node.view;
|
||||
}
|
||||
|
||||
swapViews(from: number[], to: number[]): void {
|
||||
const [fromRest, fromIndex] = tail(from);
|
||||
const [, fromParent] = this.getNode(fromRest);
|
||||
|
||||
if (!(fromParent instanceof BranchNode)) {
|
||||
throw new Error('Invalid from location');
|
||||
}
|
||||
|
||||
const fromSize = fromParent.getChildSize(fromIndex);
|
||||
const fromNode = fromParent.children[fromIndex];
|
||||
|
||||
if (!(fromNode instanceof LeafNode)) {
|
||||
throw new Error('Invalid from location');
|
||||
}
|
||||
|
||||
const [toRest, toIndex] = tail(to);
|
||||
const [, toParent] = this.getNode(toRest);
|
||||
|
||||
if (!(toParent instanceof BranchNode)) {
|
||||
throw new Error('Invalid to location');
|
||||
}
|
||||
|
||||
const toSize = toParent.getChildSize(toIndex);
|
||||
const toNode = toParent.children[toIndex];
|
||||
|
||||
if (!(toNode instanceof LeafNode)) {
|
||||
throw new Error('Invalid to location');
|
||||
}
|
||||
|
||||
if (fromParent === toParent) {
|
||||
fromParent.swapChildren(fromIndex, toIndex);
|
||||
} else {
|
||||
fromParent.removeChild(fromIndex);
|
||||
toParent.removeChild(toIndex);
|
||||
|
||||
fromParent.addChild(toNode, fromSize, fromIndex);
|
||||
toParent.addChild(fromNode, toSize, toIndex);
|
||||
|
||||
fromParent.layout(fromParent.orthogonalSize);
|
||||
toParent.layout(toParent.orthogonalSize);
|
||||
}
|
||||
}
|
||||
|
||||
resizeView(location: number[], size: number): void {
|
||||
const [rest, index] = tail(location);
|
||||
const [, parent] = this.getNode(rest);
|
||||
|
||||
if (!(parent instanceof BranchNode)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
parent.resizeChild(index, size);
|
||||
}
|
||||
|
||||
getViewSize(location: number[]): { width: number; height: number; } {
|
||||
const [, node] = this.getNode(location);
|
||||
return { width: node.width, height: node.height };
|
||||
}
|
||||
|
||||
maximizeViewSize(location: number[]): void {
|
||||
const [ancestors, node] = this.getNode(location);
|
||||
|
||||
if (!(node instanceof LeafNode)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
for (let i = 0; i < ancestors.length; i++) {
|
||||
ancestors[i].resizeChild(location[i], Number.POSITIVE_INFINITY);
|
||||
}
|
||||
}
|
||||
|
||||
distributeViewSizes(location?: number[]): void {
|
||||
if (!location) {
|
||||
this.root.distributeViewSizes(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const [, node] = this.getNode(location);
|
||||
|
||||
if (!(node instanceof BranchNode)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
node.distributeViewSizes();
|
||||
}
|
||||
|
||||
getViews(): GridBranchNode {
|
||||
return this._getViews(this.root, this.orientation, { top: 0, left: 0, width: this.width, height: this.height }) as GridBranchNode;
|
||||
}
|
||||
|
||||
private _getViews(node: Node, orientation: Orientation, box: Box): GridNode {
|
||||
if (node instanceof LeafNode) {
|
||||
return { view: node.view, box };
|
||||
}
|
||||
|
||||
const children: GridNode[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (let i = 0; i < node.children.length; i++) {
|
||||
const child = node.children[i];
|
||||
const childOrientation = orthogonal(orientation);
|
||||
const childBox: Box = orientation === Orientation.HORIZONTAL
|
||||
? { top: box.top, left: box.left + offset, width: child.width, height: box.height }
|
||||
: { top: box.top + offset, left: box.left, width: box.width, height: child.height };
|
||||
|
||||
children.push(this._getViews(child, childOrientation, childBox));
|
||||
offset += orientation === Orientation.HORIZONTAL ? child.width : child.height;
|
||||
}
|
||||
|
||||
return { children, box };
|
||||
}
|
||||
|
||||
private getNode(location: number[], node: Node = this.root, path: BranchNode[] = []): [BranchNode[], Node] {
|
||||
if (location.length === 0) {
|
||||
return [path, node];
|
||||
}
|
||||
|
||||
if (!(node instanceof BranchNode)) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
const [index, ...rest] = location;
|
||||
|
||||
if (index < 0 || index >= node.children.length) {
|
||||
throw new Error('Invalid location');
|
||||
}
|
||||
|
||||
const child = node.children[index];
|
||||
path.push(node);
|
||||
|
||||
return this.getNode(rest, child, path);
|
||||
}
|
||||
|
||||
trySet2x2(): void {
|
||||
this.disposable2x2.dispose();
|
||||
this.disposable2x2 = Disposable.None;
|
||||
|
||||
if (this.root.children.length !== 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [first, second] = this.root.children;
|
||||
|
||||
if (!(first instanceof BranchNode) || !(second instanceof BranchNode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposable2x2 = first.trySet2x2(second);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.onDidSashResetRelay.dispose();
|
||||
this.root.dispose();
|
||||
|
||||
if (this.element && this.element.parentElement) {
|
||||
this.element.parentElement.removeChild(this.element);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export class HighlightedLabel implements IDisposable {
|
||||
|
||||
private domNode: HTMLElement;
|
||||
private text: string;
|
||||
private title: string;
|
||||
private highlights: IHighlight[];
|
||||
private didEverRender: boolean;
|
||||
|
||||
@@ -32,11 +33,15 @@ export class HighlightedLabel implements IDisposable {
|
||||
return this.domNode;
|
||||
}
|
||||
|
||||
set(text: string, highlights: IHighlight[] = []) {
|
||||
set(text: string, highlights: IHighlight[] = [], title: string = '', escapeNewLines?: boolean) {
|
||||
if (!text) {
|
||||
text = '';
|
||||
}
|
||||
if (this.didEverRender && this.text === text && objects.equals(this.highlights, highlights)) {
|
||||
if (escapeNewLines) {
|
||||
// adjusts highlights inplace
|
||||
text = HighlightedLabel.escapeNewLines(text, highlights);
|
||||
}
|
||||
if (this.didEverRender && this.text === text && this.title === title && objects.equals(this.highlights, highlights)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -45,6 +50,7 @@ export class HighlightedLabel implements IDisposable {
|
||||
}
|
||||
|
||||
this.text = text;
|
||||
this.title = title;
|
||||
this.highlights = highlights;
|
||||
this.render();
|
||||
}
|
||||
@@ -80,6 +86,7 @@ export class HighlightedLabel implements IDisposable {
|
||||
}
|
||||
|
||||
this.domNode.innerHTML = htmlContent.join('');
|
||||
this.domNode.title = this.title;
|
||||
this.didEverRender = true;
|
||||
}
|
||||
|
||||
@@ -87,4 +94,30 @@ export class HighlightedLabel implements IDisposable {
|
||||
this.text = null;
|
||||
this.highlights = null;
|
||||
}
|
||||
|
||||
static escapeNewLines(text: string, highlights: IHighlight[]): string {
|
||||
|
||||
let total = 0;
|
||||
let extra = 0;
|
||||
|
||||
return text.replace(/\r\n|\r|\n/, (match, offset) => {
|
||||
extra = match === '\r\n' ? -1 : 0;
|
||||
offset += total;
|
||||
|
||||
for (const highlight of highlights) {
|
||||
if (highlight.end <= offset) {
|
||||
continue;
|
||||
}
|
||||
if (highlight.start >= offset) {
|
||||
highlight.start += extra;
|
||||
}
|
||||
if (highlight.end >= offset) {
|
||||
highlight.end += extra;
|
||||
}
|
||||
}
|
||||
|
||||
total += extra;
|
||||
return '\u23CE';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { IMatch } from 'vs/base/common/filters';
|
||||
import uri from 'vs/base/common/uri';
|
||||
import * as paths from 'vs/base/common/paths';
|
||||
import { IWorkspaceFolderProvider, getPathLabel, IUserHomeProvider, getBaseLabel } from 'vs/base/common/labels';
|
||||
import { IDisposable, combinedDisposable } from 'vs/base/common/lifecycle';
|
||||
import { IDisposable, combinedDisposable, Disposable } from 'vs/base/common/lifecycle';
|
||||
|
||||
export interface IIconLabelCreationOptions {
|
||||
supportHighlights?: boolean;
|
||||
@@ -22,6 +22,7 @@ export interface IIconLabelCreationOptions {
|
||||
export interface IIconLabelValueOptions {
|
||||
title?: string;
|
||||
descriptionTitle?: string;
|
||||
hideIcon?: boolean;
|
||||
extraClasses?: string[];
|
||||
italic?: boolean;
|
||||
matches?: IMatch[];
|
||||
@@ -38,11 +39,11 @@ class FastLabelNode {
|
||||
constructor(private _element: HTMLElement) {
|
||||
}
|
||||
|
||||
public get element(): HTMLElement {
|
||||
get element(): HTMLElement {
|
||||
return this._element;
|
||||
}
|
||||
|
||||
public set textContent(content: string) {
|
||||
set textContent(content: string) {
|
||||
if (this.disposed || content === this._textContent) {
|
||||
return;
|
||||
}
|
||||
@@ -51,7 +52,7 @@ class FastLabelNode {
|
||||
this._element.textContent = content;
|
||||
}
|
||||
|
||||
public set className(className: string) {
|
||||
set className(className: string) {
|
||||
if (this.disposed || className === this._className) {
|
||||
return;
|
||||
}
|
||||
@@ -60,7 +61,7 @@ class FastLabelNode {
|
||||
this._element.className = className;
|
||||
}
|
||||
|
||||
public set title(title: string) {
|
||||
set title(title: string) {
|
||||
if (this.disposed || title === this._title) {
|
||||
return;
|
||||
}
|
||||
@@ -73,7 +74,7 @@ class FastLabelNode {
|
||||
}
|
||||
}
|
||||
|
||||
public set empty(empty: boolean) {
|
||||
set empty(empty: boolean) {
|
||||
if (this.disposed || empty === this._empty) {
|
||||
return;
|
||||
}
|
||||
@@ -82,12 +83,12 @@ class FastLabelNode {
|
||||
this._element.style.marginLeft = empty ? '0' : null;
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
dispose(): void {
|
||||
this.disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
export class IconLabel {
|
||||
export class IconLabel extends Disposable {
|
||||
private domNode: FastLabelNode;
|
||||
private labelDescriptionContainer: FastLabelNode;
|
||||
private labelNode: FastLabelNode | HighlightedLabel;
|
||||
@@ -95,34 +96,36 @@ export class IconLabel {
|
||||
private descriptionNodeFactory: () => FastLabelNode | HighlightedLabel;
|
||||
|
||||
constructor(container: HTMLElement, options?: IIconLabelCreationOptions) {
|
||||
this.domNode = new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label')));
|
||||
super();
|
||||
|
||||
this.labelDescriptionContainer = new FastLabelNode(dom.append(this.domNode.element, dom.$('.monaco-icon-label-description-container')));
|
||||
this.domNode = this._register(new FastLabelNode(dom.append(container, dom.$('.monaco-icon-label'))));
|
||||
|
||||
this.labelDescriptionContainer = this._register(new FastLabelNode(dom.append(this.domNode.element, dom.$('.monaco-icon-label-description-container'))));
|
||||
|
||||
if (options && options.supportHighlights) {
|
||||
this.labelNode = new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name')));
|
||||
this.labelNode = this._register(new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name'))));
|
||||
} else {
|
||||
this.labelNode = new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name')));
|
||||
this.labelNode = this._register(new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('a.label-name'))));
|
||||
}
|
||||
|
||||
if (options && options.supportDescriptionHighlights) {
|
||||
this.descriptionNodeFactory = () => new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description')));
|
||||
this.descriptionNodeFactory = () => this._register(new HighlightedLabel(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description'))));
|
||||
} else {
|
||||
this.descriptionNodeFactory = () => new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description')));
|
||||
this.descriptionNodeFactory = () => this._register(new FastLabelNode(dom.append(this.labelDescriptionContainer.element, dom.$('span.label-description'))));
|
||||
}
|
||||
}
|
||||
|
||||
public get element(): HTMLElement {
|
||||
get element(): HTMLElement {
|
||||
return this.domNode.element;
|
||||
}
|
||||
|
||||
public onClick(callback: (event: MouseEvent) => void): IDisposable {
|
||||
onClick(callback: (event: MouseEvent) => void): IDisposable {
|
||||
return combinedDisposable([
|
||||
dom.addDisposableListener(this.labelDescriptionContainer.element, dom.EventType.CLICK, (e: MouseEvent) => callback(e)),
|
||||
]);
|
||||
}
|
||||
|
||||
public setValue(label?: string, description?: string, options?: IIconLabelValueOptions): void {
|
||||
setValue(label?: string, description?: string, options?: IIconLabelValueOptions): void {
|
||||
const classes = ['monaco-icon-label'];
|
||||
if (options) {
|
||||
if (options.extraClasses) {
|
||||
@@ -162,15 +165,6 @@ export class IconLabel {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this.domNode.dispose();
|
||||
this.labelNode.dispose();
|
||||
|
||||
if (this.descriptionNode) {
|
||||
this.descriptionNode.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class FileLabel extends IconLabel {
|
||||
@@ -181,9 +175,9 @@ export class FileLabel extends IconLabel {
|
||||
this.setFile(file, provider, userHome);
|
||||
}
|
||||
|
||||
public setFile(file: uri, provider: IWorkspaceFolderProvider, userHome: IUserHomeProvider): void {
|
||||
setFile(file: uri, provider: IWorkspaceFolderProvider, userHome: IUserHomeProvider): void {
|
||||
const parent = paths.dirname(file.fsPath);
|
||||
|
||||
this.setValue(getBaseLabel(file), parent && parent !== '.' ? getPathLabel(parent, provider, userHome) : '', { title: file.fsPath });
|
||||
this.setValue(getBaseLabel(file), parent && parent !== '.' ? getPathLabel(parent, userHome, provider) : '', { title: file.fsPath });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,6 @@
|
||||
}
|
||||
|
||||
.monaco-icon-label > .monaco-icon-label-description-container > .label-description {
|
||||
opacity: 0.7;
|
||||
margin-left: 0.5em;
|
||||
font-size: 0.9em;
|
||||
white-space: pre; /* enable to show labels that include multiple whitespaces */
|
||||
|
||||
@@ -18,6 +18,8 @@ import { Event, Emitter } from 'vs/base/common/event';
|
||||
import { Widget } from 'vs/base/browser/ui/widget';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { mixin } from 'vs/base/common/objects';
|
||||
import { HistoryNavigator } from 'vs/base/common/history';
|
||||
import { IHistoryNavigationWidget } from 'vs/base/browser/history';
|
||||
|
||||
const $ = dom.$;
|
||||
|
||||
@@ -86,7 +88,7 @@ export const defaultOpts = {
|
||||
|
||||
export class InputBox extends Widget {
|
||||
private contextViewProvider: IContextViewProvider;
|
||||
private element: HTMLElement;
|
||||
element: HTMLElement;
|
||||
private input: HTMLInputElement;
|
||||
private mirror: HTMLElement;
|
||||
private actionbar: ActionBar;
|
||||
@@ -528,4 +530,81 @@ export class InputBox extends Widget {
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface IHistoryInputOptions extends IInputOptions {
|
||||
history: string[];
|
||||
}
|
||||
|
||||
export class HistoryInputBox extends InputBox implements IHistoryNavigationWidget {
|
||||
|
||||
private readonly history: HistoryNavigator<string>;
|
||||
|
||||
constructor(container: HTMLElement, contextViewProvider: IContextViewProvider, options: IHistoryInputOptions) {
|
||||
super(container, contextViewProvider, options);
|
||||
this.history = new HistoryNavigator<string>(options.history, 100);
|
||||
}
|
||||
|
||||
public addToHistory(): void {
|
||||
if (this.value && this.value !== this.getCurrentValue()) {
|
||||
this.history.add(this.value);
|
||||
}
|
||||
}
|
||||
|
||||
public getHistory(): string[] {
|
||||
return this.history.getHistory();
|
||||
}
|
||||
|
||||
public showNextValue(): void {
|
||||
if (!this.history.has(this.value)) {
|
||||
this.addToHistory();
|
||||
}
|
||||
|
||||
let next = this.getNextValue();
|
||||
if (next) {
|
||||
next = next === this.value ? this.getNextValue() : next;
|
||||
}
|
||||
|
||||
if (next) {
|
||||
this.value = next;
|
||||
aria.status(this.value);
|
||||
}
|
||||
}
|
||||
|
||||
public showPreviousValue(): void {
|
||||
if (!this.history.has(this.value)) {
|
||||
this.addToHistory();
|
||||
}
|
||||
|
||||
let previous = this.getPreviousValue();
|
||||
if (previous) {
|
||||
previous = previous === this.value ? this.getPreviousValue() : previous;
|
||||
}
|
||||
|
||||
if (previous) {
|
||||
this.value = previous;
|
||||
aria.status(this.value);
|
||||
}
|
||||
}
|
||||
|
||||
public clearHistory(): void {
|
||||
this.history.clear();
|
||||
}
|
||||
|
||||
private getCurrentValue(): string {
|
||||
let currentValue = this.history.current();
|
||||
if (!currentValue) {
|
||||
currentValue = this.history.last();
|
||||
this.history.next();
|
||||
}
|
||||
return currentValue;
|
||||
}
|
||||
|
||||
private getPreviousValue(): string {
|
||||
return this.history.previous() || this.history.first();
|
||||
}
|
||||
|
||||
private getNextValue(): string {
|
||||
return this.history.next() || this.history.last();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import { GestureEvent } from 'vs/base/browser/touch';
|
||||
|
||||
export interface IDelegate<T> {
|
||||
export interface IVirtualDelegate<T> {
|
||||
getHeight(element: T): number;
|
||||
getTemplateId(element: T): string;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export interface IRenderer<TElement, TTemplateData> {
|
||||
templateId: string;
|
||||
renderTemplate(container: HTMLElement): TTemplateData;
|
||||
renderElement(element: TElement, index: number, templateData: TTemplateData): void;
|
||||
disposeElement(element: TElement, index: number, templateData: TTemplateData): void;
|
||||
disposeTemplate(templateData: TTemplateData): void;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import 'vs/css!./list';
|
||||
import { IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { range } from 'vs/base/common/arrays';
|
||||
import { IDelegate, IRenderer, IListEvent, IListOpenEvent } from './list';
|
||||
import { IVirtualDelegate, IRenderer, IListEvent, IListOpenEvent } from './list';
|
||||
import { List, IListStyles, IListOptions } from './listWidget';
|
||||
import { IPagedModel } from 'vs/base/common/paging';
|
||||
import { Event, mapEvent } from 'vs/base/common/event';
|
||||
@@ -50,6 +50,10 @@ class PagedRenderer<TElement, TTemplateData> implements IRenderer<number, ITempl
|
||||
promise.done(entry => this.renderer.renderElement(entry, index, data.data));
|
||||
}
|
||||
|
||||
disposeElement(): void {
|
||||
// noop
|
||||
}
|
||||
|
||||
disposeTemplate(data: ITemplateData<TTemplateData>): void {
|
||||
data.disposable.dispose();
|
||||
data.disposable = null;
|
||||
@@ -65,12 +69,12 @@ export class PagedList<T> implements IDisposable {
|
||||
|
||||
constructor(
|
||||
container: HTMLElement,
|
||||
delegate: IDelegate<number>,
|
||||
virtualDelegate: IVirtualDelegate<number>,
|
||||
renderers: IPagedRenderer<T, any>[],
|
||||
options: IListOptions<any> = {}
|
||||
) {
|
||||
const pagedRenderers = renderers.map(r => new PagedRenderer<T, ITemplateData<T>>(r, () => this.model));
|
||||
this.list = new List(container, delegate, pagedRenderers, options);
|
||||
this.list = new List(container, virtualDelegate, pagedRenderers, options);
|
||||
}
|
||||
|
||||
getHTMLElement(): HTMLElement {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { domEvent } from 'vs/base/browser/event';
|
||||
import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
|
||||
import { ScrollEvent, ScrollbarVisibility } from 'vs/base/common/scrollable';
|
||||
import { RangeMap, IRange, relativeComplement, intersect, shift } from './rangeMap';
|
||||
import { IDelegate, IRenderer, IListMouseEvent, IListTouchEvent, IListGestureEvent } from './list';
|
||||
import { IVirtualDelegate, IRenderer, IListMouseEvent, IListTouchEvent, IListGestureEvent } from './list';
|
||||
import { RowCache, IRow } from './rowCache';
|
||||
import { isWindows } from 'vs/base/common/platform';
|
||||
import * as browser from 'vs/base/browser/browser';
|
||||
@@ -29,15 +29,6 @@ function canUseTranslate3d(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
// see https://github.com/Microsoft/vscode/issues/24483
|
||||
if (browser.isChromev56) {
|
||||
const pixelRatio = browser.getPixelRatio();
|
||||
if (Math.floor(pixelRatio) !== pixelRatio) {
|
||||
// Not an integer
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -81,7 +72,7 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
|
||||
|
||||
constructor(
|
||||
container: HTMLElement,
|
||||
private delegate: IDelegate<T>,
|
||||
private virtualDelegate: IVirtualDelegate<T>,
|
||||
renderers: IRenderer<T, any>[],
|
||||
options: IListViewOptions = DefaultOptions
|
||||
) {
|
||||
@@ -165,8 +156,8 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
|
||||
const inserted = elements.map<IItem<T>>(element => ({
|
||||
id: String(this.itemId++),
|
||||
element,
|
||||
size: this.delegate.getHeight(element),
|
||||
templateId: this.delegate.getTemplateId(element),
|
||||
size: this.virtualDelegate.getHeight(element),
|
||||
templateId: this.virtualDelegate.getTemplateId(element),
|
||||
row: null
|
||||
}));
|
||||
|
||||
@@ -320,6 +311,12 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
|
||||
|
||||
private removeItemFromDOM(index: number): void {
|
||||
const item = this.items[index];
|
||||
const renderer = this.renderers.get(item.templateId);
|
||||
|
||||
if (renderer.disposeElement) {
|
||||
renderer.disposeElement(item.element, index, item.row.templateData);
|
||||
}
|
||||
|
||||
this.cache.release(item.row);
|
||||
item.row = null;
|
||||
}
|
||||
@@ -380,7 +377,12 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
|
||||
}
|
||||
|
||||
private onScroll(e: ScrollEvent): void {
|
||||
this.render(e.scrollTop, e.height);
|
||||
try {
|
||||
this.render(e.scrollTop, e.height);
|
||||
} catch (err) {
|
||||
console.log('Got bad scroll event:', e);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private onTouchChange(event: GestureEvent): void {
|
||||
@@ -493,7 +495,17 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
|
||||
// Dispose
|
||||
|
||||
dispose() {
|
||||
this.items = null;
|
||||
if (this.items) {
|
||||
for (const item of this.items) {
|
||||
if (item.row) {
|
||||
const renderer = this.renderers.get(item.row.templateId);
|
||||
renderer.disposeTemplate(item.row.templateData);
|
||||
item.row = null;
|
||||
}
|
||||
}
|
||||
|
||||
this.items = null;
|
||||
}
|
||||
|
||||
if (this._domNode && this._domNode.parentElement) {
|
||||
this._domNode.parentNode.removeChild(this._domNode);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import 'vs/css!./list';
|
||||
import { localize } from 'vs/nls';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { isNumber } from 'vs/base/common/types';
|
||||
import { range, firstIndex } from 'vs/base/common/arrays';
|
||||
@@ -15,29 +16,19 @@ import { KeyCode } from 'vs/base/common/keyCodes';
|
||||
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import { Event, Emitter, EventBufferer, chain, mapEvent, anyEvent } from 'vs/base/common/event';
|
||||
import { domEvent } from 'vs/base/browser/event';
|
||||
import { IDelegate, IRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IListOpenEvent } from './list';
|
||||
import { IVirtualDelegate, IRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IListOpenEvent } from './list';
|
||||
import { ListView, IListViewOptions } from './listView';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { mixin } from 'vs/base/common/objects';
|
||||
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
|
||||
import { ISpliceable } from 'vs/base/common/sequence';
|
||||
import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice';
|
||||
import { clamp } from 'vs/base/common/numbers';
|
||||
|
||||
export interface IIdentityProvider<T> {
|
||||
(element: T): string;
|
||||
}
|
||||
|
||||
class CombinedSpliceable<T> implements ISpliceable<T> {
|
||||
|
||||
constructor(private spliceables: ISpliceable<T>[]) { }
|
||||
|
||||
splice(start: number, deleteCount: number, elements: T[]): void {
|
||||
for (const spliceable of this.spliceables) {
|
||||
spliceable.splice(start, deleteCount, elements);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface ITraitChangeEvent {
|
||||
indexes: number[];
|
||||
}
|
||||
@@ -78,6 +69,10 @@ class TraitRenderer<T> implements IRenderer<T, ITraitTemplateData>
|
||||
this.trait.renderIndex(index, templateData);
|
||||
}
|
||||
|
||||
disposeElement(): void {
|
||||
// noop
|
||||
}
|
||||
|
||||
splice(start: number, deleteCount: number, insertCount: number): void {
|
||||
const rendered: IRenderedContainer[] = [];
|
||||
|
||||
@@ -361,6 +356,11 @@ class DOMFocusController<T> implements IDisposable {
|
||||
return;
|
||||
}
|
||||
|
||||
const style = window.getComputedStyle(tabIndexElement);
|
||||
if (style.visibility === 'hidden' || style.display === 'none') {
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
tabIndexElement.focus();
|
||||
@@ -817,6 +817,14 @@ class PipelineRenderer<T> implements IRenderer<T, any> {
|
||||
}
|
||||
}
|
||||
|
||||
disposeElement(element: T, index: number, templateData: any[]): void {
|
||||
let i = 0;
|
||||
|
||||
for (const renderer of this.renderers) {
|
||||
renderer.disposeElement(element, index, templateData[i++]);
|
||||
}
|
||||
}
|
||||
|
||||
disposeTemplate(templateData: any[]): void {
|
||||
let i = 0;
|
||||
|
||||
@@ -881,7 +889,7 @@ export class List<T> implements ISpliceable<T>, IDisposable {
|
||||
|
||||
constructor(
|
||||
container: HTMLElement,
|
||||
delegate: IDelegate<T>,
|
||||
virtualDelegate: IVirtualDelegate<T>,
|
||||
renderers: IRenderer<T, any>[],
|
||||
options: IListOptions<T> = DefaultOptions
|
||||
) {
|
||||
@@ -892,7 +900,7 @@ export class List<T> implements ISpliceable<T>, IDisposable {
|
||||
|
||||
renderers = renderers.map(r => new PipelineRenderer(r.templateId, [this.focus.renderer, this.selection.renderer, r]));
|
||||
|
||||
this.view = new ListView(container, delegate, renderers, options);
|
||||
this.view = new ListView(container, virtualDelegate, renderers, options);
|
||||
this.view.domNode.setAttribute('role', 'tree');
|
||||
DOM.addClass(this.view.domNode, this.idPrefix);
|
||||
this.view.domNode.tabIndex = 0;
|
||||
@@ -932,13 +940,21 @@ export class List<T> implements ISpliceable<T>, IDisposable {
|
||||
this.onSelectionChange(this._onSelectionChange, this, this.disposables);
|
||||
|
||||
if (options.ariaLabel) {
|
||||
this.view.domNode.setAttribute('aria-label', options.ariaLabel);
|
||||
this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", options.ariaLabel));
|
||||
}
|
||||
|
||||
this.style(options);
|
||||
}
|
||||
|
||||
splice(start: number, deleteCount: number, elements: T[] = []): void {
|
||||
if (start < 0 || start > this.view.length) {
|
||||
throw new Error(`Invalid start index: ${start}`);
|
||||
}
|
||||
|
||||
if (deleteCount < 0) {
|
||||
throw new Error(`Invalid delete count: ${deleteCount}`);
|
||||
}
|
||||
|
||||
if (deleteCount === 0 && elements.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
21
src/vs/base/browser/ui/list/splice.ts
Normal file
21
src/vs/base/browser/ui/list/splice.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import { ISpliceable } from 'vs/base/common/sequence';
|
||||
|
||||
export interface ISpreadSpliceable<T> {
|
||||
splice(start: number, deleteCount: number, ...elements: T[]): void;
|
||||
}
|
||||
|
||||
export class CombinedSpliceable<T> implements ISpliceable<T> {
|
||||
|
||||
constructor(private spliceables: ISpliceable<T>[]) { }
|
||||
|
||||
splice(start: number, deleteCount: number, elements: T[]): void {
|
||||
this.spliceables.forEach(s => s.splice(start, deleteCount, elements));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical {
|
||||
margin-left: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .actions-container {
|
||||
@@ -34,30 +35,39 @@
|
||||
background-color: #E4E4E4;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .action-item:hover:not(.disabled) {
|
||||
background-color: #EEE;
|
||||
.monaco-menu .monaco-action-bar.vertical .action-menu-item {
|
||||
-ms-flex: 1 1 auto;
|
||||
flex: 1 1 auto;
|
||||
display: -ms-flexbox;
|
||||
display: flex;
|
||||
height: 2.6em;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .action-label {
|
||||
-ms-flex: 1 1 auto;
|
||||
flex: 1 1 auto;
|
||||
text-decoration: none;
|
||||
padding: 0.8em 1em;
|
||||
line-height: 1.1em;
|
||||
padding: 0 1em;
|
||||
background: none;
|
||||
font-size: inherit;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .keybinding {
|
||||
.monaco-menu .monaco-action-bar.vertical .keybinding,
|
||||
.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
|
||||
display: inline-block;
|
||||
-ms-flex: 2 1 auto;
|
||||
flex: 2 1 auto;
|
||||
padding: 0.8em 1em;
|
||||
line-height: 1.1em;
|
||||
font-size: 12px;
|
||||
padding: 0 1em;
|
||||
text-align: right;
|
||||
font-size: inherit;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding {
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,
|
||||
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
@@ -87,6 +97,10 @@
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .action-label.checked:after {
|
||||
content: ' \2713';
|
||||
}
|
||||
|
||||
/* Context Menu */
|
||||
|
||||
.context-view.monaco-menu-container {
|
||||
@@ -103,19 +117,21 @@
|
||||
animation: fadeIn 0.083s linear;
|
||||
}
|
||||
|
||||
.context-view.monaco-menu-container :focus {
|
||||
.context-view.monaco-menu-container :focus,
|
||||
.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,
|
||||
.context-view.monaco-menu-container .monaco-action-bar.vertical :focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
.monaco-menu .monaco-action-bar.vertical .action-item {
|
||||
border: 1px solid transparent; /* prevents jumping behaviour on hover or focus */
|
||||
}
|
||||
|
||||
/* Dark theme */
|
||||
.vs-dark .monaco-menu .monaco-action-bar.vertical .action-item.focused {
|
||||
background-color: #4B4C4D;
|
||||
}
|
||||
|
||||
.vs-dark .monaco-menu .monaco-action-bar.vertical .action-item:hover:not(.disabled) {
|
||||
background-color: #3A3A3A;
|
||||
}
|
||||
|
||||
.vs-dark .context-view.monaco-menu-container {
|
||||
box-shadow: 0 2px 8px #000;
|
||||
color: #BBB;
|
||||
@@ -133,9 +149,4 @@
|
||||
.hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused {
|
||||
background: none;
|
||||
border: 1px dotted #f38518;
|
||||
}
|
||||
|
||||
.hc-black .monaco-menu .monaco-action-bar.vertical .action-item:hover:not(.disabled) {
|
||||
background: none;
|
||||
border: 1px dashed #f38518;
|
||||
}
|
||||
@@ -6,18 +6,35 @@
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./menu';
|
||||
import * as nls from 'vs/nls';
|
||||
import { IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { IActionRunner, IAction } from 'vs/base/common/actions';
|
||||
import { ActionBar, IActionItemProvider, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar';
|
||||
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
|
||||
import { IActionRunner, IAction, Action } from 'vs/base/common/actions';
|
||||
import { ActionBar, IActionItemProvider, ActionsOrientation, Separator, ActionItem, IActionItemOptions, BaseActionItem } from 'vs/base/browser/ui/actionbar/actionbar';
|
||||
import { ResolvedKeybinding, KeyCode } from 'vs/base/common/keyCodes';
|
||||
import { Event } from 'vs/base/common/event';
|
||||
import { addClass } from 'vs/base/browser/dom';
|
||||
import { addClass, EventType, EventHelper, EventLike, removeTabIndexAndUpdateFocus, isAncestor } from 'vs/base/browser/dom';
|
||||
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import { $, Builder } from 'vs/base/browser/builder';
|
||||
import { RunOnceScheduler } from 'vs/base/common/async';
|
||||
|
||||
export interface IMenuOptions {
|
||||
context?: any;
|
||||
actionItemProvider?: IActionItemProvider;
|
||||
actionRunner?: IActionRunner;
|
||||
getKeyBinding?: (action: IAction) => ResolvedKeybinding;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
|
||||
|
||||
export class SubmenuAction extends Action {
|
||||
constructor(label: string, public entries: (SubmenuAction | IAction)[], cssClass?: string) {
|
||||
super(!!cssClass ? cssClass : 'submenu', label, '', true);
|
||||
}
|
||||
}
|
||||
|
||||
interface ISubMenuData {
|
||||
parent: Menu;
|
||||
submenu?: Menu;
|
||||
}
|
||||
|
||||
export class Menu {
|
||||
@@ -27,20 +44,45 @@ export class Menu {
|
||||
|
||||
constructor(container: HTMLElement, actions: IAction[], options: IMenuOptions = {}) {
|
||||
addClass(container, 'monaco-menu-container');
|
||||
container.setAttribute('role', 'presentation');
|
||||
|
||||
let menuContainer = document.createElement('div');
|
||||
addClass(menuContainer, 'monaco-menu');
|
||||
menuContainer.setAttribute('role', 'presentation');
|
||||
container.appendChild(menuContainer);
|
||||
|
||||
let parentData: ISubMenuData = {
|
||||
parent: this
|
||||
};
|
||||
|
||||
this.actionBar = new ActionBar(menuContainer, {
|
||||
orientation: ActionsOrientation.VERTICAL,
|
||||
actionItemProvider: options.actionItemProvider,
|
||||
actionItemProvider: action => this.doGetActionItem(action, options, parentData),
|
||||
context: options.context,
|
||||
actionRunner: options.actionRunner,
|
||||
isMenu: true
|
||||
isMenu: true,
|
||||
ariaLabel: options.ariaLabel
|
||||
});
|
||||
|
||||
this.actionBar.push(actions, { icon: true, label: true });
|
||||
this.actionBar.push(actions, { icon: true, label: true, isMenu: true });
|
||||
}
|
||||
|
||||
private doGetActionItem(action: IAction, options: IMenuOptions, parentData: ISubMenuData): BaseActionItem {
|
||||
if (action instanceof Separator) {
|
||||
return new ActionItem(options.context, action, { icon: true });
|
||||
} else if (action instanceof SubmenuAction) {
|
||||
return new SubmenuActionItem(action, action.entries, parentData, options);
|
||||
} else {
|
||||
const menuItemOptions: IActionItemOptions = {};
|
||||
if (options.getKeyBinding) {
|
||||
const keybinding = options.getKeyBinding(action);
|
||||
if (keybinding) {
|
||||
menuItemOptions.keybinding = keybinding.getLabel();
|
||||
}
|
||||
}
|
||||
|
||||
return new MenuActionItem(options.context, action, menuItemOptions);
|
||||
}
|
||||
}
|
||||
|
||||
public get onDidCancel(): Event<void> {
|
||||
@@ -51,8 +93,10 @@ export class Menu {
|
||||
return this.actionBar.onDidBlur;
|
||||
}
|
||||
|
||||
public focus() {
|
||||
this.actionBar.focus(true);
|
||||
public focus(selectFirst = true) {
|
||||
if (this.actionBar) {
|
||||
this.actionBar.focus(selectFirst);
|
||||
}
|
||||
}
|
||||
|
||||
public dispose() {
|
||||
@@ -66,4 +110,277 @@ export class Menu {
|
||||
this.listener = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MenuActionItem extends BaseActionItem {
|
||||
static MNEMONIC_REGEX: RegExp = /&&(.)/g;
|
||||
|
||||
protected $e: Builder;
|
||||
protected $label: Builder;
|
||||
protected options: IActionItemOptions;
|
||||
private cssClass: string;
|
||||
|
||||
constructor(ctx: any, action: IAction, options: IActionItemOptions = {}) {
|
||||
options.isMenu = true;
|
||||
super(action, action, options);
|
||||
|
||||
this.options = options;
|
||||
this.options.icon = options.icon !== undefined ? options.icon : false;
|
||||
this.options.label = options.label !== undefined ? options.label : true;
|
||||
this.cssClass = '';
|
||||
}
|
||||
|
||||
public render(container: HTMLElement): void {
|
||||
super.render(container);
|
||||
|
||||
this.$e = $('a.action-menu-item').appendTo(this.builder);
|
||||
if (this._action.id === Separator.ID) {
|
||||
// A separator is a presentation item
|
||||
this.$e.attr({ role: 'presentation' });
|
||||
} else {
|
||||
this.$e.attr({ role: 'menuitem' });
|
||||
}
|
||||
|
||||
this.$label = $('span.action-label').appendTo(this.$e);
|
||||
|
||||
if (this.options.label && this.options.keybinding) {
|
||||
$('span.keybinding').text(this.options.keybinding).appendTo(this.$e);
|
||||
}
|
||||
|
||||
this._updateClass();
|
||||
this._updateLabel();
|
||||
this._updateTooltip();
|
||||
this._updateEnabled();
|
||||
this._updateChecked();
|
||||
}
|
||||
|
||||
public focus(): void {
|
||||
super.focus();
|
||||
this.$e.domFocus();
|
||||
}
|
||||
|
||||
public _updateLabel(): void {
|
||||
if (this.options.label) {
|
||||
let label = this.getAction().label;
|
||||
if (label) {
|
||||
let matches = MenuActionItem.MNEMONIC_REGEX.exec(label);
|
||||
if (matches && matches.length === 2) {
|
||||
let mnemonic = matches[1];
|
||||
|
||||
let ariaLabel = label.replace(MenuActionItem.MNEMONIC_REGEX, mnemonic);
|
||||
|
||||
this.$e.getHTMLElement().accessKey = mnemonic.toLocaleLowerCase();
|
||||
this.$label.attr('aria-label', ariaLabel);
|
||||
} else {
|
||||
this.$label.attr('aria-label', label);
|
||||
}
|
||||
|
||||
label = label.replace(MenuActionItem.MNEMONIC_REGEX, '$1\u0332');
|
||||
}
|
||||
|
||||
this.$label.text(label);
|
||||
}
|
||||
}
|
||||
|
||||
public _updateTooltip(): void {
|
||||
let title: string = null;
|
||||
|
||||
if (this.getAction().tooltip) {
|
||||
title = this.getAction().tooltip;
|
||||
|
||||
} else if (!this.options.label && this.getAction().label && this.options.icon) {
|
||||
title = this.getAction().label;
|
||||
|
||||
if (this.options.keybinding) {
|
||||
title = nls.localize({ key: 'titleLabel', comment: ['action title', 'action keybinding'] }, "{0} ({1})", title, this.options.keybinding);
|
||||
}
|
||||
}
|
||||
|
||||
if (title) {
|
||||
this.$e.attr({ title: title });
|
||||
}
|
||||
}
|
||||
|
||||
public _updateClass(): void {
|
||||
if (this.cssClass) {
|
||||
this.$e.removeClass(this.cssClass);
|
||||
}
|
||||
if (this.options.icon) {
|
||||
this.cssClass = this.getAction().class;
|
||||
this.$label.addClass('icon');
|
||||
if (this.cssClass) {
|
||||
this.$label.addClass(this.cssClass);
|
||||
}
|
||||
this._updateEnabled();
|
||||
} else {
|
||||
this.$label.removeClass('icon');
|
||||
}
|
||||
}
|
||||
|
||||
public _updateEnabled(): void {
|
||||
if (this.getAction().enabled) {
|
||||
this.builder.removeClass('disabled');
|
||||
this.$e.removeClass('disabled');
|
||||
this.$e.attr({ tabindex: 0 });
|
||||
} else {
|
||||
this.builder.addClass('disabled');
|
||||
this.$e.addClass('disabled');
|
||||
removeTabIndexAndUpdateFocus(this.$e.getHTMLElement());
|
||||
}
|
||||
}
|
||||
|
||||
public _updateChecked(): void {
|
||||
if (this.getAction().checked) {
|
||||
this.$label.addClass('checked');
|
||||
} else {
|
||||
this.$label.removeClass('checked');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SubmenuActionItem extends MenuActionItem {
|
||||
private mysubmenu: Menu;
|
||||
private submenuContainer: Builder;
|
||||
private mouseOver: boolean;
|
||||
private showScheduler: RunOnceScheduler;
|
||||
private hideScheduler: RunOnceScheduler;
|
||||
|
||||
constructor(
|
||||
action: IAction,
|
||||
private submenuActions: IAction[],
|
||||
private parentData: ISubMenuData,
|
||||
private submenuOptions?: IMenuOptions
|
||||
) {
|
||||
super(action, action, { label: true, isMenu: true });
|
||||
|
||||
this.showScheduler = new RunOnceScheduler(() => {
|
||||
if (this.mouseOver) {
|
||||
this.cleanupExistingSubmenu(false);
|
||||
this.createSubmenu(false);
|
||||
}
|
||||
}, 250);
|
||||
|
||||
this.hideScheduler = new RunOnceScheduler(() => {
|
||||
if ((!isAncestor(document.activeElement, this.builder.getHTMLElement()) && this.parentData.submenu === this.mysubmenu)) {
|
||||
this.parentData.parent.focus(false);
|
||||
this.cleanupExistingSubmenu(true);
|
||||
}
|
||||
}, 750);
|
||||
}
|
||||
|
||||
public render(container: HTMLElement): void {
|
||||
super.render(container);
|
||||
|
||||
this.$e.addClass('monaco-submenu-item');
|
||||
this.$e.attr('aria-haspopup', 'true');
|
||||
$('span.submenu-indicator').text('\u25B6').appendTo(this.$e);
|
||||
|
||||
$(this.builder).on(EventType.KEY_UP, (e) => {
|
||||
let event = new StandardKeyboardEvent(e as KeyboardEvent);
|
||||
if (event.equals(KeyCode.RightArrow)) {
|
||||
EventHelper.stop(e, true);
|
||||
|
||||
this.createSubmenu(true);
|
||||
}
|
||||
});
|
||||
|
||||
$(this.builder).on(EventType.KEY_DOWN, (e) => {
|
||||
let event = new StandardKeyboardEvent(e as KeyboardEvent);
|
||||
if (event.equals(KeyCode.RightArrow)) {
|
||||
EventHelper.stop(e, true);
|
||||
}
|
||||
});
|
||||
|
||||
$(this.builder).on(EventType.MOUSE_OVER, (e) => {
|
||||
if (!this.mouseOver) {
|
||||
this.mouseOver = true;
|
||||
|
||||
this.showScheduler.schedule();
|
||||
}
|
||||
});
|
||||
|
||||
$(this.builder).on(EventType.MOUSE_LEAVE, (e) => {
|
||||
this.mouseOver = false;
|
||||
});
|
||||
|
||||
$(this.builder).on(EventType.FOCUS_OUT, (e) => {
|
||||
if (!isAncestor(document.activeElement, this.builder.getHTMLElement())) {
|
||||
this.hideScheduler.schedule();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public onClick(e: EventLike) {
|
||||
// stop clicking from trying to run an action
|
||||
EventHelper.stop(e, true);
|
||||
|
||||
this.createSubmenu(false);
|
||||
}
|
||||
|
||||
private cleanupExistingSubmenu(force: boolean) {
|
||||
if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) {
|
||||
this.parentData.submenu.dispose();
|
||||
this.parentData.submenu = null;
|
||||
|
||||
if (this.submenuContainer) {
|
||||
this.submenuContainer.dispose();
|
||||
this.submenuContainer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private createSubmenu(selectFirstItem = true) {
|
||||
if (!this.parentData.submenu) {
|
||||
this.submenuContainer = $(this.builder).div({ class: 'monaco-submenu menubar-menu-items-holder context-view' });
|
||||
|
||||
$(this.submenuContainer).style({
|
||||
'left': `${$(this.builder).getClientArea().width}px`
|
||||
});
|
||||
|
||||
$(this.submenuContainer).on(EventType.KEY_UP, (e) => {
|
||||
let event = new StandardKeyboardEvent(e as KeyboardEvent);
|
||||
if (event.equals(KeyCode.LeftArrow)) {
|
||||
EventHelper.stop(e, true);
|
||||
|
||||
this.parentData.parent.focus();
|
||||
this.parentData.submenu.dispose();
|
||||
this.parentData.submenu = null;
|
||||
|
||||
this.submenuContainer.dispose();
|
||||
this.submenuContainer = null;
|
||||
}
|
||||
});
|
||||
|
||||
$(this.submenuContainer).on(EventType.KEY_DOWN, (e) => {
|
||||
let event = new StandardKeyboardEvent(e as KeyboardEvent);
|
||||
if (event.equals(KeyCode.LeftArrow)) {
|
||||
EventHelper.stop(e, true);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
this.parentData.submenu = new Menu(this.submenuContainer.getHTMLElement(), this.submenuActions, this.submenuOptions);
|
||||
this.parentData.submenu.focus(selectFirstItem);
|
||||
|
||||
this.mysubmenu = this.parentData.submenu;
|
||||
} else {
|
||||
this.parentData.submenu.focus(false);
|
||||
}
|
||||
}
|
||||
|
||||
public dispose() {
|
||||
super.dispose();
|
||||
|
||||
this.hideScheduler.dispose();
|
||||
|
||||
if (this.mysubmenu) {
|
||||
this.mysubmenu.dispose();
|
||||
this.mysubmenu = null;
|
||||
}
|
||||
|
||||
if (this.submenuContainer) {
|
||||
this.submenuContainer.dispose();
|
||||
this.submenuContainer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,13 @@
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./octicons/octicons';
|
||||
import 'vs/css!./octicons/octicons-animations';
|
||||
import { escape } from 'vs/base/common/strings';
|
||||
|
||||
function expand(text: string): string {
|
||||
return text.replace(/\$\(((.+?)(~(.*?))?)\)/g, (match, g1, name, g3, animation) => {
|
||||
return text.replace(/\$\(((.+?)(~(.*?))?)\)/g, (_match, _g1, name, _g3, animation) => {
|
||||
return `<span class="octicon octicon-${name} ${animation ? `octicon-animation-${animation}` : ''}"></span>`;
|
||||
});
|
||||
}
|
||||
@@ -20,11 +19,9 @@ export function renderOcticons(label: string): string {
|
||||
|
||||
export class OcticonLabel {
|
||||
|
||||
private readonly _container: HTMLElement;
|
||||
|
||||
constructor(container: HTMLElement) {
|
||||
this._container = container;
|
||||
}
|
||||
constructor(
|
||||
private readonly _container: HTMLElement
|
||||
) { }
|
||||
|
||||
set text(text: string) {
|
||||
this._container.innerHTML = renderOcticons(text || '');
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"version": "3.1.0",
|
||||
"license": "MIT",
|
||||
"licenseDetail": [
|
||||
"The Source EULA",
|
||||
"The MIT License (MIT)",
|
||||
"",
|
||||
"(c) 2012-2015 GitHub",
|
||||
"",
|
||||
|
||||
@@ -10,7 +10,7 @@ import { TPromise, ValueCallback } from 'vs/base/common/winjs.base';
|
||||
import * as assert from 'vs/base/common/assert';
|
||||
import { Builder, $ } from 'vs/base/browser/builder';
|
||||
import * as DOM from 'vs/base/browser/dom';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Disposable } from 'vs/base/common/lifecycle';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { mixin } from 'vs/base/common/objects';
|
||||
|
||||
@@ -35,9 +35,8 @@ const defaultOpts = {
|
||||
/**
|
||||
* A progress bar with support for infinite or discrete progress.
|
||||
*/
|
||||
export class ProgressBar {
|
||||
export class ProgressBar extends Disposable {
|
||||
private options: IProgressBarOptions;
|
||||
private toUnbind: IDisposable[];
|
||||
private workedVal: number;
|
||||
private element: Builder;
|
||||
private bit: HTMLElement;
|
||||
@@ -46,10 +45,11 @@ export class ProgressBar {
|
||||
private progressBarBackground: Color;
|
||||
|
||||
constructor(container: HTMLElement, options?: IProgressBarOptions) {
|
||||
super();
|
||||
|
||||
this.options = options || Object.create(null);
|
||||
mixin(this.options, defaultOpts, false);
|
||||
|
||||
this.toUnbind = [];
|
||||
this.workedVal = 0;
|
||||
|
||||
this.progressBarBackground = this.options.progressBarBackground;
|
||||
@@ -70,7 +70,7 @@ export class ProgressBar {
|
||||
break;
|
||||
}
|
||||
|
||||
}, this.toUnbind);
|
||||
}, this.toDispose);
|
||||
|
||||
this.bit = builder.getHTMLElement();
|
||||
});
|
||||
@@ -92,14 +92,14 @@ export class ProgressBar {
|
||||
/**
|
||||
* Indicates to the progress bar that all work is done.
|
||||
*/
|
||||
public done(): ProgressBar {
|
||||
done(): ProgressBar {
|
||||
return this.doDone(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the progressbar from showing any progress instantly without fading out.
|
||||
*/
|
||||
public stop(): ProgressBar {
|
||||
stop(): ProgressBar {
|
||||
return this.doDone(false);
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ export class ProgressBar {
|
||||
/**
|
||||
* Use this mode to indicate progress that has no total number of work units.
|
||||
*/
|
||||
public infinite(): ProgressBar {
|
||||
infinite(): ProgressBar {
|
||||
this.bit.style.width = '2%';
|
||||
this.bit.style.opacity = '1';
|
||||
|
||||
@@ -149,7 +149,7 @@ export class ProgressBar {
|
||||
* Tells the progress bar the total number of work. Use in combination with workedVal() to let
|
||||
* the progress bar show the actual progress based on the work that is done.
|
||||
*/
|
||||
public total(value: number): ProgressBar {
|
||||
total(value: number): ProgressBar {
|
||||
this.workedVal = 0;
|
||||
this.totalWork = value;
|
||||
|
||||
@@ -159,21 +159,36 @@ export class ProgressBar {
|
||||
/**
|
||||
* Finds out if this progress bar is configured with total work
|
||||
*/
|
||||
public hasTotal(): boolean {
|
||||
hasTotal(): boolean {
|
||||
return !isNaN(this.totalWork);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the progress bar that an amount of work has been completed.
|
||||
* Tells the progress bar that an increment of work has been completed.
|
||||
*/
|
||||
public worked(value: number): ProgressBar {
|
||||
assert.ok(!isNaN(this.totalWork), 'Total work not set');
|
||||
|
||||
worked(value: number): ProgressBar {
|
||||
value = Number(value);
|
||||
assert.ok(!isNaN(value), 'Value is not a number');
|
||||
value = Math.max(1, value);
|
||||
|
||||
this.workedVal += value;
|
||||
return this.doSetWorked(this.workedVal + value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the progress bar the total amount of work that has been completed.
|
||||
*/
|
||||
setWorked(value: number): ProgressBar {
|
||||
value = Number(value);
|
||||
assert.ok(!isNaN(value), 'Value is not a number');
|
||||
value = Math.max(1, value);
|
||||
|
||||
return this.doSetWorked(value);
|
||||
}
|
||||
|
||||
private doSetWorked(value: number): ProgressBar {
|
||||
assert.ok(!isNaN(this.totalWork), 'Total work not set');
|
||||
|
||||
this.workedVal = value;
|
||||
this.workedVal = Math.min(this.totalWork, this.workedVal);
|
||||
|
||||
if (this.element.hasClass(css_infinite)) {
|
||||
@@ -197,11 +212,11 @@ export class ProgressBar {
|
||||
return this;
|
||||
}
|
||||
|
||||
public getContainer(): HTMLElement {
|
||||
getContainer(): HTMLElement {
|
||||
return this.element.getHTMLElement();
|
||||
}
|
||||
|
||||
public show(delay?: number): void {
|
||||
show(delay?: number): void {
|
||||
if (typeof delay === 'number') {
|
||||
this.element.showDelayed(delay);
|
||||
} else {
|
||||
@@ -209,11 +224,11 @@ export class ProgressBar {
|
||||
}
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
hide(): void {
|
||||
this.element.hide();
|
||||
}
|
||||
|
||||
public style(styles: IProgressBarStyles): void {
|
||||
style(styles: IProgressBarStyles): void {
|
||||
this.progressBarBackground = styles.progressBarBackground;
|
||||
|
||||
this.applyStyles();
|
||||
@@ -226,8 +241,4 @@ export class ProgressBar {
|
||||
this.bit.style.backgroundColor = background;
|
||||
}
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this.toUnbind = dispose(this.toUnbind);
|
||||
}
|
||||
}
|
||||
@@ -9,28 +9,100 @@
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.monaco-sash.disabled {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.monaco-sash.vertical {
|
||||
cursor: ew-resize;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
width: 4px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.monaco-sash.mac.vertical {
|
||||
cursor: col-resize;
|
||||
}
|
||||
|
||||
.monaco-sash.vertical.minimum {
|
||||
cursor: e-resize;
|
||||
}
|
||||
|
||||
.monaco-sash.vertical.maximum {
|
||||
cursor: w-resize;
|
||||
}
|
||||
|
||||
.monaco-sash.horizontal {
|
||||
cursor: ns-resize;
|
||||
width: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
.monaco-sash.mac.horizontal {
|
||||
cursor: row-resize;
|
||||
}
|
||||
|
||||
.monaco-sash.horizontal.minimum {
|
||||
cursor: s-resize;
|
||||
}
|
||||
|
||||
.monaco-sash.horizontal.maximum {
|
||||
cursor: n-resize;
|
||||
}
|
||||
|
||||
.monaco-sash:not(.disabled).orthogonal-start::before,
|
||||
.monaco-sash:not(.disabled).orthogonal-end::after {
|
||||
content: ' ';
|
||||
height: 8px;
|
||||
width: 8px;
|
||||
z-index: 100;
|
||||
display: block;
|
||||
cursor: all-scroll;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.monaco-sash.orthogonal-start.vertical::before {
|
||||
left: -2px;
|
||||
top: -4px;
|
||||
}
|
||||
|
||||
.monaco-sash.orthogonal-end.vertical::after {
|
||||
left: -2px;
|
||||
bottom: -4px;
|
||||
}
|
||||
|
||||
.monaco-sash.orthogonal-start.horizontal::before {
|
||||
top: -2px;
|
||||
left: -4px;
|
||||
}
|
||||
|
||||
.monaco-sash.orthogonal-end.horizontal::after {
|
||||
top: -2px;
|
||||
right: -4px;
|
||||
}
|
||||
|
||||
.monaco-sash.disabled {
|
||||
cursor: default !important;
|
||||
}
|
||||
|
||||
/** Custom Mac Cursor */
|
||||
/** Touch **/
|
||||
|
||||
.monaco-sash.mac.vertical {
|
||||
cursor: col-resize;
|
||||
.monaco-sash.touch.vertical {
|
||||
width: 20px;
|
||||
}
|
||||
|
||||
.monaco-sash.mac.horizontal {
|
||||
cursor: row-resize;
|
||||
.monaco-sash.touch.horizontal {
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
/** Debug **/
|
||||
|
||||
.monaco-sash.debug:not(.disabled) {
|
||||
background: cyan;
|
||||
}
|
||||
|
||||
.monaco-sash.debug:not(.disabled).orthogonal-start::before,
|
||||
.monaco-sash.debug:not(.disabled).orthogonal-end::after {
|
||||
background: red;
|
||||
}
|
||||
@@ -6,15 +6,17 @@
|
||||
'use strict';
|
||||
|
||||
import 'vs/css!./sash';
|
||||
import { IDisposable, Disposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Builder, $ } from 'vs/base/browser/builder';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { isIPad } from 'vs/base/browser/browser';
|
||||
import { isMacintosh } from 'vs/base/common/platform';
|
||||
import * as types from 'vs/base/common/types';
|
||||
import { EventType, GestureEvent, Gesture } from 'vs/base/browser/touch';
|
||||
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
|
||||
import { Event, Emitter } from 'vs/base/common/event';
|
||||
import { getElementsByTagName, EventHelper, EventType as DOMEventType, createStyleSheet, addDisposableListener, Dimension } from 'vs/base/browser/dom';
|
||||
import { getElementsByTagName, EventHelper, createStyleSheet, addDisposableListener, append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom';
|
||||
import { domEvent } from 'vs/base/browser/event';
|
||||
|
||||
const DEBUG = false;
|
||||
|
||||
export interface ISashLayoutProvider { }
|
||||
|
||||
@@ -39,8 +41,9 @@ export interface ISashEvent {
|
||||
}
|
||||
|
||||
export interface ISashOptions {
|
||||
baseSize?: number;
|
||||
orientation?: Orientation;
|
||||
orthogonalStartSash?: Sash;
|
||||
orthogonalEndSash?: Sash;
|
||||
}
|
||||
|
||||
export enum Orientation {
|
||||
@@ -48,72 +51,123 @@ export enum Orientation {
|
||||
HORIZONTAL
|
||||
}
|
||||
|
||||
export enum SashState {
|
||||
Disabled,
|
||||
Minimum,
|
||||
Maximum,
|
||||
Enabled
|
||||
}
|
||||
|
||||
export class Sash {
|
||||
|
||||
private $e: Builder;
|
||||
private el: HTMLElement;
|
||||
private layoutProvider: ISashLayoutProvider;
|
||||
private isDisabled: boolean;
|
||||
private hidden: boolean;
|
||||
private orientation: Orientation;
|
||||
private size: number;
|
||||
private disposables: IDisposable[] = [];
|
||||
|
||||
private _onDidStart = new Emitter<ISashEvent>();
|
||||
private _onDidChange = new Emitter<ISashEvent>();
|
||||
private _onDidReset = new Emitter<void>();
|
||||
private _onDidEnd = new Emitter<void>();
|
||||
|
||||
constructor(container: HTMLElement, layoutProvider: ISashLayoutProvider, options: ISashOptions = {}) {
|
||||
this.$e = $('.monaco-sash').appendTo(container);
|
||||
|
||||
if (isMacintosh) {
|
||||
this.$e.addClass('mac');
|
||||
private _state: SashState = SashState.Enabled;
|
||||
get state(): SashState { return this._state; }
|
||||
set state(state: SashState) {
|
||||
if (this._state === state) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.$e.on(DOMEventType.MOUSE_DOWN, (e) => { this.onMouseDown(e as MouseEvent); });
|
||||
this.$e.on(DOMEventType.DBLCLICK, (e) => this._onDidReset.fire());
|
||||
Gesture.addTarget(this.$e.getHTMLElement());
|
||||
this.$e.on(EventType.Start, (e) => { this.onTouchStart(e as GestureEvent); });
|
||||
toggleClass(this.el, 'disabled', state === SashState.Disabled);
|
||||
toggleClass(this.el, 'minimum', state === SashState.Minimum);
|
||||
toggleClass(this.el, 'maximum', state === SashState.Maximum);
|
||||
|
||||
this.size = options.baseSize || 5;
|
||||
this._state = state;
|
||||
this._onDidEnablementChange.fire(state);
|
||||
}
|
||||
|
||||
private readonly _onDidEnablementChange = new Emitter<SashState>();
|
||||
readonly onDidEnablementChange: Event<SashState> = this._onDidEnablementChange.event;
|
||||
|
||||
private readonly _onDidStart = new Emitter<ISashEvent>();
|
||||
readonly onDidStart: Event<ISashEvent> = this._onDidStart.event;
|
||||
|
||||
private readonly _onDidChange = new Emitter<ISashEvent>();
|
||||
readonly onDidChange: Event<ISashEvent> = this._onDidChange.event;
|
||||
|
||||
private readonly _onDidReset = new Emitter<void>();
|
||||
readonly onDidReset: Event<void> = this._onDidReset.event;
|
||||
|
||||
private readonly _onDidEnd = new Emitter<void>();
|
||||
readonly onDidEnd: Event<void> = this._onDidEnd.event;
|
||||
|
||||
linkedSash: Sash | undefined = undefined;
|
||||
|
||||
private orthogonalStartSashDisposables: IDisposable[] = [];
|
||||
private _orthogonalStartSash: Sash | undefined;
|
||||
get orthogonalStartSash(): Sash | undefined { return this._orthogonalStartSash; }
|
||||
set orthogonalStartSash(sash: Sash | undefined) {
|
||||
this.orthogonalStartSashDisposables = dispose(this.orthogonalStartSashDisposables);
|
||||
|
||||
if (sash) {
|
||||
sash.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange, this, this.orthogonalStartSashDisposables);
|
||||
this.onOrthogonalStartSashEnablementChange(sash.state);
|
||||
} else {
|
||||
this.onOrthogonalStartSashEnablementChange(SashState.Disabled);
|
||||
}
|
||||
|
||||
this._orthogonalStartSash = sash;
|
||||
}
|
||||
|
||||
private orthogonalEndSashDisposables: IDisposable[] = [];
|
||||
private _orthogonalEndSash: Sash | undefined;
|
||||
get orthogonalEndSash(): Sash | undefined { return this._orthogonalEndSash; }
|
||||
set orthogonalEndSash(sash: Sash | undefined) {
|
||||
this.orthogonalEndSashDisposables = dispose(this.orthogonalEndSashDisposables);
|
||||
|
||||
if (sash) {
|
||||
sash.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange, this, this.orthogonalEndSashDisposables);
|
||||
this.onOrthogonalEndSashEnablementChange(sash.state);
|
||||
} else {
|
||||
this.onOrthogonalEndSashEnablementChange(SashState.Disabled);
|
||||
}
|
||||
|
||||
this._orthogonalEndSash = sash;
|
||||
}
|
||||
|
||||
constructor(container: HTMLElement, layoutProvider: ISashLayoutProvider, options: ISashOptions = {}) {
|
||||
this.el = append(container, $('.monaco-sash'));
|
||||
|
||||
if (isMacintosh) {
|
||||
addClass(this.el, 'mac');
|
||||
}
|
||||
|
||||
domEvent(this.el, 'mousedown')(this.onMouseDown, this, this.disposables);
|
||||
domEvent(this.el, 'dblclick')(this.onMouseDoubleClick, this, this.disposables);
|
||||
|
||||
Gesture.addTarget(this.el);
|
||||
domEvent(this.el, EventType.Start)(this.onTouchStart, this, this.disposables);
|
||||
|
||||
if (isIPad) {
|
||||
this.size *= 4; // see also http://ux.stackexchange.com/questions/39023/what-is-the-optimum-button-size-of-touch-screen-applications
|
||||
this.$e.addClass('touch');
|
||||
// see also http://ux.stackexchange.com/questions/39023/what-is-the-optimum-button-size-of-touch-screen-applications
|
||||
addClass(this.el, 'touch');
|
||||
}
|
||||
|
||||
this.setOrientation(options.orientation || Orientation.VERTICAL);
|
||||
|
||||
this.isDisabled = false;
|
||||
this.hidden = false;
|
||||
this.layoutProvider = layoutProvider;
|
||||
|
||||
this.orthogonalStartSash = options.orthogonalStartSash;
|
||||
this.orthogonalEndSash = options.orthogonalEndSash;
|
||||
|
||||
toggleClass(this.el, 'debug', DEBUG);
|
||||
}
|
||||
|
||||
public get onDidStart(): Event<ISashEvent> {
|
||||
return this._onDidStart.event;
|
||||
}
|
||||
|
||||
public get onDidChange(): Event<ISashEvent> {
|
||||
return this._onDidChange.event;
|
||||
}
|
||||
|
||||
public get onDidReset(): Event<void> {
|
||||
return this._onDidReset.event;
|
||||
}
|
||||
|
||||
public get onDidEnd(): Event<void> {
|
||||
return this._onDidEnd.event;
|
||||
}
|
||||
|
||||
public setOrientation(orientation: Orientation): void {
|
||||
setOrientation(orientation: Orientation): void {
|
||||
this.orientation = orientation;
|
||||
|
||||
this.$e.removeClass('horizontal', 'vertical');
|
||||
this.$e.addClass(this.getOrientation());
|
||||
|
||||
if (this.orientation === Orientation.HORIZONTAL) {
|
||||
this.$e.size(null, this.size);
|
||||
addClass(this.el, 'horizontal');
|
||||
removeClass(this.el, 'vertical');
|
||||
} else {
|
||||
this.$e.size(this.size);
|
||||
removeClass(this.el, 'horizontal');
|
||||
addClass(this.el, 'vertical');
|
||||
}
|
||||
|
||||
if (this.layoutProvider) {
|
||||
@@ -121,76 +175,124 @@ export class Sash {
|
||||
}
|
||||
}
|
||||
|
||||
private getOrientation(): 'horizontal' | 'vertical' {
|
||||
return this.orientation === Orientation.HORIZONTAL ? 'horizontal' : 'vertical';
|
||||
}
|
||||
|
||||
private onMouseDown(e: MouseEvent): void {
|
||||
EventHelper.stop(e, false);
|
||||
|
||||
if (this.isDisabled) {
|
||||
let isMultisashResize = false;
|
||||
|
||||
if (this.linkedSash && !(e as any).__linkedSashEvent) {
|
||||
(e as any).__linkedSashEvent = true;
|
||||
this.linkedSash.onMouseDown(e);
|
||||
}
|
||||
|
||||
if (!(e as any).__orthogonalSashEvent) {
|
||||
let orthogonalSash: Sash | undefined;
|
||||
|
||||
if (this.orientation === Orientation.VERTICAL) {
|
||||
if (e.offsetY <= 4) {
|
||||
orthogonalSash = this.orthogonalStartSash;
|
||||
} else if (e.offsetY >= this.el.clientHeight - 4) {
|
||||
orthogonalSash = this.orthogonalEndSash;
|
||||
}
|
||||
} else {
|
||||
if (e.offsetX <= 4) {
|
||||
orthogonalSash = this.orthogonalStartSash;
|
||||
} else if (e.offsetX >= this.el.clientWidth - 4) {
|
||||
orthogonalSash = this.orthogonalEndSash;
|
||||
}
|
||||
}
|
||||
|
||||
if (orthogonalSash) {
|
||||
isMultisashResize = true;
|
||||
(e as any).__orthogonalSashEvent = true;
|
||||
orthogonalSash.onMouseDown(e);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.state) {
|
||||
return;
|
||||
}
|
||||
|
||||
const iframes = $(getElementsByTagName('iframe'));
|
||||
if (iframes) {
|
||||
iframes.style('pointer-events', 'none'); // disable mouse events on iframes as long as we drag the sash
|
||||
const iframes = getElementsByTagName('iframe');
|
||||
for (const iframe of iframes) {
|
||||
iframe.style.pointerEvents = 'none'; // disable mouse events on iframes as long as we drag the sash
|
||||
}
|
||||
|
||||
const mouseDownEvent = new StandardMouseEvent(e);
|
||||
const startX = mouseDownEvent.posx;
|
||||
const startY = mouseDownEvent.posy;
|
||||
const altKey = mouseDownEvent.altKey;
|
||||
const startEvent: ISashEvent = { startX, currentX: startX, startY, currentY: startY, altKey };
|
||||
|
||||
const startEvent: ISashEvent = {
|
||||
startX: startX,
|
||||
currentX: startX,
|
||||
startY: startY,
|
||||
currentY: startY,
|
||||
altKey
|
||||
};
|
||||
|
||||
this.$e.addClass('active');
|
||||
addClass(this.el, 'active');
|
||||
this._onDidStart.fire(startEvent);
|
||||
|
||||
const $window = $(window);
|
||||
|
||||
// fix https://github.com/Microsoft/vscode/issues/21675
|
||||
const globalStyle = createStyleSheet(this.$e.getHTMLElement());
|
||||
if (this.orientation === Orientation.HORIZONTAL) {
|
||||
globalStyle.innerHTML = `* { cursor: ${isMacintosh ? 'row-resize' : 'ns-resize'}; }`;
|
||||
} else {
|
||||
globalStyle.innerHTML = `* { cursor: ${isMacintosh ? 'col-resize' : 'ew-resize'}; }`;
|
||||
const style = createStyleSheet(this.el);
|
||||
const updateStyle = () => {
|
||||
let cursor = '';
|
||||
|
||||
if (isMultisashResize) {
|
||||
cursor = 'all-scroll';
|
||||
} else if (this.orientation === Orientation.HORIZONTAL) {
|
||||
if (this.state === SashState.Minimum) {
|
||||
cursor = 's-resize';
|
||||
} else if (this.state === SashState.Maximum) {
|
||||
cursor = 'n-resize';
|
||||
} else {
|
||||
cursor = isMacintosh ? 'row-resize' : 'ns-resize';
|
||||
}
|
||||
} else {
|
||||
if (this.state === SashState.Minimum) {
|
||||
cursor = 'e-resize';
|
||||
} else if (this.state === SashState.Maximum) {
|
||||
cursor = 'w-resize';
|
||||
} else {
|
||||
cursor = isMacintosh ? 'col-resize' : 'ew-resize';
|
||||
}
|
||||
}
|
||||
|
||||
style.innerHTML = `* { cursor: ${cursor} !important; }`;
|
||||
};
|
||||
|
||||
const disposables: IDisposable[] = [];
|
||||
|
||||
updateStyle();
|
||||
|
||||
if (!isMultisashResize) {
|
||||
this.onDidEnablementChange(updateStyle, null, disposables);
|
||||
}
|
||||
|
||||
$window.on('mousemove', (e) => {
|
||||
const onMouseMove = (e: MouseEvent) => {
|
||||
EventHelper.stop(e, false);
|
||||
const mouseMoveEvent = new StandardMouseEvent(e as MouseEvent);
|
||||
|
||||
const event: ISashEvent = {
|
||||
startX: startX,
|
||||
currentX: mouseMoveEvent.posx,
|
||||
startY: startY,
|
||||
currentY: mouseMoveEvent.posy,
|
||||
altKey
|
||||
};
|
||||
const event: ISashEvent = { startX, currentX: mouseMoveEvent.posx, startY, currentY: mouseMoveEvent.posy, altKey };
|
||||
|
||||
this._onDidChange.fire(event);
|
||||
}).once('mouseup', (e) => {
|
||||
};
|
||||
|
||||
const onMouseUp = (e: MouseEvent) => {
|
||||
EventHelper.stop(e, false);
|
||||
|
||||
this.$e.getHTMLElement().removeChild(globalStyle);
|
||||
this.el.removeChild(style);
|
||||
|
||||
this.$e.removeClass('active');
|
||||
removeClass(this.el, 'active');
|
||||
this._onDidEnd.fire();
|
||||
|
||||
$window.off('mousemove');
|
||||
dispose(disposables);
|
||||
|
||||
const iframes = $(getElementsByTagName('iframe'));
|
||||
if (iframes) {
|
||||
iframes.style('pointer-events', 'auto');
|
||||
const iframes = getElementsByTagName('iframe');
|
||||
for (const iframe of iframes) {
|
||||
iframe.style.pointerEvents = 'auto';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
domEvent(window, 'mousemove')(onMouseMove, null, disposables);
|
||||
domEvent(window, 'mouseup')(onMouseUp, null, disposables);
|
||||
}
|
||||
|
||||
private onMouseDoubleClick(event: MouseEvent): void {
|
||||
this._onDidReset.fire();
|
||||
}
|
||||
|
||||
private onTouchStart(event: GestureEvent): void {
|
||||
@@ -202,7 +304,6 @@ export class Sash {
|
||||
const startY = event.pageY;
|
||||
const altKey = event.altKey;
|
||||
|
||||
|
||||
this._onDidStart.fire({
|
||||
startX: startX,
|
||||
currentX: startX,
|
||||
@@ -211,7 +312,7 @@ export class Sash {
|
||||
altKey
|
||||
});
|
||||
|
||||
listeners.push(addDisposableListener(this.$e.getHTMLElement(), EventType.Change, (event: GestureEvent) => {
|
||||
listeners.push(addDisposableListener(this.el, EventType.Change, (event: GestureEvent) => {
|
||||
if (types.isNumber(event.pageX) && types.isNumber(event.pageY)) {
|
||||
this._onDidChange.fire({
|
||||
startX: startX,
|
||||
@@ -223,163 +324,73 @@ export class Sash {
|
||||
}
|
||||
}));
|
||||
|
||||
listeners.push(addDisposableListener(this.$e.getHTMLElement(), EventType.End, (event: GestureEvent) => {
|
||||
listeners.push(addDisposableListener(this.el, EventType.End, (event: GestureEvent) => {
|
||||
this._onDidEnd.fire();
|
||||
dispose(listeners);
|
||||
}));
|
||||
}
|
||||
|
||||
public layout(): void {
|
||||
let style: { top?: string; left?: string; height?: string; width?: string; };
|
||||
layout(): void {
|
||||
const size = isIPad ? 20 : 4;
|
||||
|
||||
if (this.orientation === Orientation.VERTICAL) {
|
||||
const verticalProvider = (<IVerticalSashLayoutProvider>this.layoutProvider);
|
||||
style = { left: verticalProvider.getVerticalSashLeft(this) - (this.size / 2) + 'px' };
|
||||
this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (size / 2) + 'px';
|
||||
|
||||
if (verticalProvider.getVerticalSashTop) {
|
||||
style.top = verticalProvider.getVerticalSashTop(this) + 'px';
|
||||
this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px';
|
||||
}
|
||||
|
||||
if (verticalProvider.getVerticalSashHeight) {
|
||||
style.height = verticalProvider.getVerticalSashHeight(this) + 'px';
|
||||
this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px';
|
||||
}
|
||||
} else {
|
||||
const horizontalProvider = (<IHorizontalSashLayoutProvider>this.layoutProvider);
|
||||
style = { top: horizontalProvider.getHorizontalSashTop(this) - (this.size / 2) + 'px' };
|
||||
this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (size / 2) + 'px';
|
||||
|
||||
if (horizontalProvider.getHorizontalSashLeft) {
|
||||
style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px';
|
||||
this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px';
|
||||
}
|
||||
|
||||
if (horizontalProvider.getHorizontalSashWidth) {
|
||||
style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px';
|
||||
this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px';
|
||||
}
|
||||
}
|
||||
|
||||
this.$e.style(style);
|
||||
}
|
||||
|
||||
public show(): void {
|
||||
show(): void {
|
||||
this.hidden = false;
|
||||
this.$e.show();
|
||||
this.el.style.removeProperty('display');
|
||||
this.el.setAttribute('aria-hidden', 'false');
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
hide(): void {
|
||||
this.hidden = true;
|
||||
this.$e.hide();
|
||||
this.el.style.display = 'none';
|
||||
this.el.setAttribute('aria-hidden', 'true');
|
||||
}
|
||||
|
||||
public isHidden(): boolean {
|
||||
isHidden(): boolean {
|
||||
return this.hidden;
|
||||
}
|
||||
|
||||
public enable(): void {
|
||||
this.$e.removeClass('disabled');
|
||||
this.isDisabled = false;
|
||||
private onOrthogonalStartSashEnablementChange(state: SashState): void {
|
||||
toggleClass(this.el, 'orthogonal-start', state !== SashState.Disabled);
|
||||
}
|
||||
|
||||
public disable(): void {
|
||||
this.$e.addClass('disabled');
|
||||
this.isDisabled = true;
|
||||
private onOrthogonalEndSashEnablementChange(state: SashState): void {
|
||||
toggleClass(this.el, 'orthogonal-end', state !== SashState.Disabled);
|
||||
}
|
||||
|
||||
get enabled(): boolean {
|
||||
return !this.isDisabled;
|
||||
}
|
||||
dispose(): void {
|
||||
this.orthogonalStartSashDisposables = dispose(this.orthogonalStartSashDisposables);
|
||||
this.orthogonalEndSashDisposables = dispose(this.orthogonalEndSashDisposables);
|
||||
|
||||
public dispose(): void {
|
||||
if (this.$e) {
|
||||
this.$e.destroy();
|
||||
this.$e = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple Vertical Sash that computes the position of the sash when it is moved between the given dimension.
|
||||
* Triggers onPositionChange event when the position is changed
|
||||
*/
|
||||
export class VSash extends Disposable implements IVerticalSashLayoutProvider {
|
||||
private sash: Sash;
|
||||
private ratio: number;
|
||||
private startPosition: number;
|
||||
private position: number;
|
||||
private dimension: Dimension;
|
||||
|
||||
private readonly _onPositionChange: Emitter<number> = new Emitter<number>();
|
||||
public get onPositionChange(): Event<number> { return this._onPositionChange.event; }
|
||||
|
||||
constructor(container: HTMLElement, private minWidth: number) {
|
||||
super();
|
||||
|
||||
this.ratio = 0.5;
|
||||
this.sash = new Sash(container, this);
|
||||
|
||||
this._register(this.sash.onDidStart(() => this.onSashDragStart()));
|
||||
this._register(this.sash.onDidChange((e: ISashEvent) => this.onSashDrag(e)));
|
||||
this._register(this.sash.onDidEnd(() => this.onSashDragEnd()));
|
||||
this._register(this.sash.onDidReset(() => this.onSashReset()));
|
||||
}
|
||||
|
||||
public getVerticalSashTop(): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public getVerticalSashLeft(): number {
|
||||
return this.position;
|
||||
}
|
||||
|
||||
public getVerticalSashHeight(): number {
|
||||
return this.dimension.height;
|
||||
}
|
||||
|
||||
public setDimenesion(dimension: Dimension) {
|
||||
this.dimension = dimension;
|
||||
this.compute(this.ratio);
|
||||
}
|
||||
|
||||
private onSashDragStart(): void {
|
||||
this.startPosition = this.position;
|
||||
}
|
||||
|
||||
private onSashDrag(e: ISashEvent): void {
|
||||
this.compute((this.startPosition + (e.currentX - e.startX)) / this.dimension.width);
|
||||
}
|
||||
|
||||
private compute(ratio: number) {
|
||||
this.computeSashPosition(ratio);
|
||||
this.ratio = this.position / this.dimension.width;
|
||||
this._onPositionChange.fire(this.position);
|
||||
}
|
||||
|
||||
private onSashDragEnd(): void {
|
||||
this.sash.layout();
|
||||
}
|
||||
|
||||
private onSashReset(): void {
|
||||
this.compute(0.5);
|
||||
this._onPositionChange.fire(this.position);
|
||||
this.sash.layout();
|
||||
}
|
||||
|
||||
private computeSashPosition(sashRatio: number = this.ratio) {
|
||||
const contentWidth = this.dimension.width;
|
||||
let sashPosition = Math.floor((sashRatio || 0.5) * contentWidth);
|
||||
const midPoint = Math.floor(0.5 * contentWidth);
|
||||
|
||||
if (contentWidth > this.minWidth * 2) {
|
||||
if (sashPosition < this.minWidth) {
|
||||
sashPosition = this.minWidth;
|
||||
}
|
||||
if (sashPosition > contentWidth - this.minWidth) {
|
||||
sashPosition = contentWidth - this.minWidth;
|
||||
}
|
||||
} else {
|
||||
sashPosition = midPoint;
|
||||
}
|
||||
if (this.position !== sashPosition) {
|
||||
this.position = sashPosition;
|
||||
this.sash.layout();
|
||||
if (this.el && this.el.parentElement) {
|
||||
this.el.parentElement.removeChild(this.el);
|
||||
}
|
||||
|
||||
this.el = null;
|
||||
this.disposables = dispose(this.disposables);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +163,8 @@ export abstract class AbstractScrollableElement extends Widget {
|
||||
private readonly _hideTimeout: TimeoutTimer;
|
||||
private _shouldRender: boolean;
|
||||
|
||||
private _revealOnScroll: boolean;
|
||||
|
||||
private readonly _onScroll = this._register(new Emitter<ScrollEvent>());
|
||||
public readonly onScroll: Event<ScrollEvent> = this._onScroll.event;
|
||||
|
||||
@@ -221,6 +223,8 @@ export abstract class AbstractScrollableElement extends Widget {
|
||||
this._mouseIsOver = false;
|
||||
|
||||
this._shouldRender = true;
|
||||
|
||||
this._revealOnScroll = true;
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
@@ -286,6 +290,10 @@ export abstract class AbstractScrollableElement extends Widget {
|
||||
}
|
||||
}
|
||||
|
||||
public setRevealOnScroll(value: boolean) {
|
||||
this._revealOnScroll = value;
|
||||
}
|
||||
|
||||
// -------------------- mouse wheel scrolling --------------------
|
||||
|
||||
private _setListeningToMouseWheel(shouldListen: boolean): void {
|
||||
@@ -382,7 +390,9 @@ export abstract class AbstractScrollableElement extends Widget {
|
||||
this._shouldRender = true;
|
||||
}
|
||||
|
||||
this._reveal();
|
||||
if (this._revealOnScroll) {
|
||||
this._reveal();
|
||||
}
|
||||
|
||||
if (!this._options.lazyRender) {
|
||||
this._render();
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
import 'vs/css!./selectBox';
|
||||
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Event } from 'vs/base/common/event';
|
||||
import { Widget } from 'vs/base/browser/ui/widget';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
@@ -24,6 +23,7 @@ export interface ISelectBoxDelegate {
|
||||
readonly onDidSelect: Event<ISelectData>;
|
||||
setOptions(options: string[], selected?: number, disabled?: number): void;
|
||||
select(index: number): void;
|
||||
setAriaLabel(label: string);
|
||||
focus(): void;
|
||||
blur(): void;
|
||||
dispose(): void;
|
||||
@@ -35,7 +35,6 @@ export interface ISelectBoxDelegate {
|
||||
}
|
||||
|
||||
export interface ISelectBoxOptions {
|
||||
// {{SQL CARBON EDIT}}
|
||||
ariaLabel?: string;
|
||||
minBottomMargin?: number;
|
||||
}
|
||||
@@ -65,15 +64,12 @@ export class SelectBox extends Widget implements ISelectBoxDelegate {
|
||||
protected selectBackground: Color;
|
||||
protected selectForeground: Color;
|
||||
protected selectBorder: Color;
|
||||
private toDispose: IDisposable[];
|
||||
private styles: ISelectBoxStyles;
|
||||
private selectBoxDelegate: ISelectBoxDelegate;
|
||||
|
||||
constructor(options: string[], selected: number, contextViewProvider: IContextViewProvider, styles: ISelectBoxStyles = deepClone(defaultStyles), selectBoxOptions?: ISelectBoxOptions) {
|
||||
super();
|
||||
|
||||
this.toDispose = [];
|
||||
|
||||
mixin(this.styles, defaultStyles, false);
|
||||
|
||||
// Instantiate select implementation based on platform
|
||||
@@ -87,7 +83,7 @@ export class SelectBox extends Widget implements ISelectBoxDelegate {
|
||||
// {{SQL CARBON EDIT}}
|
||||
this.selectElement = (<any>this.selectBoxDelegate).selectElement;
|
||||
|
||||
this.toDispose.push(this.selectBoxDelegate);
|
||||
this._register(this.selectBoxDelegate);
|
||||
}
|
||||
|
||||
// Public SelectBox Methods - routed through delegate interface
|
||||
@@ -104,6 +100,10 @@ export class SelectBox extends Widget implements ISelectBoxDelegate {
|
||||
this.selectBoxDelegate.select(index);
|
||||
}
|
||||
|
||||
public setAriaLabel(label: string): void {
|
||||
this.selectBoxDelegate.setAriaLabel(label);
|
||||
}
|
||||
|
||||
public focus(): void {
|
||||
this.selectBoxDelegate.focus();
|
||||
}
|
||||
@@ -125,7 +125,6 @@ export class SelectBox extends Widget implements ISelectBoxDelegate {
|
||||
public applyStyles(): void {
|
||||
this.selectBoxDelegate.applyStyles();
|
||||
}
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
protected createOption(value: string, disabled?: boolean): HTMLOptionElement {
|
||||
let option = document.createElement('option');
|
||||
@@ -136,8 +135,4 @@ export class SelectBox extends Widget implements ISelectBoxDelegate {
|
||||
return option;
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this.toDispose = dispose(this.toDispose);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,17 @@
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
/* Use custom CSS vars to expose padding into parent select for padding calculation */
|
||||
.monaco-select-box-dropdown-padding {
|
||||
--dropdown-padding-top: 1px;
|
||||
--dropdown-padding-bottom: 1px;
|
||||
}
|
||||
|
||||
.hc-black .monaco-select-box-dropdown-padding {
|
||||
--dropdown-padding-top: 3px;
|
||||
--dropdown-padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.monaco-select-box-dropdown-container {
|
||||
display: none;
|
||||
}
|
||||
@@ -18,8 +29,8 @@
|
||||
.monaco-select-box-dropdown-container > .select-box-dropdown-list-container {
|
||||
flex: 0 0 auto;
|
||||
align-self: flex-start;
|
||||
padding-bottom: 1px;
|
||||
padding-top: 1px;
|
||||
padding-top: var(--dropdown-padding-top);
|
||||
padding-bottom: var(--dropdown-padding-bottom);
|
||||
padding-left: 1px;
|
||||
padding-right: 1px;
|
||||
width: 100%;
|
||||
@@ -32,8 +43,8 @@
|
||||
}
|
||||
|
||||
.hc-black .monaco-select-box-dropdown-container > .select-box-dropdown-list-container {
|
||||
padding-bottom: 4px;
|
||||
padding-top: 3px;
|
||||
padding-top: var(--dropdown-padding-top);
|
||||
padding-bottom: var(--dropdown-padding-bottom);
|
||||
}
|
||||
|
||||
.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .option-text {
|
||||
|
||||
@@ -12,9 +12,9 @@ import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes';
|
||||
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import * as dom from 'vs/base/browser/dom';
|
||||
import * as arrays from 'vs/base/common/arrays';
|
||||
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
|
||||
import { IContextViewProvider, AnchorPosition } from 'vs/base/browser/ui/contextview/contextview';
|
||||
import { List } from 'vs/base/browser/ui/list/listWidget';
|
||||
import { IDelegate, IRenderer } from 'vs/base/browser/ui/list/list';
|
||||
import { IVirtualDelegate, IRenderer } from 'vs/base/browser/ui/list/list';
|
||||
import { domEvent } from 'vs/base/browser/event';
|
||||
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
|
||||
import { ISelectBoxDelegate, ISelectBoxOptions, ISelectBoxStyles, ISelectData } from 'vs/base/browser/ui/selectBox/selectBox';
|
||||
@@ -58,6 +58,9 @@ class SelectListRenderer implements IRenderer<ISelectOptionItem, ISelectListTemp
|
||||
data.optionText.textContent = optionText;
|
||||
data.root.setAttribute('aria-label', nls.localize('selectAriaOption', "{0}", optionText));
|
||||
|
||||
// Workaround for list labels
|
||||
data.root.setAttribute('aria-selected', 'true');
|
||||
|
||||
// pseudo-select disabled option
|
||||
if (optionDisabled) {
|
||||
dom.addClass((<HTMLElement>data.root), 'option-disabled');
|
||||
@@ -67,14 +70,20 @@ class SelectListRenderer implements IRenderer<ISelectOptionItem, ISelectListTemp
|
||||
}
|
||||
}
|
||||
|
||||
disposeElement(): void {
|
||||
// noop
|
||||
}
|
||||
|
||||
disposeTemplate(templateData: ISelectListTemplateData): void {
|
||||
templateData.disposables = dispose(templateData.disposables);
|
||||
}
|
||||
}
|
||||
|
||||
export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptionItem> {
|
||||
export class SelectBoxList implements ISelectBoxDelegate, IVirtualDelegate<ISelectOptionItem> {
|
||||
|
||||
private static readonly DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN = 32;
|
||||
private static readonly DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN = 42;
|
||||
private static readonly DEFAULT_MINIMUM_VISIBLE_OPTIONS = 3;
|
||||
|
||||
private _isVisible: boolean;
|
||||
private selectBoxOptions: ISelectBoxOptions;
|
||||
@@ -94,6 +103,7 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
private selectDropDownListContainer: HTMLElement;
|
||||
private widthControlElement: HTMLElement;
|
||||
private _currentSelection: number;
|
||||
private _dropDownPosition: AnchorPosition;
|
||||
|
||||
constructor(options: string[], selected: number, contextViewProvider: IContextViewProvider, styles: ISelectBoxStyles, selectBoxOptions?: ISelectBoxOptions) {
|
||||
|
||||
@@ -108,14 +118,15 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
}
|
||||
|
||||
this.selectElement = document.createElement('select');
|
||||
this.selectElement.className = 'monaco-select-box';
|
||||
// Use custom CSS vars for padding calculation
|
||||
this.selectElement.className = 'monaco-select-box monaco-select-box-dropdown-padding';
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
if (selectBoxOptions && selectBoxOptions.ariaLabel) {
|
||||
this.selectElement.setAttribute('aria-label', selectBoxOptions.ariaLabel);
|
||||
if (typeof this.selectBoxOptions.ariaLabel === 'string') {
|
||||
this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
|
||||
}
|
||||
|
||||
this._onDidSelect = new Emitter<ISelectData>();
|
||||
|
||||
this.styles = styles;
|
||||
|
||||
this.registerListeners();
|
||||
@@ -139,7 +150,8 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
// SetUp ContextView container to hold select Dropdown
|
||||
this.contextViewProvider = contextViewProvider;
|
||||
this.selectDropDownContainer = dom.$('.monaco-select-box-dropdown-container');
|
||||
|
||||
// Use custom CSS vars for padding calculation (shared with parent select)
|
||||
dom.addClass(this.selectDropDownContainer, 'monaco-select-box-dropdown-padding');
|
||||
// Setup list for drop-down select
|
||||
this.createSelectList(this.selectDropDownContainer);
|
||||
|
||||
@@ -150,6 +162,9 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
this.widthControlElement.className = 'option-text-width-control';
|
||||
dom.append(widthControlInnerDiv, this.widthControlElement);
|
||||
|
||||
// Always default to below position
|
||||
this._dropDownPosition = AnchorPosition.BELOW;
|
||||
|
||||
// Inline stylesheet for themes
|
||||
this.styleElement = dom.createStyleSheet(this.selectDropDownContainer);
|
||||
}
|
||||
@@ -244,6 +259,8 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
|
||||
if (selected !== undefined) {
|
||||
this.select(selected);
|
||||
// Set current = selected since this is not necessarily a user exit
|
||||
this._currentSelection = this.selected;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +280,12 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
this.selectElement.title = this.options[this.selected];
|
||||
}
|
||||
|
||||
public setAriaLabel(label: string): void {
|
||||
this.selectBoxOptions.ariaLabel = label;
|
||||
this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
|
||||
this.selectList.getHTMLElement().setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
|
||||
}
|
||||
|
||||
public focus(): void {
|
||||
if (this.selectElement) {
|
||||
this.selectElement.focus();
|
||||
@@ -371,7 +394,6 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
return option;
|
||||
}
|
||||
|
||||
// Non-native select list handling
|
||||
// ContextView dropdown methods
|
||||
|
||||
private showSelectDropDown() {
|
||||
@@ -379,8 +401,12 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
return;
|
||||
}
|
||||
|
||||
// Set drop-down position above/below from required height and margins
|
||||
this.layoutSelectDropDown(true);
|
||||
|
||||
this._isVisible = true;
|
||||
this.cloneElementFont(this.selectElement, this.selectDropDownContainer);
|
||||
|
||||
this.contextViewProvider.showContextView({
|
||||
getAnchor: () => this.selectElement,
|
||||
render: (container: HTMLElement) => this.renderSelectDropDown(container),
|
||||
@@ -388,8 +414,11 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
onHide: () => {
|
||||
dom.toggleClass(this.selectDropDownContainer, 'visible', false);
|
||||
dom.toggleClass(this.selectElement, 'synthetic-focus', false);
|
||||
}
|
||||
},
|
||||
anchorPosition: this._dropDownPosition
|
||||
});
|
||||
|
||||
// Track initial selection the case user escape, blur
|
||||
this._currentSelection = this.selected;
|
||||
}
|
||||
|
||||
@@ -414,60 +443,91 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
// {{SQL CARBON EDIT}}
|
||||
return {
|
||||
dispose: () => {
|
||||
// contextView will dispose itself if moving from one View to another
|
||||
try {
|
||||
container.removeChild(this.selectDropDownContainer); // remove to take out the CSS rules we add
|
||||
} catch(e) {
|
||||
// if this fails it means it is already removed
|
||||
}
|
||||
catch (error) {
|
||||
// Ignore, removed already by change of focus
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private layoutSelectDropDown() {
|
||||
private layoutSelectDropDown(preLayoutPosition?: boolean) {
|
||||
|
||||
// Layout ContextView drop down select list and container
|
||||
// Have to manage our vertical overflow, sizing
|
||||
// Need to be visible to measure
|
||||
// Have to manage our vertical overflow, sizing, position below or above
|
||||
// Position has to be determined and set prior to contextView instantiation
|
||||
|
||||
dom.toggleClass(this.selectDropDownContainer, 'visible', true);
|
||||
|
||||
const selectWidth = dom.getTotalWidth(this.selectElement);
|
||||
const selectPosition = dom.getDomNodePagePosition(this.selectElement);
|
||||
|
||||
// Set container height to max from select bottom to margin (default/minBottomMargin)
|
||||
let maxSelectDropDownHeight = (window.innerHeight - selectPosition.top - selectPosition.height - this.selectBoxOptions.minBottomMargin);
|
||||
|
||||
if (maxSelectDropDownHeight < 0) {
|
||||
maxSelectDropDownHeight = 0;
|
||||
}
|
||||
|
||||
// SetUp list dimensions and layout - account for container padding
|
||||
if (this.selectList) {
|
||||
|
||||
const selectPosition = dom.getDomNodePagePosition(this.selectElement);
|
||||
const styles = getComputedStyle(this.selectElement);
|
||||
const verticalPadding = parseFloat(styles.getPropertyValue('--dropdown-padding-top')) + parseFloat(styles.getPropertyValue('--dropdown-padding-bottom'));
|
||||
let maxSelectDropDownHeight = 0;
|
||||
maxSelectDropDownHeight = (window.innerHeight - selectPosition.top - selectPosition.height - this.selectBoxOptions.minBottomMargin);
|
||||
|
||||
this.selectList.layout();
|
||||
let listHeight = this.selectList.contentHeight;
|
||||
const listContainerHeight = dom.getTotalHeight(this.selectDropDownListContainer);
|
||||
const totalVerticalListPadding = listContainerHeight - listHeight;
|
||||
|
||||
// Always show complete list items - never more than Max available vertical height
|
||||
if (listContainerHeight > maxSelectDropDownHeight) {
|
||||
listHeight = ((Math.floor((maxSelectDropDownHeight - totalVerticalListPadding) / this.getHeight())) * this.getHeight());
|
||||
// If we are only doing pre-layout check/adjust position only
|
||||
// Calculate vertical space available, flip up if insufficient
|
||||
// Use reflected padding on parent select, ContextView style properties not available before DOM attachment
|
||||
if (preLayoutPosition) {
|
||||
|
||||
// Always show complete list items - never more than Max available vertical height
|
||||
if (listHeight + verticalPadding > maxSelectDropDownHeight) {
|
||||
const maxVisibleOptions = ((Math.floor((maxSelectDropDownHeight - verticalPadding) / this.getHeight())));
|
||||
|
||||
// Check if we can at least show min items otherwise flip above
|
||||
if (maxVisibleOptions < SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS) {
|
||||
this._dropDownPosition = AnchorPosition.ABOVE;
|
||||
} else {
|
||||
this._dropDownPosition = AnchorPosition.BELOW;
|
||||
}
|
||||
}
|
||||
// Do full layout on showSelectDropDown only
|
||||
return;
|
||||
}
|
||||
|
||||
// Make visible to enable measurements
|
||||
dom.toggleClass(this.selectDropDownContainer, 'visible', true);
|
||||
|
||||
// SetUp list dimensions and layout - account for container padding
|
||||
// Use position to check above or below available space
|
||||
if (this._dropDownPosition === AnchorPosition.BELOW) {
|
||||
// Set container height to max from select bottom to margin (default/minBottomMargin)
|
||||
if (listHeight + verticalPadding > maxSelectDropDownHeight) {
|
||||
listHeight = ((Math.floor((maxSelectDropDownHeight - verticalPadding) / this.getHeight())) * this.getHeight());
|
||||
}
|
||||
} else {
|
||||
// Set container height to max from select top to margin (default/minTopMargin)
|
||||
maxSelectDropDownHeight = (selectPosition.top - SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN);
|
||||
if (listHeight + verticalPadding > maxSelectDropDownHeight) {
|
||||
listHeight = ((Math.floor((maxSelectDropDownHeight - SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN) / this.getHeight())) * this.getHeight());
|
||||
}
|
||||
}
|
||||
|
||||
// Set adjusted list height and relayout
|
||||
this.selectList.layout(listHeight);
|
||||
this.selectList.domFocus();
|
||||
|
||||
// Finally set focus on selected item
|
||||
this.selectList.setFocus([this.selected]);
|
||||
this.selectList.reveal(this.selectList.getFocus()[0]);
|
||||
if (this.selectList.length > 0) {
|
||||
this.selectList.setFocus([this.selected || 0]);
|
||||
this.selectList.reveal(this.selectList.getFocus()[0] || 0);
|
||||
}
|
||||
|
||||
// Set final container height after adjustments
|
||||
this.selectDropDownContainer.style.height = (listHeight + totalVerticalListPadding) + 'px';
|
||||
this.selectDropDownContainer.style.height = (listHeight + verticalPadding) + 'px';
|
||||
|
||||
// Determine optimal width - min(longest option), opt(parent select), max(ContextView controlled)
|
||||
// Determine optimal width - min(longest option), opt(parent select, excluding margins), max(ContextView controlled)
|
||||
const selectWidth = this.selectElement.offsetWidth;
|
||||
const selectMinWidth = this.setWidthControlElement(this.widthControlElement);
|
||||
const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + 'px';
|
||||
|
||||
this.selectDropDownContainer.style.minWidth = selectOptimalWidth;
|
||||
this.selectDropDownContainer.style.width = selectOptimalWidth;
|
||||
|
||||
// Maintain focus outline on parent select as well as list container - tabindex for focus
|
||||
this.selectDropDownListContainer.setAttribute('tabindex', '0');
|
||||
@@ -510,6 +570,7 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
this.listRenderer = new SelectListRenderer();
|
||||
|
||||
this.selectList = new List(this.selectDropDownListContainer, this, [this.listRenderer], {
|
||||
ariaLabel: this.selectBoxOptions.ariaLabel,
|
||||
useShadows: false,
|
||||
selectOnMouseDown: false,
|
||||
verticalScrollMode: ScrollbarVisibility.Visible,
|
||||
@@ -539,13 +600,17 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
.on(e => this.onMouseUp(e), this, this.toDispose);
|
||||
|
||||
this.toDispose.push(this.selectList.onDidBlur(e => this.onListBlur()));
|
||||
|
||||
this.selectList.getHTMLElement().setAttribute('aria-expanded', 'true');
|
||||
}
|
||||
|
||||
// List methods
|
||||
|
||||
// List mouse controller - active exit, select option, fire onDidSelect, return focus to parent select
|
||||
// List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select
|
||||
private onMouseUp(e: MouseEvent): void {
|
||||
|
||||
dom.EventHelper.stop(e);
|
||||
|
||||
// Check our mouse event is on an option (not scrollbar)
|
||||
if (!e.toElement.classList.contains('option-text')) {
|
||||
return;
|
||||
@@ -563,59 +628,58 @@ export class SelectBoxList implements ISelectBoxDelegate, IDelegate<ISelectOptio
|
||||
this.selectList.setFocus([this.selected]);
|
||||
this.selectList.reveal(this.selectList.getFocus()[0]);
|
||||
|
||||
// {{SQL CARBON EDIT}} - Update the selection before firing the handler instead of after
|
||||
// Reset Selection Handler
|
||||
this._currentSelection = -1;
|
||||
this.hideSelectDropDown(true);
|
||||
// Only fire if selection change
|
||||
if (this.selected !== this._currentSelection) {
|
||||
// Set current = selected
|
||||
this._currentSelection = this.selected;
|
||||
|
||||
// {{SQL CARBON EDIT}} - Update the selection before firing the handler instead of after
|
||||
this.hideSelectDropDown(true);
|
||||
|
||||
this._onDidSelect.fire({
|
||||
index: this.selectElement.selectedIndex,
|
||||
selected: this.selectElement.title
|
||||
});
|
||||
this._onDidSelect.fire({
|
||||
index: this.selectElement.selectedIndex,
|
||||
selected: this.selectElement.title
|
||||
});
|
||||
}
|
||||
}
|
||||
dom.EventHelper.stop(e);
|
||||
}
|
||||
|
||||
// List Exit - passive - hide drop-down, fire onDidSelect
|
||||
// List Exit - passive - implicit no selection change, hide drop-down
|
||||
private onListBlur(): void {
|
||||
if (this._currentSelection >= 0) {
|
||||
|
||||
if (this.selected !== this._currentSelection) {
|
||||
// Reset selected to current if no change
|
||||
this.select(this._currentSelection);
|
||||
}
|
||||
|
||||
this._onDidSelect.fire({
|
||||
index: this.selectElement.selectedIndex,
|
||||
selected: this.selectElement.title
|
||||
});
|
||||
|
||||
this.hideSelectDropDown(false);
|
||||
}
|
||||
|
||||
// List keyboard controller
|
||||
// List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect
|
||||
|
||||
// List exit - active - hide ContextView dropdown, reset selection, return focus to parent select
|
||||
private onEscape(e: StandardKeyboardEvent): void {
|
||||
dom.EventHelper.stop(e);
|
||||
|
||||
// Reset selection to value when opened
|
||||
this.select(this._currentSelection);
|
||||
|
||||
this.hideSelectDropDown(true);
|
||||
|
||||
this._onDidSelect.fire({
|
||||
index: this.selectElement.selectedIndex,
|
||||
selected: this.selectElement.title
|
||||
});
|
||||
}
|
||||
|
||||
// List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect
|
||||
// List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change
|
||||
private onEnter(e: StandardKeyboardEvent): void {
|
||||
dom.EventHelper.stop(e);
|
||||
|
||||
// Reset current selection
|
||||
this._currentSelection = -1;
|
||||
// Only fire if selection change
|
||||
if (this.selected !== this._currentSelection) {
|
||||
this._currentSelection = this.selected;
|
||||
this._onDidSelect.fire({
|
||||
index: this.selectElement.selectedIndex,
|
||||
selected: this.selectElement.title
|
||||
});
|
||||
}
|
||||
|
||||
this.hideSelectDropDown(true);
|
||||
this._onDidSelect.fire({
|
||||
index: this.selectElement.selectedIndex,
|
||||
selected: this.selectElement.title
|
||||
});
|
||||
}
|
||||
|
||||
// List navigation - have to handle a disabled option (jump over)
|
||||
|
||||
@@ -8,30 +8,30 @@ import { Event, Emitter } from 'vs/base/common/event';
|
||||
import { KeyCode } from 'vs/base/common/keyCodes';
|
||||
import * as dom from 'vs/base/browser/dom';
|
||||
import * as arrays from 'vs/base/common/arrays';
|
||||
import { ISelectBoxDelegate, ISelectBoxStyles, ISelectData, ISelectBoxOptions } from 'vs/base/browser/ui/selectBox/selectBox';
|
||||
import { ISelectBoxDelegate, ISelectBoxOptions, ISelectBoxStyles, ISelectData } from 'vs/base/browser/ui/selectBox/selectBox';
|
||||
import { isMacintosh } from 'vs/base/common/platform';
|
||||
|
||||
export class SelectBoxNative implements ISelectBoxDelegate {
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
public selectElement: HTMLSelectElement;
|
||||
private selectBoxOptions: ISelectBoxOptions;
|
||||
private options: string[];
|
||||
private selected: number;
|
||||
private readonly _onDidSelect: Emitter<ISelectData>;
|
||||
private toDispose: IDisposable[];
|
||||
private styles: ISelectBoxStyles;
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
constructor(options: string[], selected: number, styles: ISelectBoxStyles, selectBoxOptions?: ISelectBoxOptions) {
|
||||
|
||||
this.toDispose = [];
|
||||
this.selectBoxOptions = selectBoxOptions || Object.create(null);
|
||||
|
||||
this.selectElement = document.createElement('select');
|
||||
this.selectElement.className = 'monaco-select-box';
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
if (selectBoxOptions && selectBoxOptions.ariaLabel) {
|
||||
this.selectElement.setAttribute('aria-label', selectBoxOptions.ariaLabel);
|
||||
if (typeof this.selectBoxOptions.ariaLabel === 'string') {
|
||||
this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
|
||||
}
|
||||
|
||||
this._onDidSelect = new Emitter<ISelectData>();
|
||||
@@ -39,7 +39,6 @@ export class SelectBoxNative implements ISelectBoxDelegate {
|
||||
this.styles = styles;
|
||||
|
||||
this.registerListeners();
|
||||
|
||||
this.setOptions(options, selected);
|
||||
}
|
||||
|
||||
@@ -110,6 +109,11 @@ export class SelectBoxNative implements ISelectBoxDelegate {
|
||||
this.selectElement.title = this.options[this.selected];
|
||||
}
|
||||
|
||||
public setAriaLabel(label: string): void {
|
||||
this.selectBoxOptions.ariaLabel = label;
|
||||
this.selectElement.setAttribute('aria-label', label);
|
||||
}
|
||||
|
||||
public focus(): void {
|
||||
if (this.selectElement) {
|
||||
this.selectElement.focus();
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import { Event, anyEvent } from 'vs/base/common/event';
|
||||
import { Orientation } from 'vs/base/browser/ui/sash/sash';
|
||||
import { append, $ } from 'vs/base/browser/dom';
|
||||
import { SplitView, IView } from 'vs/base/browser/ui/splitview/splitview';
|
||||
export { Orientation } from 'vs/base/browser/ui/sash/sash';
|
||||
|
||||
export class GridNode implements IView {
|
||||
|
||||
get minimumSize(): number {
|
||||
let result = 0;
|
||||
|
||||
for (const child of this.children) {
|
||||
for (const grandchild of child.children) {
|
||||
result += grandchild.minimumSize;
|
||||
}
|
||||
}
|
||||
|
||||
return result === 0 ? 50 : result;
|
||||
}
|
||||
|
||||
readonly maximumSize = Number.MAX_VALUE;
|
||||
|
||||
private _onDidChange: Event<number | undefined> = Event.None;
|
||||
get onDidChange(): Event<number | undefined> {
|
||||
return this._onDidChange;
|
||||
}
|
||||
|
||||
protected orientation: Orientation | undefined;
|
||||
protected size: number | undefined;
|
||||
protected orthogonalSize: number | undefined;
|
||||
private splitview: SplitView | undefined;
|
||||
private children: GridNode[] = [];
|
||||
private color: string | undefined;
|
||||
|
||||
constructor(private parent?: GridNode, orthogonalSize?: number, color?: string) {
|
||||
this.orthogonalSize = orthogonalSize;
|
||||
this.color = color || `hsl(${Math.round(Math.random() * 360)}, 72%, 72%)`;
|
||||
}
|
||||
|
||||
render(container: HTMLElement): void {
|
||||
container = append(container, $('.node'));
|
||||
container.style.backgroundColor = this.color;
|
||||
|
||||
append(container, $('.action', { onclick: () => this.split(container, Orientation.HORIZONTAL) }, '⬌'));
|
||||
append(container, $('.action', { onclick: () => this.split(container, Orientation.VERTICAL) }, '⬍'));
|
||||
}
|
||||
|
||||
protected split(container: HTMLElement, orientation: Orientation): void {
|
||||
if (this.parent && this.parent.orientation === orientation) {
|
||||
const index = this.parent.children.indexOf(this);
|
||||
this.parent.addChild(this.size / 2, this.orthogonalSize, index + 1);
|
||||
} else {
|
||||
this.branch(container, orientation);
|
||||
}
|
||||
}
|
||||
|
||||
protected branch(container: HTMLElement, orientation: Orientation): void {
|
||||
this.orientation = orientation;
|
||||
container.innerHTML = '';
|
||||
|
||||
this.splitview = new SplitView(container, { orientation });
|
||||
this.layout(this.size);
|
||||
this.orthogonalLayout(this.orthogonalSize);
|
||||
|
||||
this.addChild(this.orthogonalSize / 2, this.size, 0, this.color);
|
||||
this.addChild(this.orthogonalSize / 2, this.size);
|
||||
}
|
||||
|
||||
layout(size: number): void {
|
||||
this.size = size;
|
||||
|
||||
for (const child of this.children) {
|
||||
child.orthogonalLayout(size);
|
||||
}
|
||||
}
|
||||
|
||||
orthogonalLayout(size: number): void {
|
||||
this.orthogonalSize = size;
|
||||
|
||||
if (this.splitview) {
|
||||
this.splitview.layout(size);
|
||||
}
|
||||
}
|
||||
|
||||
private addChild(size: number, orthogonalSize: number, index?: number, color?: string): void {
|
||||
const child = new GridNode(this, orthogonalSize, color);
|
||||
this.splitview.addView(child, size, index);
|
||||
|
||||
if (typeof index === 'number') {
|
||||
this.children.splice(index, 0, child);
|
||||
} else {
|
||||
this.children.push(child);
|
||||
}
|
||||
|
||||
this._onDidChange = anyEvent(...this.children.map(c => c.onDidChange));
|
||||
}
|
||||
}
|
||||
|
||||
export class RootGridNode extends GridNode {
|
||||
|
||||
private width: number;
|
||||
private height: number;
|
||||
|
||||
protected branch(container: HTMLElement, orientation: Orientation): void {
|
||||
if (orientation === Orientation.VERTICAL) {
|
||||
this.size = this.width;
|
||||
this.orthogonalSize = this.height;
|
||||
} else {
|
||||
this.size = this.height;
|
||||
this.orthogonalSize = this.width;
|
||||
}
|
||||
|
||||
super.branch(container, orientation);
|
||||
}
|
||||
|
||||
layoutBox(width: number, height: number): void {
|
||||
if (this.orientation === Orientation.VERTICAL) {
|
||||
this.layout(width);
|
||||
this.orthogonalLayout(height);
|
||||
} else if (this.orientation === Orientation.HORIZONTAL) {
|
||||
this.layout(height);
|
||||
this.orthogonalLayout(width);
|
||||
} else {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class Grid {
|
||||
|
||||
private root: RootGridNode;
|
||||
|
||||
constructor(container: HTMLElement) {
|
||||
this.root = new RootGridNode();
|
||||
this.root.render(container);
|
||||
}
|
||||
|
||||
layout(width: number, height: number): void {
|
||||
this.root.layoutBox(width, height);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,15 @@ export interface IPanelStyles {
|
||||
headerHighContrastBorder?: Color;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Panel is a structured SplitView view.
|
||||
*
|
||||
* WARNING: You must call `render()` after you contruct it.
|
||||
* It can't be done automatically at the end of the ctor
|
||||
* because of the order of property initialization in TypeScript.
|
||||
* Subclasses wouldn't be able to set own properties
|
||||
* before the `render()` call, thus forbiding their use.
|
||||
*/
|
||||
export abstract class Panel implements IView {
|
||||
|
||||
private static readonly HEADER_SIZE = 22;
|
||||
@@ -40,25 +49,21 @@ export abstract class Panel implements IView {
|
||||
private _minimumBodySize: number;
|
||||
private _maximumBodySize: number;
|
||||
private ariaHeaderLabel: string;
|
||||
private styles: IPanelStyles | undefined = undefined;
|
||||
private styles: IPanelStyles = {};
|
||||
|
||||
private el: HTMLElement;
|
||||
readonly element: HTMLElement;
|
||||
private header: HTMLElement;
|
||||
protected disposables: IDisposable[] = [];
|
||||
|
||||
private _onDidChange = new Emitter<number | undefined>();
|
||||
readonly onDidChange: Event<number | undefined> = this._onDidChange.event;
|
||||
|
||||
get element(): HTMLElement {
|
||||
return this.el;
|
||||
}
|
||||
|
||||
get draggableElement(): HTMLElement {
|
||||
return this.header;
|
||||
}
|
||||
|
||||
get dropTargetElement(): HTMLElement {
|
||||
return this.el;
|
||||
return this.element;
|
||||
}
|
||||
|
||||
private _dropBackground: Color | undefined;
|
||||
@@ -109,6 +114,8 @@ export abstract class Panel implements IView {
|
||||
this.ariaHeaderLabel = options.ariaHeaderLabel || '';
|
||||
this._minimumBodySize = typeof options.minimumBodySize === 'number' ? options.minimumBodySize : 120;
|
||||
this._maximumBodySize = typeof options.maximumBodySize === 'number' ? options.maximumBodySize : Number.POSITIVE_INFINITY;
|
||||
|
||||
this.element = $('.panel');
|
||||
}
|
||||
|
||||
isExpanded(): boolean {
|
||||
@@ -139,11 +146,9 @@ export abstract class Panel implements IView {
|
||||
this._onDidChange.fire();
|
||||
}
|
||||
|
||||
render(container: HTMLElement): void {
|
||||
this.el = append(container, $('.panel'));
|
||||
|
||||
render(): void {
|
||||
this.header = $('.panel-header');
|
||||
append(this.el, this.header);
|
||||
append(this.element, this.header);
|
||||
this.header.setAttribute('tabindex', '0');
|
||||
this.header.setAttribute('role', 'toolbar');
|
||||
this.header.setAttribute('aria-label', this.ariaHeaderLabel);
|
||||
@@ -177,7 +182,7 @@ export abstract class Panel implements IView {
|
||||
// onHeaderKeyDown.filter(e => e.keyCode === KeyCode.DownArrow)
|
||||
// .event(focusNext, this, this.disposables);
|
||||
|
||||
const body = append(this.el, $('.panel-body'));
|
||||
const body = append(this.element, $('.panel-body'));
|
||||
this.renderBody(body);
|
||||
}
|
||||
|
||||
@@ -370,7 +375,7 @@ export class PanelView implements IDisposable {
|
||||
private _onDidDrop = new Emitter<{ from: Panel, to: Panel }>();
|
||||
readonly onDidDrop: Event<{ from: Panel, to: Panel }> = this._onDidDrop.event;
|
||||
|
||||
readonly onDidSashChange: Event<void>;
|
||||
readonly onDidSashChange: Event<number>;
|
||||
|
||||
constructor(container: HTMLElement, options: IPanelViewOptions = {}) {
|
||||
this.dnd = options.dnd;
|
||||
|
||||
@@ -5,18 +5,39 @@
|
||||
|
||||
.monaco-split-view2 {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.monaco-split-view2 > .sash-container {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.monaco-split-view2 > .sash-container > .monaco-sash {
|
||||
pointer-events: initial;
|
||||
}
|
||||
|
||||
.monaco-split-view2 > .split-view-container {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.monaco-split-view2.vertical > .split-view-container {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.monaco-split-view2.horizontal > .split-view-container {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.monaco-split-view2 > .split-view-container > .split-view-view {
|
||||
overflow: hidden;
|
||||
white-space: initial;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.monaco-split-view2.vertical > .split-view-container > .split-view-view {
|
||||
@@ -27,3 +48,27 @@
|
||||
height: 100%;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.monaco-split-view2.separator-border > .split-view-container > .split-view-view {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.monaco-split-view2.separator-border > .split-view-container > .split-view-view:not(:first-child)::before {
|
||||
content: ' ';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
background-color: var(--separator-border);
|
||||
}
|
||||
|
||||
.monaco-split-view2.separator-border.horizontal > .split-view-container > .split-view-view:not(:first-child)::before {
|
||||
height: 100%;
|
||||
width: 1px;
|
||||
}
|
||||
|
||||
.monaco-split-view2.separator-border.vertical > .split-view-container > .split-view-view:not(:first-child)::before {
|
||||
height: 1px;
|
||||
width: 100%;
|
||||
}
|
||||
@@ -11,19 +11,33 @@ import { Event, mapEvent, Emitter } from 'vs/base/common/event';
|
||||
import * as types from 'vs/base/common/types';
|
||||
import * as dom from 'vs/base/browser/dom';
|
||||
import { clamp } from 'vs/base/common/numbers';
|
||||
import { range, firstIndex } from 'vs/base/common/arrays';
|
||||
import { Sash, Orientation, ISashEvent as IBaseSashEvent } from 'vs/base/browser/ui/sash/sash';
|
||||
import { range, firstIndex, pushToStart, pushToEnd } from 'vs/base/common/arrays';
|
||||
import { Sash, Orientation, ISashEvent as IBaseSashEvent, SashState } from 'vs/base/browser/ui/sash/sash';
|
||||
import { Color } from 'vs/base/common/color';
|
||||
import { domEvent } from 'vs/base/browser/event';
|
||||
export { Orientation } from 'vs/base/browser/ui/sash/sash';
|
||||
|
||||
export interface ISplitViewStyles {
|
||||
separatorBorder: Color;
|
||||
}
|
||||
|
||||
const defaultStyles: ISplitViewStyles = {
|
||||
separatorBorder: Color.transparent
|
||||
};
|
||||
|
||||
export interface ISplitViewOptions {
|
||||
orientation?: Orientation; // default Orientation.VERTICAL
|
||||
styles?: ISplitViewStyles;
|
||||
orthogonalStartSash?: Sash;
|
||||
orthogonalEndSash?: Sash;
|
||||
inverseAltBehavior?: boolean;
|
||||
}
|
||||
|
||||
export interface IView {
|
||||
readonly element: HTMLElement;
|
||||
readonly minimumSize: number;
|
||||
readonly maximumSize: number;
|
||||
readonly onDidChange: Event<number | undefined>;
|
||||
render(container: HTMLElement, orientation: Orientation): void;
|
||||
layout(size: number, orientation: Orientation): void;
|
||||
}
|
||||
|
||||
@@ -31,6 +45,7 @@ interface ISashEvent {
|
||||
sash: Sash;
|
||||
start: number;
|
||||
current: number;
|
||||
alt: boolean;
|
||||
}
|
||||
|
||||
interface IViewItem {
|
||||
@@ -49,9 +64,12 @@ interface ISashItem {
|
||||
interface ISashDragState {
|
||||
index: number;
|
||||
start: number;
|
||||
current: number;
|
||||
sizes: number[];
|
||||
minDelta: number;
|
||||
maxDelta: number;
|
||||
alt: boolean;
|
||||
disposable: IDisposable;
|
||||
}
|
||||
|
||||
enum State {
|
||||
@@ -59,60 +77,98 @@ enum State {
|
||||
Busy
|
||||
}
|
||||
|
||||
function pushToEnd<T>(arr: T[], value: T): T[] {
|
||||
let didFindValue = false;
|
||||
export type DistributeSizing = { type: 'distribute' };
|
||||
export type SplitSizing = { type: 'split', index: number };
|
||||
export type Sizing = DistributeSizing | SplitSizing;
|
||||
|
||||
const result = arr.filter(v => {
|
||||
if (v === value) {
|
||||
didFindValue = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if (didFindValue) {
|
||||
result.push(value);
|
||||
}
|
||||
|
||||
return result;
|
||||
export namespace Sizing {
|
||||
export const Distribute: DistributeSizing = { type: 'distribute' };
|
||||
export function Split(index: number): SplitSizing { return { type: 'split', index }; }
|
||||
}
|
||||
|
||||
export class SplitView implements IDisposable {
|
||||
|
||||
private orientation: Orientation;
|
||||
private el: HTMLElement;
|
||||
readonly orientation: Orientation;
|
||||
// TODO@Joao have the same pattern as grid here
|
||||
readonly el: HTMLElement;
|
||||
private sashContainer: HTMLElement;
|
||||
private viewContainer: HTMLElement;
|
||||
private size = 0;
|
||||
private contentSize = 0;
|
||||
private proportions: undefined | number[] = undefined;
|
||||
private viewItems: IViewItem[] = [];
|
||||
private sashItems: ISashItem[] = [];
|
||||
private sashDragState: ISashDragState;
|
||||
private state: State = State.Idle;
|
||||
private inverseAltBehavior: boolean;
|
||||
|
||||
private _onDidSashChange = new Emitter<void>();
|
||||
private _onDidSashChange = new Emitter<number>();
|
||||
readonly onDidSashChange = this._onDidSashChange.event;
|
||||
private _onDidSashReset = new Emitter<void>();
|
||||
private _onDidSashReset = new Emitter<number>();
|
||||
readonly onDidSashReset = this._onDidSashReset.event;
|
||||
|
||||
get length(): number {
|
||||
return this.viewItems.length;
|
||||
}
|
||||
|
||||
get minimumSize(): number {
|
||||
return this.viewItems.reduce((r, item) => r + item.view.minimumSize, 0);
|
||||
}
|
||||
|
||||
get maximumSize(): number {
|
||||
return this.length === 0 ? Number.POSITIVE_INFINITY : this.viewItems.reduce((r, item) => r + item.view.maximumSize, 0);
|
||||
}
|
||||
|
||||
private _orthogonalStartSash: Sash | undefined;
|
||||
get orthogonalStartSash(): Sash | undefined { return this._orthogonalStartSash; }
|
||||
set orthogonalStartSash(sash: Sash | undefined) {
|
||||
for (const sashItem of this.sashItems) {
|
||||
sashItem.sash.orthogonalStartSash = sash;
|
||||
}
|
||||
|
||||
this._orthogonalStartSash = sash;
|
||||
}
|
||||
|
||||
private _orthogonalEndSash: Sash | undefined;
|
||||
get orthogonalEndSash(): Sash | undefined { return this._orthogonalEndSash; }
|
||||
set orthogonalEndSash(sash: Sash | undefined) {
|
||||
for (const sashItem of this.sashItems) {
|
||||
sashItem.sash.orthogonalEndSash = sash;
|
||||
}
|
||||
|
||||
this._orthogonalEndSash = sash;
|
||||
}
|
||||
|
||||
get sashes(): Sash[] {
|
||||
return this.sashItems.map(s => s.sash);
|
||||
}
|
||||
|
||||
constructor(container: HTMLElement, options: ISplitViewOptions = {}) {
|
||||
this.orientation = types.isUndefined(options.orientation) ? Orientation.VERTICAL : options.orientation;
|
||||
this.inverseAltBehavior = !!options.inverseAltBehavior;
|
||||
|
||||
this.el = document.createElement('div');
|
||||
dom.addClass(this.el, 'monaco-split-view2');
|
||||
dom.addClass(this.el, this.orientation === Orientation.VERTICAL ? 'vertical' : 'horizontal');
|
||||
container.appendChild(this.el);
|
||||
|
||||
this.viewContainer = document.createElement('div');
|
||||
dom.addClass(this.viewContainer, 'split-view-container');
|
||||
this.el.appendChild(this.viewContainer);
|
||||
this.sashContainer = dom.append(this.el, dom.$('.sash-container'));
|
||||
this.viewContainer = dom.append(this.el, dom.$('.split-view-container'));
|
||||
|
||||
this.style(options.styles || defaultStyles);
|
||||
}
|
||||
|
||||
addView(view: IView, size: number, index = this.viewItems.length): void {
|
||||
style(styles: ISplitViewStyles): void {
|
||||
if (styles.separatorBorder.isTransparent()) {
|
||||
dom.removeClass(this.el, 'separator-border');
|
||||
this.el.style.removeProperty('--separator-border');
|
||||
} else {
|
||||
dom.addClass(this.el, 'separator-border');
|
||||
this.el.style.setProperty('--separator-border', styles.separatorBorder.toString());
|
||||
}
|
||||
}
|
||||
|
||||
addView(view: IView, size: number | Sizing, index = this.viewItems.length): void {
|
||||
if (this.state !== State.Idle) {
|
||||
throw new Error('Cant modify splitview');
|
||||
}
|
||||
@@ -133,48 +189,72 @@ export class SplitView implements IDisposable {
|
||||
const disposable = combinedDisposable([onChangeDisposable, containerDisposable]);
|
||||
|
||||
const layoutContainer = this.orientation === Orientation.VERTICAL
|
||||
? size => item.container.style.height = `${item.size}px`
|
||||
: size => item.container.style.width = `${item.size}px`;
|
||||
? () => item.container.style.height = `${item.size}px`
|
||||
: () => item.container.style.width = `${item.size}px`;
|
||||
|
||||
const layout = () => {
|
||||
layoutContainer(item.size);
|
||||
layoutContainer();
|
||||
item.view.layout(item.size, this.orientation);
|
||||
};
|
||||
|
||||
size = Math.round(size);
|
||||
const item: IViewItem = { view, container, size, layout, disposable };
|
||||
let viewSize: number;
|
||||
|
||||
if (typeof size === 'number') {
|
||||
viewSize = size;
|
||||
} else if (size.type === 'split') {
|
||||
viewSize = this.getViewSize(size.index) / 2;
|
||||
} else {
|
||||
viewSize = view.minimumSize;
|
||||
}
|
||||
|
||||
const item: IViewItem = { view, container, size: viewSize, layout, disposable };
|
||||
this.viewItems.splice(index, 0, item);
|
||||
|
||||
// Add sash
|
||||
if (this.viewItems.length > 1) {
|
||||
const orientation = this.orientation === Orientation.VERTICAL ? Orientation.HORIZONTAL : Orientation.VERTICAL;
|
||||
const layoutProvider = this.orientation === Orientation.VERTICAL ? { getHorizontalSashTop: sash => this.getSashPosition(sash) } : { getVerticalSashLeft: sash => this.getSashPosition(sash) };
|
||||
const sash = new Sash(this.el, layoutProvider, { orientation });
|
||||
const sash = new Sash(this.sashContainer, layoutProvider, {
|
||||
orientation,
|
||||
orthogonalStartSash: this.orthogonalStartSash,
|
||||
orthogonalEndSash: this.orthogonalEndSash
|
||||
});
|
||||
|
||||
const sashEventMapper = this.orientation === Orientation.VERTICAL
|
||||
? (e: IBaseSashEvent) => ({ sash, start: e.startY, current: e.currentY })
|
||||
: (e: IBaseSashEvent) => ({ sash, start: e.startX, current: e.currentX });
|
||||
? (e: IBaseSashEvent) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey } as ISashEvent)
|
||||
: (e: IBaseSashEvent) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey } as ISashEvent);
|
||||
|
||||
const onStart = mapEvent(sash.onDidStart, sashEventMapper);
|
||||
const onStartDisposable = onStart(this.onSashStart, this);
|
||||
const onChange = mapEvent(sash.onDidChange, sashEventMapper);
|
||||
const onSashChangeDisposable = onChange(this.onSashChange, this);
|
||||
const onEnd = mapEvent<void, void>(sash.onDidEnd, () => null);
|
||||
const onEndDisposable = onEnd(() => this._onDidSashChange.fire());
|
||||
const onDidReset = mapEvent<void, void>(sash.onDidReset, () => null);
|
||||
const onDidResetDisposable = onDidReset(() => this._onDidSashReset.fire());
|
||||
const onChangeDisposable = onChange(this.onSashChange, this);
|
||||
const onEnd = mapEvent(sash.onDidEnd, () => firstIndex(this.sashItems, item => item.sash === sash));
|
||||
const onEndDisposable = onEnd(this.onSashEnd, this);
|
||||
const onDidResetDisposable = sash.onDidReset(() => this._onDidSashReset.fire(firstIndex(this.sashItems, item => item.sash === sash)));
|
||||
|
||||
const disposable = combinedDisposable([onStartDisposable, onSashChangeDisposable, onEndDisposable, onDidResetDisposable, sash]);
|
||||
const disposable = combinedDisposable([onStartDisposable, onChangeDisposable, onEndDisposable, onDidResetDisposable, sash]);
|
||||
const sashItem: ISashItem = { sash, disposable };
|
||||
|
||||
this.sashItems.splice(index - 1, 0, sashItem);
|
||||
}
|
||||
|
||||
view.render(container, this.orientation);
|
||||
this.relayout(index);
|
||||
container.appendChild(view.element);
|
||||
|
||||
let highPriorityIndex: number | undefined;
|
||||
|
||||
if (typeof size !== 'number' && size.type === 'split') {
|
||||
highPriorityIndex = size.index;
|
||||
}
|
||||
|
||||
this.relayout(index, highPriorityIndex);
|
||||
this.state = State.Idle;
|
||||
|
||||
if (typeof size !== 'number' && size.type === 'distribute') {
|
||||
this.distributeViewSizes();
|
||||
}
|
||||
}
|
||||
|
||||
removeView(index: number): void {
|
||||
removeView(index: number, sizing?: Sizing): IView {
|
||||
if (this.state !== State.Idle) {
|
||||
throw new Error('Cant modify splitview');
|
||||
}
|
||||
@@ -182,7 +262,7 @@ export class SplitView implements IDisposable {
|
||||
this.state = State.Busy;
|
||||
|
||||
if (index < 0 || index >= this.viewItems.length) {
|
||||
return;
|
||||
throw new Error('Index out of bounds');
|
||||
}
|
||||
|
||||
// Remove view
|
||||
@@ -198,6 +278,12 @@ export class SplitView implements IDisposable {
|
||||
|
||||
this.relayout();
|
||||
this.state = State.Idle;
|
||||
|
||||
if (sizing && sizing.type === 'distribute') {
|
||||
this.distributeViewSizes();
|
||||
}
|
||||
|
||||
return viewItem.view;
|
||||
}
|
||||
|
||||
moveView(from: number, to: number): void {
|
||||
@@ -205,67 +291,129 @@ export class SplitView implements IDisposable {
|
||||
throw new Error('Cant modify splitview');
|
||||
}
|
||||
|
||||
this.state = State.Busy;
|
||||
|
||||
if (from < 0 || from >= this.viewItems.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (to < 0 || to >= this.viewItems.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (from === to) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewItem = this.viewItems.splice(from, 1)[0];
|
||||
this.viewItems.splice(to, 0, viewItem);
|
||||
|
||||
if (to + 1 < this.viewItems.length) {
|
||||
this.viewContainer.insertBefore(viewItem.container, this.viewItems[to + 1].container);
|
||||
} else {
|
||||
this.viewContainer.appendChild(viewItem.container);
|
||||
}
|
||||
|
||||
this.layoutViews();
|
||||
this.state = State.Idle;
|
||||
const size = this.getViewSize(from);
|
||||
const view = this.removeView(from);
|
||||
this.addView(view, size, to);
|
||||
}
|
||||
|
||||
private relayout(lowPriorityIndex?: number): void {
|
||||
swapViews(from: number, to: number): void {
|
||||
if (this.state !== State.Idle) {
|
||||
throw new Error('Cant modify splitview');
|
||||
}
|
||||
|
||||
if (from > to) {
|
||||
return this.swapViews(to, from);
|
||||
}
|
||||
|
||||
const fromSize = this.getViewSize(from);
|
||||
const toSize = this.getViewSize(to);
|
||||
const toView = this.removeView(to);
|
||||
const fromView = this.removeView(from);
|
||||
|
||||
this.addView(toView, fromSize, from);
|
||||
this.addView(fromView, toSize, to);
|
||||
}
|
||||
|
||||
private relayout(lowPriorityIndex?: number, highPriorityIndex?: number): void {
|
||||
const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
|
||||
this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndex);
|
||||
|
||||
this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndex, highPriorityIndex);
|
||||
this.distributeEmptySpace();
|
||||
this.layoutViews();
|
||||
this.saveProportions();
|
||||
}
|
||||
|
||||
layout(size: number): void {
|
||||
const previousSize = Math.max(this.size, this.contentSize);
|
||||
this.size = size;
|
||||
this.resize(this.viewItems.length - 1, size - previousSize);
|
||||
|
||||
if (!this.proportions) {
|
||||
this.resize(this.viewItems.length - 1, size - previousSize);
|
||||
} else {
|
||||
for (let i = 0; i < this.viewItems.length; i++) {
|
||||
const item = this.viewItems[i];
|
||||
item.size = clamp(Math.round(this.proportions[i] * size), item.view.minimumSize, item.view.maximumSize);
|
||||
}
|
||||
}
|
||||
|
||||
this.distributeEmptySpace();
|
||||
this.layoutViews();
|
||||
}
|
||||
|
||||
private onSashStart({ sash, start }: ISashEvent): void {
|
||||
private saveProportions(): void {
|
||||
if (this.contentSize > 0) {
|
||||
this.proportions = this.viewItems.map(i => i.size / this.contentSize);
|
||||
}
|
||||
}
|
||||
|
||||
private onSashStart({ sash, start, alt }: ISashEvent): void {
|
||||
const index = firstIndex(this.sashItems, item => item.sash === sash);
|
||||
const sizes = this.viewItems.map(i => i.size);
|
||||
|
||||
const upIndexes = range(index, -1);
|
||||
const collapseUp = upIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].view.minimumSize), 0);
|
||||
const expandUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].view.maximumSize - sizes[i]), 0);
|
||||
// This way, we can press Alt while we resize a sash, macOS style!
|
||||
const disposable = combinedDisposable([
|
||||
domEvent(document.body, 'keydown')(e => resetSashDragState(this.sashDragState.current, e.altKey)),
|
||||
domEvent(document.body, 'keyup')(() => resetSashDragState(this.sashDragState.current, false))
|
||||
]);
|
||||
|
||||
const downIndexes = range(index + 1, this.viewItems.length);
|
||||
const collapseDown = downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].view.minimumSize), 0);
|
||||
const expandDown = downIndexes.reduce((r, i) => r + (this.viewItems[i].view.maximumSize - sizes[i]), 0);
|
||||
const resetSashDragState = (start: number, alt: boolean) => {
|
||||
const sizes = this.viewItems.map(i => i.size);
|
||||
let minDelta = Number.NEGATIVE_INFINITY;
|
||||
let maxDelta = Number.POSITIVE_INFINITY;
|
||||
|
||||
const minDelta = -Math.min(collapseUp, expandDown);
|
||||
const maxDelta = Math.min(collapseDown, expandUp);
|
||||
if (this.inverseAltBehavior) {
|
||||
alt = !alt;
|
||||
}
|
||||
|
||||
this.sashDragState = { start, index, sizes, minDelta, maxDelta };
|
||||
if (alt) {
|
||||
// When we're using the last sash with Alt, we're resizing
|
||||
// the view to the left/up, instead of right/down as usual
|
||||
// Thus, we must do the inverse of the usual
|
||||
const isLastSash = index === this.sashItems.length - 1;
|
||||
|
||||
if (isLastSash) {
|
||||
const viewItem = this.viewItems[index];
|
||||
minDelta = (viewItem.view.minimumSize - viewItem.size) / 2;
|
||||
maxDelta = (viewItem.view.maximumSize - viewItem.size) / 2;
|
||||
} else {
|
||||
const viewItem = this.viewItems[index + 1];
|
||||
minDelta = (viewItem.size - viewItem.view.maximumSize) / 2;
|
||||
maxDelta = (viewItem.size - viewItem.view.minimumSize) / 2;
|
||||
}
|
||||
}
|
||||
|
||||
this.sashDragState = { start, current: start, index, sizes, minDelta, maxDelta, alt, disposable };
|
||||
};
|
||||
|
||||
resetSashDragState(start, alt);
|
||||
}
|
||||
|
||||
private onSashChange({ sash, current }: ISashEvent): void {
|
||||
const { index, start, sizes, minDelta, maxDelta } = this.sashDragState;
|
||||
const delta = clamp(current - start, minDelta, maxDelta);
|
||||
private onSashChange({ current }: ISashEvent): void {
|
||||
const { index, start, sizes, alt, minDelta, maxDelta } = this.sashDragState;
|
||||
this.sashDragState.current = current;
|
||||
|
||||
this.resize(index, delta, sizes);
|
||||
const delta = current - start;
|
||||
const newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta);
|
||||
|
||||
if (alt) {
|
||||
const isLastSash = index === this.sashItems.length - 1;
|
||||
const newSizes = this.viewItems.map(i => i.size);
|
||||
const viewItemIndex = isLastSash ? index : index + 1;
|
||||
const viewItem = this.viewItems[viewItemIndex];
|
||||
const newMinDelta = viewItem.size - viewItem.view.maximumSize;
|
||||
const newMaxDelta = viewItem.size - viewItem.view.minimumSize;
|
||||
const resizeIndex = isLastSash ? index - 1 : index + 1;
|
||||
|
||||
this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta);
|
||||
}
|
||||
|
||||
this.distributeEmptySpace();
|
||||
this.layoutViews();
|
||||
}
|
||||
|
||||
private onSashEnd(index: number): void {
|
||||
this._onDidSashChange.fire(index);
|
||||
this.sashDragState.disposable.dispose();
|
||||
this.saveProportions();
|
||||
}
|
||||
|
||||
private onViewChange(item: IViewItem, size: number | undefined): void {
|
||||
@@ -277,8 +425,17 @@ export class SplitView implements IDisposable {
|
||||
|
||||
size = typeof size === 'number' ? size : item.size;
|
||||
size = clamp(size, item.view.minimumSize, item.view.maximumSize);
|
||||
item.size = size;
|
||||
this.relayout(index);
|
||||
|
||||
if (this.inverseAltBehavior && index > 0) {
|
||||
// In this case, we want the view to grow or shrink both sides equally
|
||||
// so we just resize the "left" side by half and let `resize` do the clamping magic
|
||||
this.resize(index - 1, Math.floor((item.size - size) / 2));
|
||||
this.distributeEmptySpace();
|
||||
this.layoutViews();
|
||||
} else {
|
||||
item.size = size;
|
||||
this.relayout(index, undefined);
|
||||
}
|
||||
}
|
||||
|
||||
resizeView(index: number, size: number): void {
|
||||
@@ -316,9 +473,20 @@ export class SplitView implements IDisposable {
|
||||
this.resize(index - 1, deltaUp);
|
||||
}
|
||||
|
||||
this.distributeEmptySpace();
|
||||
this.layoutViews();
|
||||
this.saveProportions();
|
||||
this.state = State.Idle;
|
||||
}
|
||||
|
||||
distributeViewSizes(): void {
|
||||
const size = Math.floor(this.size / this.viewItems.length);
|
||||
|
||||
for (let i = 0; i < this.viewItems.length - 1; i++) {
|
||||
this.resizeView(i, size);
|
||||
}
|
||||
}
|
||||
|
||||
getViewSize(index: number): number {
|
||||
if (index < 0 || index >= this.viewItems.length) {
|
||||
return -1;
|
||||
@@ -327,49 +495,73 @@ export class SplitView implements IDisposable {
|
||||
return this.viewItems[index].size;
|
||||
}
|
||||
|
||||
private resize(index: number, delta: number, sizes = this.viewItems.map(i => i.size), lowPriorityIndex?: number): void {
|
||||
private resize(
|
||||
index: number,
|
||||
delta: number,
|
||||
sizes = this.viewItems.map(i => i.size),
|
||||
lowPriorityIndex?: number,
|
||||
highPriorityIndex?: number,
|
||||
overloadMinDelta: number = Number.NEGATIVE_INFINITY,
|
||||
overloadMaxDelta: number = Number.POSITIVE_INFINITY
|
||||
): number {
|
||||
if (index < 0 || index >= this.viewItems.length) {
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (delta !== 0) {
|
||||
let upIndexes = range(index, -1);
|
||||
let downIndexes = range(index + 1, this.viewItems.length);
|
||||
const upIndexes = range(index, -1);
|
||||
const downIndexes = range(index + 1, this.viewItems.length);
|
||||
|
||||
if (typeof lowPriorityIndex === 'number') {
|
||||
upIndexes = pushToEnd(upIndexes, lowPriorityIndex);
|
||||
downIndexes = pushToEnd(downIndexes, lowPriorityIndex);
|
||||
}
|
||||
|
||||
const upItems = upIndexes.map(i => this.viewItems[i]);
|
||||
const upSizes = upIndexes.map(i => sizes[i]);
|
||||
|
||||
const downItems = downIndexes.map(i => this.viewItems[i]);
|
||||
const downSizes = downIndexes.map(i => sizes[i]);
|
||||
|
||||
for (let i = 0, deltaUp = delta; deltaUp !== 0 && i < upItems.length; i++) {
|
||||
const item = upItems[i];
|
||||
const size = clamp(upSizes[i] + deltaUp, item.view.minimumSize, item.view.maximumSize);
|
||||
const viewDelta = size - upSizes[i];
|
||||
|
||||
deltaUp -= viewDelta;
|
||||
item.size = size;
|
||||
}
|
||||
|
||||
for (let i = 0, deltaDown = delta; deltaDown !== 0 && i < downItems.length; i++) {
|
||||
const item = downItems[i];
|
||||
const size = clamp(downSizes[i] - deltaDown, item.view.minimumSize, item.view.maximumSize);
|
||||
const viewDelta = size - downSizes[i];
|
||||
|
||||
deltaDown += viewDelta;
|
||||
item.size = size;
|
||||
}
|
||||
if (typeof highPriorityIndex === 'number') {
|
||||
pushToStart(upIndexes, highPriorityIndex);
|
||||
pushToStart(downIndexes, highPriorityIndex);
|
||||
}
|
||||
|
||||
if (typeof lowPriorityIndex === 'number') {
|
||||
pushToEnd(upIndexes, lowPriorityIndex);
|
||||
pushToEnd(downIndexes, lowPriorityIndex);
|
||||
}
|
||||
|
||||
const upItems = upIndexes.map(i => this.viewItems[i]);
|
||||
const upSizes = upIndexes.map(i => sizes[i]);
|
||||
|
||||
const downItems = downIndexes.map(i => this.viewItems[i]);
|
||||
const downSizes = downIndexes.map(i => sizes[i]);
|
||||
|
||||
const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].view.minimumSize - sizes[i]), 0);
|
||||
const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].view.maximumSize - sizes[i]), 0);
|
||||
const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].view.minimumSize), 0);
|
||||
const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].view.maximumSize), 0);
|
||||
const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
|
||||
const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
|
||||
|
||||
delta = clamp(delta, minDelta, maxDelta);
|
||||
|
||||
for (let i = 0, deltaUp = delta; i < upItems.length; i++) {
|
||||
const item = upItems[i];
|
||||
const size = clamp(upSizes[i] + deltaUp, item.view.minimumSize, item.view.maximumSize);
|
||||
const viewDelta = size - upSizes[i];
|
||||
|
||||
deltaUp -= viewDelta;
|
||||
item.size = size;
|
||||
}
|
||||
|
||||
for (let i = 0, deltaDown = delta; i < downItems.length; i++) {
|
||||
const item = downItems[i];
|
||||
const size = clamp(downSizes[i] - deltaDown, item.view.minimumSize, item.view.maximumSize);
|
||||
const viewDelta = size - downSizes[i];
|
||||
|
||||
deltaDown += viewDelta;
|
||||
item.size = size;
|
||||
}
|
||||
|
||||
return delta;
|
||||
}
|
||||
|
||||
private distributeEmptySpace(): void {
|
||||
let contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
|
||||
let emptyDelta = this.size - contentSize;
|
||||
|
||||
for (let i = this.viewItems.length - 1; emptyDelta > 0 && i >= 0; i--) {
|
||||
for (let i = this.viewItems.length - 1; emptyDelta !== 0 && i >= 0; i--) {
|
||||
const item = this.viewItems[i];
|
||||
const size = clamp(item.size + emptyDelta, item.view.minimumSize, item.view.maximumSize);
|
||||
const viewDelta = size - item.size;
|
||||
@@ -377,14 +569,16 @@ export class SplitView implements IDisposable {
|
||||
emptyDelta -= viewDelta;
|
||||
item.size = size;
|
||||
}
|
||||
|
||||
this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
|
||||
|
||||
this.layoutViews();
|
||||
}
|
||||
|
||||
private layoutViews(): void {
|
||||
// Save new content size
|
||||
this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
|
||||
|
||||
// Layout views
|
||||
this.viewItems.forEach(item => item.layout());
|
||||
|
||||
// Layout sashes
|
||||
this.sashItems.forEach(item => item.sash.layout());
|
||||
|
||||
// Update sashes enablement
|
||||
@@ -402,10 +596,17 @@ export class SplitView implements IDisposable {
|
||||
const expandsUp = reverseViews.map(i => previous = (i.view.maximumSize - i.size > 0) || previous).reverse();
|
||||
|
||||
this.sashItems.forEach((s, i) => {
|
||||
if ((collapsesDown[i] && expandsUp[i + 1]) || (expandsDown[i] && collapsesUp[i + 1])) {
|
||||
s.sash.enable();
|
||||
const min = !(collapsesDown[i] && expandsUp[i + 1]);
|
||||
const max = !(expandsDown[i] && collapsesUp[i + 1]);
|
||||
|
||||
if (min && max) {
|
||||
s.sash.state = SashState.Disabled;
|
||||
} else if (min && !max) {
|
||||
s.sash.state = SashState.Minimum;
|
||||
} else if (!min && max) {
|
||||
s.sash.state = SashState.Maximum;
|
||||
} else {
|
||||
s.sash.disable();
|
||||
s.sash.state = SashState.Enabled;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><g fill="#262626"><circle cx="3.5" cy="7.5" r="2.5"/><circle cx="8.5" cy="7.5" r="2.5"/><circle cx="13.5" cy="7.5" r="2.5"/></g><g fill="#C5C5C5"><circle cx="3.5" cy="7.5" r="1.5"/><circle cx="8.5" cy="7.5" r="1.5"/><circle cx="13.5" cy="7.5" r="1.5"/></g></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#252526;}.icon-canvas-transparent{opacity:0;}.icon-vs-bg{fill:#c5c5c5;}</style></defs><title>Ellipsis_bold_16x</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="M6,7.5A2.5,2.5,0,1,1,3.5,5,2.5,2.5,0,0,1,6,7.5ZM8.5,5A2.5,2.5,0,1,0,11,7.5,2.5,2.5,0,0,0,8.5,5Zm5,0A2.5,2.5,0,1,0,16,7.5,2.5,2.5,0,0,0,13.5,5Z" style="display: none;"/></g><g id="iconBg"><path class="icon-vs-bg" d="M5,7.5A1.5,1.5,0,1,1,3.5,6,1.5,1.5,0,0,1,5,7.5ZM8.5,6A1.5,1.5,0,1,0,10,7.5,1.5,1.5,0,0,0,8.5,6Zm5,0A1.5,1.5,0,1,0,15,7.5,1.5,1.5,0,0,0,13.5,6Z"/></g></svg>
|
||||
|
Before Width: | Height: | Size: 325 B After Width: | Height: | Size: 748 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><g fill="#F6F6F6"><circle cx="3.5" cy="7.5" r="2.5"/><circle cx="8.5" cy="7.5" r="2.5"/><circle cx="13.5" cy="7.5" r="2.5"/></g><g fill="#424242"><circle cx="3.5" cy="7.5" r="1.5"/><circle cx="8.5" cy="7.5" r="1.5"/><circle cx="13.5" cy="7.5" r="1.5"/></g></svg>
|
||||
<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-vs-bg{fill:#424242;}</style></defs><title>Ellipsis_bold_16x</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="M6,7.5A2.5,2.5,0,1,1,3.5,5,2.5,2.5,0,0,1,6,7.5ZM8.5,5A2.5,2.5,0,1,0,11,7.5,2.5,2.5,0,0,0,8.5,5Zm5,0A2.5,2.5,0,1,0,16,7.5,2.5,2.5,0,0,0,13.5,5Z" style="display: none;"/></g><g id="iconBg"><path class="icon-vs-bg" d="M5,7.5A1.5,1.5,0,1,1,3.5,6,1.5,1.5,0,0,1,5,7.5ZM8.5,6A1.5,1.5,0,1,0,10,7.5,1.5,1.5,0,0,0,8.5,6Zm5,0A1.5,1.5,0,1,0,15,7.5,1.5,1.5,0,0,0,13.5,6Z"/></g></svg>
|
||||
|
Before Width: | Height: | Size: 325 B After Width: | Height: | Size: 748 B |
@@ -12,6 +12,7 @@ import { Action, IActionRunner, IAction } from 'vs/base/common/actions';
|
||||
import { ActionBar, ActionsOrientation, IActionItemProvider } from 'vs/base/browser/ui/actionbar/actionbar';
|
||||
import { IContextMenuProvider, DropdownMenuActionItem } from 'vs/base/browser/ui/dropdown/dropdown';
|
||||
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
|
||||
import { Disposable } from 'vs/base/common/lifecycle';
|
||||
|
||||
export const CONTEXT = 'context.toolbar';
|
||||
|
||||
@@ -26,7 +27,7 @@ export interface IToolBarOptions {
|
||||
/**
|
||||
* A widget that combines an action bar for primary actions and a dropdown for secondary actions.
|
||||
*/
|
||||
export class ToolBar {
|
||||
export class ToolBar extends Disposable {
|
||||
private options: IToolBarOptions;
|
||||
private actionBar: ActionBar;
|
||||
private toggleMenuAction: ToggleMenuAction;
|
||||
@@ -35,16 +36,18 @@ export class ToolBar {
|
||||
private lookupKeybindings: boolean;
|
||||
|
||||
constructor(container: HTMLElement, contextMenuProvider: IContextMenuProvider, options: IToolBarOptions = { orientation: ActionsOrientation.HORIZONTAL }) {
|
||||
super();
|
||||
|
||||
this.options = options;
|
||||
this.lookupKeybindings = typeof this.options.getKeyBinding === 'function';
|
||||
|
||||
this.toggleMenuAction = new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show());
|
||||
this.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionItem && this.toggleMenuActionItem.show()));
|
||||
|
||||
let element = document.createElement('div');
|
||||
element.className = 'monaco-toolbar';
|
||||
container.appendChild(element);
|
||||
|
||||
this.actionBar = new ActionBar(element, {
|
||||
this.actionBar = this._register(new ActionBar(element, {
|
||||
orientation: options.orientation,
|
||||
ariaLabel: options.ariaLabel,
|
||||
actionRunner: options.actionRunner,
|
||||
@@ -75,29 +78,29 @@ export class ToolBar {
|
||||
|
||||
return options.actionItemProvider ? options.actionItemProvider(action) : null;
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
public set actionRunner(actionRunner: IActionRunner) {
|
||||
set actionRunner(actionRunner: IActionRunner) {
|
||||
this.actionBar.actionRunner = actionRunner;
|
||||
}
|
||||
|
||||
public get actionRunner(): IActionRunner {
|
||||
get actionRunner(): IActionRunner {
|
||||
return this.actionBar.actionRunner;
|
||||
}
|
||||
|
||||
public set context(context: any) {
|
||||
set context(context: any) {
|
||||
this.actionBar.context = context;
|
||||
if (this.toggleMenuActionItem) {
|
||||
this.toggleMenuActionItem.setActionContext(context);
|
||||
}
|
||||
}
|
||||
|
||||
public getContainer(): HTMLElement {
|
||||
getContainer(): HTMLElement {
|
||||
return this.actionBar.getContainer();
|
||||
}
|
||||
|
||||
public getItemsWidth(): number {
|
||||
getItemsWidth(): number {
|
||||
let itemsWidth = 0;
|
||||
for (let i = 0; i < this.actionBar.length(); i++) {
|
||||
itemsWidth += this.actionBar.getWidth(i);
|
||||
@@ -105,11 +108,11 @@ export class ToolBar {
|
||||
return itemsWidth;
|
||||
}
|
||||
|
||||
public setAriaLabel(label: string): void {
|
||||
setAriaLabel(label: string): void {
|
||||
this.actionBar.setAriaLabel(label);
|
||||
}
|
||||
|
||||
public setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void {
|
||||
setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void {
|
||||
return () => {
|
||||
let primaryActionsToSet = primaryActions ? primaryActions.slice(0) : [];
|
||||
|
||||
@@ -134,7 +137,7 @@ export class ToolBar {
|
||||
return key ? key.getLabel() : void 0;
|
||||
}
|
||||
|
||||
public addPrimaryAction(primaryAction: IAction): () => void {
|
||||
addPrimaryAction(primaryAction: IAction): () => void {
|
||||
return () => {
|
||||
|
||||
// Add after the "..." action if we have secondary actions
|
||||
@@ -150,40 +153,40 @@ export class ToolBar {
|
||||
};
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this.actionBar.dispose();
|
||||
this.toggleMenuAction.dispose();
|
||||
|
||||
dispose(): void {
|
||||
if (this.toggleMenuActionItem) {
|
||||
this.toggleMenuActionItem.dispose();
|
||||
this.toggleMenuActionItem = void 0;
|
||||
}
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class ToggleMenuAction extends Action {
|
||||
|
||||
public static readonly ID = 'toolbar.toggle.more';
|
||||
static readonly ID = 'toolbar.toggle.more';
|
||||
|
||||
private _menuActions: IAction[];
|
||||
private toggleDropdownMenu: () => void;
|
||||
|
||||
constructor(toggleDropdownMenu: () => void) {
|
||||
super(ToggleMenuAction.ID, nls.localize('more', "More"), null, true);
|
||||
super(ToggleMenuAction.ID, nls.localize('moreActions', "More Actions..."), null, true);
|
||||
|
||||
this.toggleDropdownMenu = toggleDropdownMenu;
|
||||
}
|
||||
|
||||
public run(): TPromise<any> {
|
||||
run(): TPromise<any> {
|
||||
this.toggleDropdownMenu();
|
||||
|
||||
return TPromise.as(true);
|
||||
}
|
||||
|
||||
public get menuActions() {
|
||||
get menuActions() {
|
||||
return this._menuActions;
|
||||
}
|
||||
|
||||
public set menuActions(actions: IAction[]) {
|
||||
set menuActions(actions: IAction[]) {
|
||||
this._menuActions = actions;
|
||||
}
|
||||
}
|
||||
16
src/vs/base/browser/ui/tree/tree.css
Normal file
16
src/vs/base/browser/ui/tree/tree.css
Normal file
@@ -0,0 +1,16 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
.monaco-tl-row {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.monaco-tl-row > .tl-twistie {
|
||||
font-size: 10px;
|
||||
text-align: right;
|
||||
padding-right: 10px;
|
||||
}
|
||||
252
src/vs/base/browser/ui/tree/tree.ts
Normal file
252
src/vs/base/browser/ui/tree/tree.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import 'vs/css!./tree';
|
||||
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { IListOptions, List, IIdentityProvider, IMultipleSelectionController } from 'vs/base/browser/ui/list/listWidget';
|
||||
import { TreeModel, ITreeNode, ITreeElement, getNodeLocation } from 'vs/base/browser/ui/tree/treeModel';
|
||||
import { Iterator, ISequence } from 'vs/base/common/iterator';
|
||||
import { IVirtualDelegate, IRenderer, IListMouseEvent } from 'vs/base/browser/ui/list/list';
|
||||
import { append, $ } from 'vs/base/browser/dom';
|
||||
import { Event, Relay, chain } from 'vs/base/common/event';
|
||||
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
|
||||
import { KeyCode } from 'vs/base/common/keyCodes';
|
||||
import { tail2 } from 'vs/base/common/arrays';
|
||||
|
||||
function toTreeListOptions<T>(options?: IListOptions<T>): IListOptions<ITreeNode<T>> {
|
||||
if (!options) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let identityProvider: IIdentityProvider<ITreeNode<T>> | undefined = undefined;
|
||||
let multipleSelectionController: IMultipleSelectionController<ITreeNode<T>> | undefined = undefined;
|
||||
|
||||
if (options.identityProvider) {
|
||||
identityProvider = el => options.identityProvider(el.element);
|
||||
}
|
||||
|
||||
if (options.multipleSelectionController) {
|
||||
multipleSelectionController = {
|
||||
isSelectionSingleChangeEvent(e) {
|
||||
return options.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element } as any);
|
||||
},
|
||||
isSelectionRangeChangeEvent(e) {
|
||||
return options.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element } as any);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...options,
|
||||
identityProvider,
|
||||
multipleSelectionController
|
||||
};
|
||||
}
|
||||
|
||||
class TreeDelegate<T> implements IVirtualDelegate<ITreeNode<T>> {
|
||||
|
||||
constructor(private delegate: IVirtualDelegate<T>) { }
|
||||
|
||||
getHeight(element: ITreeNode<T>): number {
|
||||
return this.delegate.getHeight(element.element);
|
||||
}
|
||||
|
||||
getTemplateId(element: ITreeNode<T>): string {
|
||||
return this.delegate.getTemplateId(element.element);
|
||||
}
|
||||
}
|
||||
|
||||
interface ITreeListTemplateData<T> {
|
||||
twistie: HTMLElement;
|
||||
templateData: T;
|
||||
}
|
||||
|
||||
function renderTwistie<T>(node: ITreeNode<T>, twistie: HTMLElement): void {
|
||||
if (node.children.length === 0 && !node.collapsible) {
|
||||
twistie.innerText = '';
|
||||
} else {
|
||||
twistie.innerText = node.collapsed ? '▹' : '◢';
|
||||
}
|
||||
}
|
||||
|
||||
class TreeRenderer<T, TTemplateData> implements IRenderer<ITreeNode<T>, ITreeListTemplateData<TTemplateData>> {
|
||||
|
||||
readonly templateId: string;
|
||||
private renderedNodes = new Map<ITreeNode<T>, ITreeListTemplateData<TTemplateData>>();
|
||||
private disposables: IDisposable[] = [];
|
||||
|
||||
constructor(
|
||||
private renderer: IRenderer<T, TTemplateData>,
|
||||
onDidChangeCollapseState: Event<ITreeNode<T>>
|
||||
) {
|
||||
this.templateId = renderer.templateId;
|
||||
onDidChangeCollapseState(this.onDidChangeCollapseState, this, this.disposables);
|
||||
}
|
||||
|
||||
renderTemplate(container: HTMLElement): ITreeListTemplateData<TTemplateData> {
|
||||
const el = append(container, $('.monaco-tl-row'));
|
||||
const twistie = append(el, $('.tl-twistie'));
|
||||
const contents = append(el, $('.tl-contents'));
|
||||
const templateData = this.renderer.renderTemplate(contents);
|
||||
|
||||
return { twistie, templateData };
|
||||
}
|
||||
|
||||
renderElement(node: ITreeNode<T>, index: number, templateData: ITreeListTemplateData<TTemplateData>): void {
|
||||
this.renderedNodes.set(node, templateData);
|
||||
|
||||
templateData.twistie.style.width = `${10 + node.depth * 10}px`;
|
||||
renderTwistie(node, templateData.twistie);
|
||||
|
||||
this.renderer.renderElement(node.element, index, templateData.templateData);
|
||||
}
|
||||
|
||||
disposeElement(node: ITreeNode<T>): void {
|
||||
this.renderedNodes.delete(node);
|
||||
}
|
||||
|
||||
disposeTemplate(templateData: ITreeListTemplateData<TTemplateData>): void {
|
||||
this.renderer.disposeTemplate(templateData.templateData);
|
||||
}
|
||||
|
||||
private onDidChangeCollapseState(node: ITreeNode<T>): void {
|
||||
const templateData = this.renderedNodes.get(node);
|
||||
|
||||
if (!templateData) {
|
||||
return;
|
||||
}
|
||||
|
||||
renderTwistie(node, templateData.twistie);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.renderedNodes.clear();
|
||||
this.disposables = dispose(this.disposables);
|
||||
}
|
||||
}
|
||||
|
||||
function isInputElement(e: HTMLElement): boolean {
|
||||
return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
|
||||
}
|
||||
|
||||
export interface ITreeOptions<T> extends IListOptions<T> { }
|
||||
|
||||
export class Tree<T> implements IDisposable {
|
||||
|
||||
private view: List<ITreeNode<T>>;
|
||||
private model: TreeModel<T>;
|
||||
private disposables: IDisposable[] = [];
|
||||
|
||||
constructor(
|
||||
container: HTMLElement,
|
||||
delegate: IVirtualDelegate<T>,
|
||||
renderers: IRenderer<T, any>[],
|
||||
options?: ITreeOptions<T>
|
||||
) {
|
||||
const treeDelegate = new TreeDelegate(delegate);
|
||||
|
||||
const onDidChangeCollapseStateRelay = new Relay<ITreeNode<T>>();
|
||||
const treeRenderers = renderers.map(r => new TreeRenderer(r, onDidChangeCollapseStateRelay.event));
|
||||
this.disposables.push(...treeRenderers);
|
||||
|
||||
const treeOptions = toTreeListOptions(options);
|
||||
|
||||
this.view = new List(container, treeDelegate, treeRenderers, treeOptions);
|
||||
this.model = new TreeModel<T>(this.view);
|
||||
onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
|
||||
|
||||
this.view.onMouseClick(this.onMouseClick, this, this.disposables);
|
||||
|
||||
const onKeyDown = chain(this.view.onKeyDown)
|
||||
.filter(e => !isInputElement(e.target as HTMLElement))
|
||||
.map(e => new StandardKeyboardEvent(e));
|
||||
|
||||
onKeyDown.filter(e => e.keyCode === KeyCode.LeftArrow).on(this.onLeftArrow, this, this.disposables);
|
||||
onKeyDown.filter(e => e.keyCode === KeyCode.RightArrow).on(this.onRightArrow, this, this.disposables);
|
||||
onKeyDown.filter(e => e.keyCode === KeyCode.Space).on(this.onSpace, this, this.disposables);
|
||||
}
|
||||
|
||||
splice(location: number[], deleteCount: number, toInsert: ISequence<ITreeElement<T>> = Iterator.empty()): Iterator<ITreeElement<T>> {
|
||||
return this.model.splice(location, deleteCount, toInsert);
|
||||
}
|
||||
|
||||
private onMouseClick(e: IListMouseEvent<ITreeNode<T>>): void {
|
||||
const node = e.element;
|
||||
const location = getNodeLocation(node);
|
||||
|
||||
this.model.toggleCollapsed(location);
|
||||
}
|
||||
|
||||
private onLeftArrow(e: StandardKeyboardEvent): void {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const nodes = this.view.getFocusedElements();
|
||||
|
||||
if (nodes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const node = nodes[0];
|
||||
const location = getNodeLocation(node);
|
||||
const didChange = this.model.setCollapsed(location, true);
|
||||
|
||||
if (!didChange) {
|
||||
if (location.length === 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [parentLocation] = tail2(location);
|
||||
const parentListIndex = this.model.getListIndex(parentLocation);
|
||||
this.view.setFocus([parentListIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
private onRightArrow(e: StandardKeyboardEvent): void {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const nodes = this.view.getFocusedElements();
|
||||
|
||||
if (nodes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const node = nodes[0];
|
||||
const location = getNodeLocation(node);
|
||||
const didChange = this.model.setCollapsed(location, false);
|
||||
|
||||
if (!didChange) {
|
||||
if (node.children.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [focusedIndex] = this.view.getFocus();
|
||||
this.view.setFocus([focusedIndex + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
private onSpace(e: StandardKeyboardEvent): void {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const nodes = this.view.getFocusedElements();
|
||||
|
||||
if (nodes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const node = nodes[0];
|
||||
const location = getNodeLocation(node);
|
||||
this.model.toggleCollapsed(location);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposables = dispose(this.disposables);
|
||||
this.view.dispose();
|
||||
this.view = null;
|
||||
this.model = null;
|
||||
}
|
||||
}
|
||||
232
src/vs/base/browser/ui/tree/treeModel.ts
Normal file
232
src/vs/base/browser/ui/tree/treeModel.ts
Normal file
@@ -0,0 +1,232 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import { ISpliceable } from 'vs/base/common/sequence';
|
||||
import { Iterator, ISequence } from 'vs/base/common/iterator';
|
||||
import { Emitter, Event } from 'vs/base/common/event';
|
||||
|
||||
export interface ITreeElement<T> {
|
||||
readonly element: T;
|
||||
readonly children?: Iterator<ITreeElement<T>> | ITreeElement<T>[];
|
||||
readonly collapsible?: boolean;
|
||||
readonly collapsed?: boolean;
|
||||
}
|
||||
|
||||
export interface ITreeNode<T> {
|
||||
readonly parent: IMutableTreeNode<T> | undefined;
|
||||
readonly element: T;
|
||||
readonly children: IMutableTreeNode<T>[];
|
||||
readonly depth: number;
|
||||
readonly collapsible: boolean;
|
||||
readonly collapsed: boolean;
|
||||
readonly visibleCount: number;
|
||||
}
|
||||
|
||||
interface IMutableTreeNode<T> extends ITreeNode<T> {
|
||||
collapsed: boolean;
|
||||
visibleCount: number;
|
||||
}
|
||||
|
||||
function visibleCountReducer<T>(result: number, node: IMutableTreeNode<T>): number {
|
||||
return result + (node.collapsed ? 1 : node.visibleCount);
|
||||
}
|
||||
|
||||
function getVisibleCount<T>(nodes: IMutableTreeNode<T>[]): number {
|
||||
return nodes.reduce(visibleCountReducer, 0);
|
||||
}
|
||||
|
||||
function getVisibleNodes<T>(nodes: IMutableTreeNode<T>[], result: ITreeNode<T>[] = []): ITreeNode<T>[] {
|
||||
for (const node of nodes) {
|
||||
result.push(node);
|
||||
|
||||
if (!node.collapsed) {
|
||||
getVisibleNodes(node.children, result);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function getTreeElementIterator<T>(elements: Iterator<ITreeElement<T>> | ITreeElement<T>[] | undefined): Iterator<ITreeElement<T>> {
|
||||
if (!elements) {
|
||||
return Iterator.empty();
|
||||
} else if (Array.isArray(elements)) {
|
||||
return Iterator.iterate(elements);
|
||||
} else {
|
||||
return elements;
|
||||
}
|
||||
}
|
||||
|
||||
function treeElementToNode<T>(treeElement: ITreeElement<T>, parent: IMutableTreeNode<T>, visible: boolean, treeListElements: ITreeNode<T>[]): IMutableTreeNode<T> {
|
||||
const depth = parent.depth + 1;
|
||||
const { element, collapsible, collapsed } = treeElement;
|
||||
const node = { parent, element, children: [], depth, collapsible: !!collapsible, collapsed: !!collapsed, visibleCount: 0 };
|
||||
|
||||
if (visible) {
|
||||
treeListElements.push(node);
|
||||
}
|
||||
|
||||
const children = getTreeElementIterator(treeElement.children);
|
||||
node.children = Iterator.collect(Iterator.map(children, el => treeElementToNode(el, node, visible && !treeElement.collapsed, treeListElements)));
|
||||
node.collapsible = node.collapsible || node.children.length > 0;
|
||||
node.visibleCount = 1 + getVisibleCount(node.children);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function treeNodeToElement<T>(node: IMutableTreeNode<T>): ITreeElement<T> {
|
||||
const { element, collapsed } = node;
|
||||
const children = Iterator.map(Iterator.iterate(node.children), treeNodeToElement);
|
||||
|
||||
return { element, children, collapsed };
|
||||
}
|
||||
|
||||
export function getNodeLocation<T>(node: ITreeNode<T>): number[] {
|
||||
const location = [];
|
||||
|
||||
while (node.parent) {
|
||||
location.push(node.parent.children.indexOf(node));
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
return location.reverse();
|
||||
}
|
||||
|
||||
export class TreeModel<T> {
|
||||
|
||||
private root: IMutableTreeNode<T> = {
|
||||
parent: undefined,
|
||||
element: undefined,
|
||||
children: [],
|
||||
depth: 0,
|
||||
collapsible: false,
|
||||
collapsed: false,
|
||||
visibleCount: 1
|
||||
};
|
||||
|
||||
private _onDidChangeCollapseState = new Emitter<ITreeNode<T>>();
|
||||
readonly onDidChangeCollapseState: Event<ITreeNode<T>> = this._onDidChangeCollapseState.event;
|
||||
|
||||
constructor(private list: ISpliceable<ITreeNode<T>>) { }
|
||||
|
||||
splice(location: number[], deleteCount: number, toInsert?: ISequence<ITreeElement<T>>): Iterator<ITreeElement<T>> {
|
||||
if (location.length === 0) {
|
||||
throw new Error('Invalid tree location');
|
||||
}
|
||||
|
||||
const { parentNode, listIndex, visible } = this.findParentNode(location);
|
||||
const treeListElementsToInsert: ITreeNode<T>[] = [];
|
||||
const elementsToInsert = getTreeElementIterator(toInsert);
|
||||
const nodesToInsert = Iterator.collect(Iterator.map(elementsToInsert, el => treeElementToNode(el, parentNode, visible, treeListElementsToInsert)));
|
||||
const lastIndex = location[location.length - 1];
|
||||
const deletedNodes = parentNode.children.splice(lastIndex, deleteCount, ...nodesToInsert);
|
||||
const visibleDeleteCount = getVisibleCount(deletedNodes);
|
||||
|
||||
parentNode.visibleCount += getVisibleCount(nodesToInsert) - visibleDeleteCount;
|
||||
|
||||
if (visible) {
|
||||
this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert);
|
||||
}
|
||||
|
||||
return Iterator.map(Iterator.iterate(deletedNodes), treeNodeToElement);
|
||||
}
|
||||
|
||||
getListIndex(location: number[]): number {
|
||||
return this.findNode(location).listIndex;
|
||||
}
|
||||
|
||||
setCollapsed(location: number[], collapsed: boolean): boolean {
|
||||
return this._setCollapsed(location, collapsed);
|
||||
}
|
||||
|
||||
toggleCollapsed(location: number[]): void {
|
||||
this._setCollapsed(location);
|
||||
}
|
||||
|
||||
private _setCollapsed(location: number[], collapsed?: boolean | undefined): boolean {
|
||||
const { node, listIndex, visible } = this.findNode(location);
|
||||
|
||||
if (!node.collapsible) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof collapsed === 'undefined') {
|
||||
collapsed = !node.collapsed;
|
||||
}
|
||||
|
||||
if (node.collapsed === collapsed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
node.collapsed = collapsed;
|
||||
|
||||
if (visible) {
|
||||
this._onDidChangeCollapseState.fire(node);
|
||||
|
||||
let visibleCountDiff: number;
|
||||
|
||||
if (collapsed) {
|
||||
const deleteCount = getVisibleCount(node.children);
|
||||
|
||||
this.list.splice(listIndex + 1, deleteCount, []);
|
||||
visibleCountDiff = -deleteCount;
|
||||
} else {
|
||||
const toInsert = getVisibleNodes(node.children);
|
||||
|
||||
this.list.splice(listIndex + 1, 0, toInsert);
|
||||
visibleCountDiff = toInsert.length;
|
||||
}
|
||||
|
||||
let mutableNode = node;
|
||||
|
||||
while (mutableNode) {
|
||||
mutableNode.visibleCount += visibleCountDiff;
|
||||
mutableNode = mutableNode.parent;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
isCollapsed(location: number[]): boolean {
|
||||
return this.findNode(location).node.collapsed;
|
||||
}
|
||||
|
||||
private findNode(location: number[]): { node: IMutableTreeNode<T>, listIndex: number, visible: boolean } {
|
||||
const { parentNode, listIndex, visible } = this.findParentNode(location);
|
||||
const index = location[location.length - 1];
|
||||
|
||||
if (index < 0 || index > parentNode.children.length) {
|
||||
throw new Error('Invalid tree location');
|
||||
}
|
||||
|
||||
const node = parentNode.children[index];
|
||||
|
||||
return { node, listIndex, visible };
|
||||
}
|
||||
|
||||
private findParentNode(location: number[], node: IMutableTreeNode<T> = this.root, listIndex: number = 0, visible = true): { parentNode: IMutableTreeNode<T>; listIndex: number; visible: boolean; } {
|
||||
const [index, ...rest] = location;
|
||||
|
||||
if (index < 0 || index > node.children.length) {
|
||||
throw new Error('Invalid tree location');
|
||||
}
|
||||
|
||||
// TODO@joao perf!
|
||||
for (let i = 0; i < index; i++) {
|
||||
listIndex += node.children[i].visibleCount;
|
||||
}
|
||||
|
||||
visible = visible && !node.collapsed;
|
||||
|
||||
if (rest.length === 0) {
|
||||
return { parentNode: node, listIndex, visible };
|
||||
}
|
||||
|
||||
return this.findParentNode(rest, node.children[index], listIndex + 1, visible);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
'use strict';
|
||||
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { IDisposable, combinedDisposable } from 'vs/base/common/lifecycle';
|
||||
import { Event, Emitter } from 'vs/base/common/event';
|
||||
|
||||
export interface ITelemetryData {
|
||||
@@ -237,3 +237,26 @@ export class ActionRunner implements IActionRunner {
|
||||
this._onDidRun.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export class RadioGroup {
|
||||
|
||||
private _disposable: IDisposable;
|
||||
|
||||
constructor(readonly actions: Action[]) {
|
||||
this._disposable = combinedDisposable(actions.map(action => {
|
||||
return action.onDidChange(e => {
|
||||
if (e.checked && action.checked) {
|
||||
for (const candidate of actions) {
|
||||
if (candidate !== action) {
|
||||
candidate.checked = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this._disposable.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,11 +12,19 @@ import { ISplice } from 'vs/base/common/sequence';
|
||||
* @param array The array.
|
||||
* @param n Which element from the end (default is zero).
|
||||
*/
|
||||
export function tail<T>(array: T[], n: number = 0): T {
|
||||
export function tail<T>(array: ArrayLike<T>, n: number = 0): T {
|
||||
return array[array.length - (1 + n)];
|
||||
}
|
||||
|
||||
export function equals<T>(one: T[], other: T[], itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean {
|
||||
export function tail2<T>(arr: T[]): [T[], T] {
|
||||
if (arr.length === 0) {
|
||||
throw new Error('Invalid tail call');
|
||||
}
|
||||
|
||||
return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
|
||||
}
|
||||
|
||||
export function equals<T>(one: ReadonlyArray<T>, other: ReadonlyArray<T>, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean {
|
||||
if (one.length !== other.length) {
|
||||
return false;
|
||||
}
|
||||
@@ -69,48 +77,56 @@ export function findFirstInSorted<T>(array: T[], p: (x: T) => boolean): number {
|
||||
return low;
|
||||
}
|
||||
|
||||
type Compare<T> = (a: T, b: T) => number;
|
||||
|
||||
/**
|
||||
* Like `Array#sort` but always stable. Usually runs a little slower `than Array#sort`
|
||||
* so only use this when actually needing stable sort.
|
||||
*/
|
||||
export function mergeSort<T>(data: T[], compare: (a: T, b: T) => number): T[] {
|
||||
_divideAndMerge(data, compare);
|
||||
export function mergeSort<T>(data: T[], compare: Compare<T>): T[] {
|
||||
_sort(data, compare, 0, data.length - 1, []);
|
||||
return data;
|
||||
}
|
||||
|
||||
function _divideAndMerge<T>(data: T[], compare: (a: T, b: T) => number): void {
|
||||
if (data.length <= 1) {
|
||||
// sorted
|
||||
return;
|
||||
function _merge<T>(a: T[], compare: Compare<T>, lo: number, mid: number, hi: number, aux: T[]): void {
|
||||
let leftIdx = lo, rightIdx = mid + 1;
|
||||
for (let i = lo; i <= hi; i++) {
|
||||
aux[i] = a[i];
|
||||
}
|
||||
const p = (data.length / 2) | 0;
|
||||
const left = data.slice(0, p);
|
||||
const right = data.slice(p);
|
||||
|
||||
_divideAndMerge(left, compare);
|
||||
_divideAndMerge(right, compare);
|
||||
|
||||
let leftIdx = 0;
|
||||
let rightIdx = 0;
|
||||
let i = 0;
|
||||
while (leftIdx < left.length && rightIdx < right.length) {
|
||||
let ret = compare(left[leftIdx], right[rightIdx]);
|
||||
if (ret <= 0) {
|
||||
// smaller_equal -> take left to preserve order
|
||||
data[i++] = left[leftIdx++];
|
||||
for (let i = lo; i <= hi; i++) {
|
||||
if (leftIdx > mid) {
|
||||
// left side consumed
|
||||
a[i] = aux[rightIdx++];
|
||||
} else if (rightIdx > hi) {
|
||||
// right side consumed
|
||||
a[i] = aux[leftIdx++];
|
||||
} else if (compare(aux[rightIdx], aux[leftIdx]) < 0) {
|
||||
// right element is less -> comes first
|
||||
a[i] = aux[rightIdx++];
|
||||
} else {
|
||||
// greater -> take right
|
||||
data[i++] = right[rightIdx++];
|
||||
// left element comes first (less or equal)
|
||||
a[i] = aux[leftIdx++];
|
||||
}
|
||||
}
|
||||
while (leftIdx < left.length) {
|
||||
data[i++] = left[leftIdx++];
|
||||
}
|
||||
while (rightIdx < right.length) {
|
||||
data[i++] = right[rightIdx++];
|
||||
}
|
||||
}
|
||||
|
||||
function _sort<T>(a: T[], compare: Compare<T>, lo: number, hi: number, aux: T[]) {
|
||||
if (hi <= lo) {
|
||||
return;
|
||||
}
|
||||
let mid = lo + ((hi - lo) / 2) | 0;
|
||||
_sort(a, compare, lo, mid, aux);
|
||||
_sort(a, compare, mid + 1, hi, aux);
|
||||
if (compare(a[mid], a[mid + 1]) <= 0) {
|
||||
// left and right are sorted and if the last-left element is less
|
||||
// or equals than the first-right element there is nothing else
|
||||
// to do
|
||||
return;
|
||||
}
|
||||
_merge(a, compare, lo, mid, hi, aux);
|
||||
}
|
||||
|
||||
|
||||
export function groupBy<T>(data: T[], compare: (a: T, b: T) => number): T[][] {
|
||||
const result: T[][] = [];
|
||||
let currentGroup: T[];
|
||||
@@ -276,12 +292,27 @@ function topStep<T>(array: T[], compare: (a: T, b: T) => number, result: T[], i:
|
||||
/**
|
||||
* @returns a new array with all undefined or null values removed. The original array is not modified at all.
|
||||
*/
|
||||
export function coalesce<T>(array: T[]): T[] {
|
||||
export function coalesce<T>(array: T[]): T[];
|
||||
export function coalesce<T>(array: T[], inplace: true): void;
|
||||
export function coalesce<T>(array: T[], inplace?: true): void | T[] {
|
||||
if (!array) {
|
||||
return array;
|
||||
if (!inplace) {
|
||||
return array;
|
||||
}
|
||||
}
|
||||
if (!inplace) {
|
||||
return array.filter(e => !!e);
|
||||
|
||||
return array.filter(e => !!e);
|
||||
} else {
|
||||
let to = 0;
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (!!array[i]) {
|
||||
array[to] = array[i];
|
||||
to += 1;
|
||||
}
|
||||
}
|
||||
array.length = to;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -338,7 +369,7 @@ export function uniqueFilter<T>(keyFn: (t: T) => string): (t: T) => boolean {
|
||||
};
|
||||
}
|
||||
|
||||
export function firstIndex<T>(array: T[], fn: (item: T) => boolean): number {
|
||||
export function firstIndex<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => boolean): number {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const element = array[i];
|
||||
|
||||
@@ -350,7 +381,7 @@ export function firstIndex<T>(array: T[], fn: (item: T) => boolean): number {
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function first<T>(array: T[], fn: (item: T) => boolean, notFoundValue: T = null): T {
|
||||
export function first<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => boolean, notFoundValue: T = null): T {
|
||||
const index = firstIndex(array, fn);
|
||||
return index < 0 ? notFoundValue : array[index];
|
||||
}
|
||||
@@ -443,15 +474,44 @@ export function arrayInsert<T>(target: T[], insertIndex: number, insertArr: T[])
|
||||
* Uses Fisher-Yates shuffle to shuffle the given array
|
||||
* @param array
|
||||
*/
|
||||
export function shuffle<T>(array: T[]): void {
|
||||
var i = 0
|
||||
, j = 0
|
||||
, temp = null;
|
||||
export function shuffle<T>(array: T[], seed?: number): void {
|
||||
// Seeded random number generator in JS. Modified from:
|
||||
// https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript
|
||||
const random = () => {
|
||||
var x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias
|
||||
return x - Math.floor(x);
|
||||
};
|
||||
|
||||
for (i = array.length - 1; i > 0; i -= 1) {
|
||||
j = Math.floor(Math.random() * (i + 1));
|
||||
temp = array[i];
|
||||
const rand = typeof seed === 'number' ? random : Math.random;
|
||||
|
||||
for (let i = array.length - 1; i > 0; i -= 1) {
|
||||
let j = Math.floor(rand() * (i + 1));
|
||||
let temp = array[i];
|
||||
array[i] = array[j];
|
||||
array[j] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes an element to the start of the array, if found.
|
||||
*/
|
||||
export function pushToStart<T>(arr: T[], value: T): void {
|
||||
const index = arr.indexOf(value);
|
||||
|
||||
if (index > -1) {
|
||||
arr.splice(index, 1);
|
||||
arr.unshift(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes an element to the end of the array, if found.
|
||||
*/
|
||||
export function pushToEnd<T>(arr: T[], value: T): void {
|
||||
const index = arr.indexOf(value);
|
||||
|
||||
if (index > -1) {
|
||||
arr.splice(index, 1);
|
||||
arr.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
'use strict';
|
||||
|
||||
import * as errors from 'vs/base/common/errors';
|
||||
import { Promise, TPromise, ValueCallback, ErrorCallback, ProgressCallback } from 'vs/base/common/winjs.base';
|
||||
import { TPromise, ValueCallback, ErrorCallback, ProgressCallback } from 'vs/base/common/winjs.base';
|
||||
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
|
||||
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
|
||||
import { Event, Emitter } from 'vs/base/common/event';
|
||||
@@ -24,6 +24,48 @@ export function toThenable<T>(arg: T | Thenable<T>): Thenable<T> {
|
||||
}
|
||||
}
|
||||
|
||||
export function toWinJsPromise<T>(arg: Thenable<T> | TPromise<T>): TPromise<T> {
|
||||
if (arg instanceof TPromise) {
|
||||
return arg;
|
||||
}
|
||||
|
||||
return new TPromise((resolve, reject) => arg.then(resolve, reject));
|
||||
}
|
||||
|
||||
export interface CancelablePromise<T> extends Promise<T> {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
export function createCancelablePromise<T>(callback: (token: CancellationToken) => Thenable<T>): CancelablePromise<T> {
|
||||
const source = new CancellationTokenSource();
|
||||
|
||||
const thenable = callback(source.token);
|
||||
const promise = new Promise<T>((resolve, reject) => {
|
||||
source.token.onCancellationRequested(() => {
|
||||
reject(errors.canceled());
|
||||
});
|
||||
Promise.resolve(thenable).then(value => {
|
||||
source.dispose();
|
||||
resolve(value);
|
||||
}, err => {
|
||||
source.dispose();
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
|
||||
return new class implements CancelablePromise<T> {
|
||||
cancel() {
|
||||
source.cancel();
|
||||
}
|
||||
then<TResult1 = T, TResult2 = never>(resolve?: ((value: T) => TResult1 | Thenable<TResult1>) | undefined | null, reject?: ((reason: any) => TResult2 | Thenable<TResult2>) | undefined | null): Promise<TResult1 | TResult2> {
|
||||
return promise.then(resolve, reject);
|
||||
}
|
||||
catch<TResult = never>(reject?: ((reason: any) => TResult | Thenable<TResult>) | undefined | null): Promise<T | TResult> {
|
||||
return this.then(undefined, reject);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function asWinJsPromise<T>(callback: (token: CancellationToken) => T | TPromise<T> | Thenable<T>): TPromise<T> {
|
||||
let source = new CancellationTokenSource();
|
||||
return new TPromise<T>((resolve, reject, progress) => {
|
||||
@@ -69,6 +111,33 @@ export function wireCancellationToken<T>(token: CancellationToken, promise: TPro
|
||||
return always(promise, () => subscription.dispose());
|
||||
}
|
||||
|
||||
export function asDisposablePromise<T>(input: Thenable<T>, cancelValue?: T, bucket?: IDisposable[]): { promise: Thenable<T> } & IDisposable {
|
||||
let dispose: () => void;
|
||||
let promise = new TPromise((resolve, reject) => {
|
||||
dispose = function () {
|
||||
resolve(cancelValue);
|
||||
if (isWinJSPromise(input)) {
|
||||
input.cancel();
|
||||
}
|
||||
};
|
||||
input.then(resolve, err => {
|
||||
if (errors.isPromiseCanceledError(err)) {
|
||||
resolve(cancelValue);
|
||||
} else {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
let res = {
|
||||
promise,
|
||||
dispose
|
||||
};
|
||||
if (Array.isArray(bucket)) {
|
||||
bucket.push(res);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
export interface ITask<T> {
|
||||
(): T;
|
||||
}
|
||||
@@ -101,9 +170,9 @@ export interface ITask<T> {
|
||||
*/
|
||||
export class Throttler {
|
||||
|
||||
private activePromise: Promise;
|
||||
private queuedPromise: Promise;
|
||||
private queuedPromiseFactory: ITask<Promise>;
|
||||
private activePromise: TPromise;
|
||||
private queuedPromise: TPromise;
|
||||
private queuedPromiseFactory: ITask<TPromise>;
|
||||
|
||||
constructor() {
|
||||
this.activePromise = null;
|
||||
@@ -169,7 +238,7 @@ export class SimpleThrottler {
|
||||
* A helper to delay execution of a task that is being requested often.
|
||||
*
|
||||
* Following the throttler, now imagine the mail man wants to optimize the number of
|
||||
* trips proactively. The trip itself can be long, so the he decides not to make the trip
|
||||
* trips proactively. The trip itself can be long, so he decides not to make the trip
|
||||
* as soon as a letter is submitted. Instead he waits a while, in case more
|
||||
* letters are submitted. After said waiting period, if no letters were submitted, he
|
||||
* decides to make the trip. Imagine that N more letters were submitted after the first
|
||||
@@ -191,7 +260,7 @@ export class SimpleThrottler {
|
||||
export class Delayer<T> {
|
||||
|
||||
private timeout: number;
|
||||
private completionPromise: Promise;
|
||||
private completionPromise: TPromise;
|
||||
private onSuccess: ValueCallback;
|
||||
private task: ITask<T | TPromise<T>>;
|
||||
|
||||
@@ -254,7 +323,7 @@ export class Delayer<T> {
|
||||
* A helper to delay execution of a task that is being requested often, while
|
||||
* preventing accumulation of consecutive executions, while the task runs.
|
||||
*
|
||||
* Simply combine the two mail man strategies from the Throttler and Delayer
|
||||
* Simply combine the two mail men's strategies from the Throttler and Delayer
|
||||
* helpers, for an analogy.
|
||||
*/
|
||||
export class ThrottledDelayer<T> extends Delayer<TPromise<T>> {
|
||||
@@ -283,7 +352,7 @@ export class Barrier {
|
||||
|
||||
constructor() {
|
||||
this._isOpen = false;
|
||||
this._promise = new TPromise<boolean>((c, e, p) => {
|
||||
this._promise = new TPromise<boolean>((c, e) => {
|
||||
this._completePromise = c;
|
||||
}, () => {
|
||||
console.warn('You should really not try to cancel this ready promise!');
|
||||
@@ -327,10 +396,18 @@ export class ShallowCancelThenPromise<T> extends TPromise<T> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Replacement for `WinJS.Promise.timeout`.
|
||||
* Replacement for `WinJS.TPromise.timeout`.
|
||||
*/
|
||||
export function timeout(n: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, n));
|
||||
export function timeout(n: number): CancelablePromise<void> {
|
||||
return createCancelablePromise(token => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const handle = setTimeout(resolve, n);
|
||||
token.onCancellationRequested(_ => {
|
||||
clearTimeout(handle);
|
||||
reject(errors.canceled());
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isWinJSPromise(candidate: any): candidate is TPromise {
|
||||
@@ -384,16 +461,11 @@ export function always<T>(winjsPromiseOrThenable: Thenable<T> | TPromise<T>, f:
|
||||
|
||||
export function sequence<T>(promiseFactories: ITask<Thenable<T>>[]): TPromise<T[]> {
|
||||
const results: T[] = [];
|
||||
let index = 0;
|
||||
const len = promiseFactories.length;
|
||||
|
||||
// reverse since we start with last element using pop()
|
||||
promiseFactories = promiseFactories.reverse();
|
||||
|
||||
function next(): Thenable<any> {
|
||||
if (promiseFactories.length) {
|
||||
return promiseFactories.pop()();
|
||||
}
|
||||
|
||||
return null;
|
||||
function next(): Thenable<T> | null {
|
||||
return index < len ? promiseFactories[index++]() : null;
|
||||
}
|
||||
|
||||
function thenHandler(result: any): Thenable<any> {
|
||||
@@ -412,15 +484,38 @@ export function sequence<T>(promiseFactories: ITask<Thenable<T>>[]): TPromise<T[
|
||||
return TPromise.as(null).then(thenHandler);
|
||||
}
|
||||
|
||||
export function first<T>(promiseFactories: ITask<TPromise<T>>[], shouldStop: (t: T) => boolean = t => !!t): TPromise<T> {
|
||||
promiseFactories = [...promiseFactories.reverse()];
|
||||
export function first2<T>(promiseFactories: ITask<Promise<T>>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T = null): Promise<T> {
|
||||
|
||||
let index = 0;
|
||||
const len = promiseFactories.length;
|
||||
|
||||
const loop = () => {
|
||||
if (index >= len) {
|
||||
return Promise.resolve(defaultValue);
|
||||
}
|
||||
const factory = promiseFactories[index++];
|
||||
const promise = factory();
|
||||
return promise.then(result => {
|
||||
if (shouldStop(result)) {
|
||||
return Promise.resolve(result);
|
||||
}
|
||||
return loop();
|
||||
});
|
||||
};
|
||||
|
||||
return loop();
|
||||
}
|
||||
|
||||
export function first<T>(promiseFactories: ITask<TPromise<T>>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T = null): TPromise<T> {
|
||||
let index = 0;
|
||||
const len = promiseFactories.length;
|
||||
|
||||
const loop: () => TPromise<T> = () => {
|
||||
if (promiseFactories.length === 0) {
|
||||
return TPromise.as(null);
|
||||
if (index >= len) {
|
||||
return TPromise.as(defaultValue);
|
||||
}
|
||||
|
||||
const factory = promiseFactories.pop();
|
||||
const factory = promiseFactories[index++];
|
||||
const promise = factory();
|
||||
|
||||
return promise.then(result => {
|
||||
@@ -436,7 +531,7 @@ export function first<T>(promiseFactories: ITask<TPromise<T>>[], shouldStop: (t:
|
||||
}
|
||||
|
||||
interface ILimitedTaskFactory {
|
||||
factory: ITask<Promise>;
|
||||
factory: ITask<TPromise>;
|
||||
c: ValueCallback;
|
||||
e: ErrorCallback;
|
||||
p: ProgressCallback;
|
||||
@@ -467,7 +562,7 @@ export class Limiter<T> {
|
||||
return this.runningPromises + this.outstandingPromises.length;
|
||||
}
|
||||
|
||||
queue(promiseFactory: ITask<Promise>): Promise;
|
||||
queue(promiseFactory: ITask<TPromise>): TPromise;
|
||||
queue(promiseFactory: ITask<TPromise<T>>): TPromise<T> {
|
||||
return new TPromise<T>((c, e, p) => {
|
||||
this.outstandingPromises.push({
|
||||
@@ -620,12 +715,13 @@ export class IntervalTimer extends Disposable {
|
||||
|
||||
export class RunOnceScheduler {
|
||||
|
||||
protected runner: (...args: any[]) => void;
|
||||
|
||||
private timeoutToken: number;
|
||||
private runner: () => void;
|
||||
private timeout: number;
|
||||
private timeoutHandler: () => void;
|
||||
|
||||
constructor(runner: () => void, timeout: number) {
|
||||
constructor(runner: (...args: any[]) => void, timeout: number) {
|
||||
this.timeoutToken = -1;
|
||||
this.runner = runner;
|
||||
this.timeout = timeout;
|
||||
@@ -668,61 +764,52 @@ export class RunOnceScheduler {
|
||||
private onTimeout() {
|
||||
this.timeoutToken = -1;
|
||||
if (this.runner) {
|
||||
this.runner();
|
||||
this.doRun();
|
||||
}
|
||||
}
|
||||
|
||||
protected doRun(): void {
|
||||
this.runner();
|
||||
}
|
||||
}
|
||||
|
||||
export function nfcall(fn: Function, ...args: any[]): Promise;
|
||||
export class RunOnceWorker<T> extends RunOnceScheduler {
|
||||
private units: T[] = [];
|
||||
|
||||
constructor(runner: (units: T[]) => void, timeout: number) {
|
||||
super(runner, timeout);
|
||||
}
|
||||
|
||||
work(unit: T): void {
|
||||
this.units.push(unit);
|
||||
|
||||
if (!this.isScheduled()) {
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
|
||||
protected doRun(): void {
|
||||
const units = this.units;
|
||||
this.units = [];
|
||||
|
||||
this.runner(units);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.units = [];
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export function nfcall(fn: Function, ...args: any[]): TPromise;
|
||||
export function nfcall<T>(fn: Function, ...args: any[]): TPromise<T>;
|
||||
export function nfcall(fn: Function, ...args: any[]): any {
|
||||
return new TPromise((c, e) => fn(...args, (err: any, result: any) => err ? e(err) : c(result)), () => null);
|
||||
}
|
||||
|
||||
export function ninvoke(thisArg: any, fn: Function, ...args: any[]): Promise;
|
||||
export function ninvoke(thisArg: any, fn: Function, ...args: any[]): TPromise;
|
||||
export function ninvoke<T>(thisArg: any, fn: Function, ...args: any[]): TPromise<T>;
|
||||
export function ninvoke(thisArg: any, fn: Function, ...args: any[]): any {
|
||||
return new TPromise((c, e) => fn.call(thisArg, ...args, (err: any, result: any) => err ? e(err) : c(result)), () => null);
|
||||
}
|
||||
|
||||
/**
|
||||
* An emitter that will ignore any events that occur during a specific code
|
||||
* execution triggered via throttle() until the promise has finished (either
|
||||
* successfully or with an error). Only after the promise has finished, the
|
||||
* last event that was fired during the operation will get emitted.
|
||||
*
|
||||
*/
|
||||
export class ThrottledEmitter<T> extends Emitter<T> {
|
||||
private suspended: boolean;
|
||||
|
||||
private lastEvent: T;
|
||||
private hasLastEvent: boolean;
|
||||
|
||||
public throttle<C>(promise: TPromise<C>): TPromise<C> {
|
||||
this.suspended = true;
|
||||
|
||||
return always(promise, () => this.resume());
|
||||
}
|
||||
|
||||
public fire(event?: T): any {
|
||||
if (this.suspended) {
|
||||
this.lastEvent = event;
|
||||
this.hasLastEvent = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return super.fire(event);
|
||||
}
|
||||
|
||||
private resume(): void {
|
||||
this.suspended = false;
|
||||
|
||||
if (this.hasLastEvent) {
|
||||
this.fire(this.lastEvent);
|
||||
}
|
||||
|
||||
this.hasLastEvent = false;
|
||||
this.lastEvent = void 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,15 @@ export function size<T>(from: IStringDictionary<T> | INumberDictionary<T>): numb
|
||||
return count;
|
||||
}
|
||||
|
||||
export function first<T>(from: IStringDictionary<T> | INumberDictionary<T>): T {
|
||||
for (let key in from) {
|
||||
if (hasOwnProperty.call(from, key)) {
|
||||
return from[key];
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates over each entry in the provided set. The iterator allows
|
||||
* to remove elements and will stop when the callback returns {{false}}.
|
||||
|
||||
@@ -114,7 +114,7 @@ export class HSLA {
|
||||
return new HSLA(h, s, l, a);
|
||||
}
|
||||
|
||||
private static _hue2rgb(p: number, q: number, t: number) {
|
||||
private static _hue2rgb(p: number, q: number, t: number): number {
|
||||
if (t < 0) {
|
||||
t += 1;
|
||||
}
|
||||
|
||||
@@ -5,21 +5,15 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
function pad(number: number): string {
|
||||
if (number < 10) {
|
||||
return '0' + number;
|
||||
}
|
||||
|
||||
return String(number);
|
||||
}
|
||||
import { pad } from './strings';
|
||||
|
||||
export function toLocalISOString(date: Date): string {
|
||||
return date.getFullYear() +
|
||||
'-' + pad(date.getMonth() + 1) +
|
||||
'-' + pad(date.getDate()) +
|
||||
'T' + pad(date.getHours()) +
|
||||
':' + pad(date.getMinutes()) +
|
||||
':' + pad(date.getSeconds()) +
|
||||
'-' + pad(date.getMonth() + 1, 2) +
|
||||
'-' + pad(date.getDate(), 2) +
|
||||
'T' + pad(date.getHours(), 2) +
|
||||
':' + pad(date.getMinutes(), 2) +
|
||||
':' + pad(date.getSeconds(), 2) +
|
||||
'.' + (date.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
|
||||
'Z';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,19 +69,23 @@ export interface IDebouceReducer<T> {
|
||||
export function debounce<T>(delay: number, reducer?: IDebouceReducer<T>, initialValueProvider?: () => T): Function {
|
||||
return createDecorator((fn, key) => {
|
||||
const timerKey = `$debounce$${key}`;
|
||||
let result = initialValueProvider ? initialValueProvider() : void 0;
|
||||
const resultKey = `$debounce$result$${key}`;
|
||||
|
||||
return function (this: any, ...args: any[]) {
|
||||
if (!this[resultKey]) {
|
||||
this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
|
||||
}
|
||||
|
||||
clearTimeout(this[timerKey]);
|
||||
|
||||
if (reducer) {
|
||||
result = reducer(result, ...args);
|
||||
args = [result];
|
||||
this[resultKey] = reducer(this[resultKey], ...args);
|
||||
args = [this[resultKey]];
|
||||
}
|
||||
|
||||
this[timerKey] = setTimeout(() => {
|
||||
fn.apply(this, args);
|
||||
result = initialValueProvider ? initialValueProvider() : void 0;
|
||||
this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
|
||||
}, delay);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import * as Platform from 'vs/base/common/platform';
|
||||
|
||||
/**
|
||||
* To enable diagnostics, open a browser console and type: window.Monaco.Diagnostics.<diagnostics name> = true.
|
||||
* Then trigger an action that will write to diagnostics to see all cached output from the past.
|
||||
*/
|
||||
|
||||
const globals = Platform.globals;
|
||||
if (!globals.Monaco) {
|
||||
globals.Monaco = {};
|
||||
}
|
||||
globals.Monaco.Diagnostics = {};
|
||||
|
||||
const switches = globals.Monaco.Diagnostics;
|
||||
const map = new Map<string, Function[]>();
|
||||
const data: any[] = [];
|
||||
|
||||
function fifo(array: any[], size: number) {
|
||||
while (array.length > size) {
|
||||
array.shift();
|
||||
}
|
||||
}
|
||||
|
||||
export function register(what: string, fn: Function): (...args: any[]) => void {
|
||||
|
||||
let disable = true; // Otherwise we have unreachable code.
|
||||
if (disable) {
|
||||
return () => {
|
||||
// Intentional empty, disable for now because it is leaking memory
|
||||
};
|
||||
}
|
||||
|
||||
// register switch
|
||||
const flag = switches[what] || false;
|
||||
switches[what] = flag;
|
||||
|
||||
// register function
|
||||
const tracers = map.get(what) || [];
|
||||
tracers.push(fn);
|
||||
map.set(what, tracers);
|
||||
|
||||
const result = function (...args: any[]) {
|
||||
|
||||
let idx: number;
|
||||
|
||||
if (switches[what] === true) {
|
||||
// replay back-in-time functions
|
||||
const allArgs = [arguments];
|
||||
idx = data.indexOf(fn);
|
||||
if (idx !== -1) {
|
||||
allArgs.unshift.apply(allArgs, data[idx + 1] || []);
|
||||
data[idx + 1] = [];
|
||||
}
|
||||
|
||||
const doIt: () => void = function () {
|
||||
const thisArguments = allArgs.shift();
|
||||
fn.apply(fn, thisArguments);
|
||||
if (allArgs.length > 0) {
|
||||
setTimeout(doIt, 500);
|
||||
}
|
||||
};
|
||||
doIt();
|
||||
|
||||
} else {
|
||||
// know where to store
|
||||
idx = data.indexOf(fn);
|
||||
idx = idx !== -1 ? idx : data.length;
|
||||
const dataIdx = idx + 1;
|
||||
|
||||
// store arguments
|
||||
const allargs = data[dataIdx] || [];
|
||||
allargs.push(arguments);
|
||||
fifo(allargs, 50);
|
||||
|
||||
// store data
|
||||
data[idx] = fn;
|
||||
data[dataIdx] = allargs;
|
||||
}
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -6,12 +6,10 @@
|
||||
|
||||
import { DiffChange } from 'vs/base/common/diff/diffChange';
|
||||
|
||||
|
||||
function createStringSequence(a: string): ISequence {
|
||||
|
||||
return {
|
||||
getLength() { return a.length; },
|
||||
getElementHash(pos: number) { return a[pos]; }
|
||||
getElementAtIndex(pos: number) { return a.charCodeAt(pos); }
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,7 +20,7 @@ export function stringDiff(original: string, modified: string, pretty: boolean):
|
||||
|
||||
export interface ISequence {
|
||||
getLength(): number;
|
||||
getElementHash(index: number): string;
|
||||
getElementAtIndex(index: number): number | string;
|
||||
}
|
||||
|
||||
export interface IDiffChange {
|
||||
@@ -211,8 +209,6 @@ class DiffChangeHelper {
|
||||
|
||||
}
|
||||
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
|
||||
/**
|
||||
* An implementation of the difference algorithm described in
|
||||
* "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers
|
||||
@@ -223,8 +219,6 @@ export class LcsDiff {
|
||||
private ModifiedSequence: ISequence;
|
||||
private ContinueProcessingPredicate: IContinueProcessingPredicate;
|
||||
|
||||
private m_originalIds: number[];
|
||||
private m_modifiedIds: number[];
|
||||
private m_forwardHistory: number[][];
|
||||
private m_reverseHistory: number[][];
|
||||
|
||||
@@ -235,63 +229,21 @@ export class LcsDiff {
|
||||
this.OriginalSequence = originalSequence;
|
||||
this.ModifiedSequence = newSequence;
|
||||
this.ContinueProcessingPredicate = continueProcessingPredicate;
|
||||
this.m_originalIds = [];
|
||||
this.m_modifiedIds = [];
|
||||
|
||||
this.m_forwardHistory = [];
|
||||
this.m_reverseHistory = [];
|
||||
|
||||
this.ComputeUniqueIdentifiers();
|
||||
}
|
||||
|
||||
private ComputeUniqueIdentifiers(): void {
|
||||
let originalSequenceLength = this.OriginalSequence.getLength();
|
||||
let modifiedSequenceLength = this.ModifiedSequence.getLength();
|
||||
this.m_originalIds = new Array<number>(originalSequenceLength);
|
||||
this.m_modifiedIds = new Array<number>(modifiedSequenceLength);
|
||||
|
||||
// Create a new hash table for unique elements from the original
|
||||
// sequence.
|
||||
let hashTable: { [key: string]: number; } = {};
|
||||
let currentUniqueId = 1;
|
||||
let i: number;
|
||||
|
||||
// Fill up the hash table for unique elements
|
||||
for (i = 0; i < originalSequenceLength; i++) {
|
||||
let originalElementHash = this.OriginalSequence.getElementHash(i);
|
||||
if (!hasOwnProperty.call(hashTable, originalElementHash)) {
|
||||
// No entry in the hashtable so this is a new unique element.
|
||||
// Assign the element a new unique identifier and add it to the
|
||||
// hash table
|
||||
this.m_originalIds[i] = currentUniqueId++;
|
||||
hashTable[originalElementHash] = this.m_originalIds[i];
|
||||
} else {
|
||||
this.m_originalIds[i] = hashTable[originalElementHash];
|
||||
}
|
||||
}
|
||||
|
||||
// Now match up modified elements
|
||||
for (i = 0; i < modifiedSequenceLength; i++) {
|
||||
let modifiedElementHash = this.ModifiedSequence.getElementHash(i);
|
||||
if (!hasOwnProperty.call(hashTable, modifiedElementHash)) {
|
||||
this.m_modifiedIds[i] = currentUniqueId++;
|
||||
hashTable[modifiedElementHash] = this.m_modifiedIds[i];
|
||||
} else {
|
||||
this.m_modifiedIds[i] = hashTable[modifiedElementHash];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ElementsAreEqual(originalIndex: number, newIndex: number): boolean {
|
||||
return this.m_originalIds[originalIndex] === this.m_modifiedIds[newIndex];
|
||||
return (this.OriginalSequence.getElementAtIndex(originalIndex) === this.ModifiedSequence.getElementAtIndex(newIndex));
|
||||
}
|
||||
|
||||
private OriginalElementsAreEqual(index1: number, index2: number): boolean {
|
||||
return this.m_originalIds[index1] === this.m_originalIds[index2];
|
||||
return (this.OriginalSequence.getElementAtIndex(index1) === this.OriginalSequence.getElementAtIndex(index2));
|
||||
}
|
||||
|
||||
private ModifiedElementsAreEqual(index1: number, index2: number): boolean {
|
||||
return this.m_modifiedIds[index1] === this.m_modifiedIds[index2];
|
||||
return (this.ModifiedSequence.getElementAtIndex(index1) === this.ModifiedSequence.getElementAtIndex(index2));
|
||||
}
|
||||
|
||||
public ComputeDiff(pretty: boolean): IDiffChange[] {
|
||||
@@ -891,7 +843,8 @@ export class LcsDiff {
|
||||
if (index <= 0 || index >= this.OriginalSequence.getLength() - 1) {
|
||||
return true;
|
||||
}
|
||||
return /^\s*$/.test(this.OriginalSequence.getElementHash(index));
|
||||
const element = this.OriginalSequence.getElementAtIndex(index);
|
||||
return (typeof element === 'string' && /^\s*$/.test(element));
|
||||
}
|
||||
|
||||
private _OriginalRegionIsBoundary(originalStart: number, originalLength: number): boolean {
|
||||
@@ -911,7 +864,8 @@ export class LcsDiff {
|
||||
if (index <= 0 || index >= this.ModifiedSequence.getLength() - 1) {
|
||||
return true;
|
||||
}
|
||||
return /^\s*$/.test(this.ModifiedSequence.getElementHash(index));
|
||||
const element = this.ModifiedSequence.getElementAtIndex(index);
|
||||
return (typeof element === 'string' && /^\s*$/.test(element));
|
||||
}
|
||||
|
||||
private _ModifiedRegionIsBoundary(modifiedStart: number, modifiedLength: number): boolean {
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { IDisposable, toDisposable, combinedDisposable, empty as EmptyDisposable } from 'vs/base/common/lifecycle';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { once as onceFn } from 'vs/base/common/functional';
|
||||
import { onUnexpectedError } from 'vs/base/common/errors';
|
||||
import { once as onceFn } from 'vs/base/common/functional';
|
||||
import { combinedDisposable, Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
|
||||
import { LinkedList } from 'vs/base/common/linkedList';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
|
||||
/**
|
||||
* To an event a function with one or zero parameters
|
||||
@@ -58,9 +58,9 @@ export class Emitter<T> {
|
||||
private static readonly _noop = function () { };
|
||||
|
||||
private _event: Event<T>;
|
||||
private _listeners: LinkedList<Listener>;
|
||||
private _deliveryQueue: [Listener, T][];
|
||||
private _disposed: boolean;
|
||||
private _deliveryQueue: [Listener, T][];
|
||||
protected _listeners: LinkedList<Listener>;
|
||||
|
||||
constructor(private _options?: EmitterOptions) {
|
||||
|
||||
@@ -159,6 +159,52 @@ export class Emitter<T> {
|
||||
}
|
||||
}
|
||||
|
||||
export interface IWaitUntil {
|
||||
waitUntil(thenable: Thenable<any>): void;
|
||||
}
|
||||
|
||||
export class AsyncEmitter<T extends IWaitUntil> extends Emitter<T> {
|
||||
|
||||
private _asyncDeliveryQueue: [Listener, T, Thenable<any>[]][];
|
||||
|
||||
async fireAsync(eventFn: (thenables: Thenable<any>[], listener: Function) => T): Promise<void> {
|
||||
if (!this._listeners) {
|
||||
return;
|
||||
}
|
||||
|
||||
// put all [listener,event]-pairs into delivery queue
|
||||
// then emit all event. an inner/nested event might be
|
||||
// the driver of this
|
||||
if (!this._asyncDeliveryQueue) {
|
||||
this._asyncDeliveryQueue = [];
|
||||
}
|
||||
|
||||
for (let iter = this._listeners.iterator(), e = iter.next(); !e.done; e = iter.next()) {
|
||||
let thenables: Thenable<void>[] = [];
|
||||
this._asyncDeliveryQueue.push([e.value, eventFn(thenables, typeof e.value === 'function' ? e.value : e.value[0]), thenables]);
|
||||
}
|
||||
|
||||
while (this._asyncDeliveryQueue.length > 0) {
|
||||
const [listener, event, thenables] = this._asyncDeliveryQueue.shift();
|
||||
try {
|
||||
if (typeof listener === 'function') {
|
||||
listener.call(undefined, event);
|
||||
} else {
|
||||
listener[0].call(listener[1], event);
|
||||
}
|
||||
} catch (e) {
|
||||
onUnexpectedError(e);
|
||||
continue;
|
||||
}
|
||||
|
||||
// freeze thenables-collection to enforce sync-calls to
|
||||
// wait until and then wait for all thenables to resolve
|
||||
Object.freeze(thenables);
|
||||
await Promise.all(thenables);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class EventMultiplexer<T> implements IDisposable {
|
||||
|
||||
private readonly emitter: Emitter<T>;
|
||||
@@ -367,6 +413,7 @@ export interface IChainableEvent<T> {
|
||||
filter(fn: (e: T) => boolean): IChainableEvent<T>;
|
||||
latch(): IChainableEvent<T>;
|
||||
on(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]): IDisposable;
|
||||
once(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]): IDisposable;
|
||||
}
|
||||
|
||||
export function mapEvent<I, O>(event: Event<I>, map: (i: I) => O): Event<O> {
|
||||
@@ -377,6 +424,8 @@ export function forEach<I>(event: Event<I>, each: (i: I) => void): Event<I> {
|
||||
return (listener, thisArgs = null, disposables?) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables);
|
||||
}
|
||||
|
||||
export function filterEvent<T>(event: Event<T>, filter: (e: T) => boolean): Event<T>;
|
||||
export function filterEvent<T, R>(event: Event<T | R>, filter: (e: T | R) => e is R): Event<R>;
|
||||
export function filterEvent<T>(event: Event<T>, filter: (e: T) => boolean): Event<T> {
|
||||
return (listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables);
|
||||
}
|
||||
@@ -406,6 +455,10 @@ class ChainableEvent<T> implements IChainableEvent<T> {
|
||||
on(listener: (e: T) => any, thisArgs: any, disposables: IDisposable[]) {
|
||||
return this._event(listener, thisArgs, disposables);
|
||||
}
|
||||
|
||||
once(listener: (e: T) => any, thisArgs: any, disposables: IDisposable[]) {
|
||||
return once(this._event)(listener, thisArgs, disposables);
|
||||
}
|
||||
}
|
||||
|
||||
export function chain<T>(event: Event<T>): IChainableEvent<T> {
|
||||
@@ -513,7 +566,7 @@ export class Relay<T> implements IDisposable {
|
||||
private emitter = new Emitter<T>();
|
||||
readonly event: Event<T> = this.emitter.event;
|
||||
|
||||
private disposable: IDisposable = EmptyDisposable;
|
||||
private disposable: IDisposable = Disposable.None;
|
||||
|
||||
set input(event: Event<T>) {
|
||||
this.disposable.dispose();
|
||||
@@ -550,4 +603,4 @@ export function latch<T>(event: Event<T>): Event<T> {
|
||||
cache = value;
|
||||
return shouldEmit;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +255,8 @@ export function matchesCamelCase(word: string, camelCaseWord: string): IMatch[]
|
||||
let result: IMatch[] = null;
|
||||
let i = 0;
|
||||
|
||||
while (i < camelCaseWord.length && (result = _matchesCamelCase(word.toLowerCase(), camelCaseWord, 0, i)) === null) {
|
||||
word = word.toLowerCase();
|
||||
while (i < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i)) === null) {
|
||||
i = nextAnchor(camelCaseWord, i + 1);
|
||||
}
|
||||
|
||||
@@ -275,7 +276,9 @@ export function matchesWords(word: string, target: string, contiguous: boolean =
|
||||
let result: IMatch[] = null;
|
||||
let i = 0;
|
||||
|
||||
while (i < target.length && (result = _matchesWords(word.toLowerCase(), target, 0, i, contiguous)) === null) {
|
||||
word = word.toLowerCase();
|
||||
target = target.toLowerCase();
|
||||
while (i < target.length && (result = _matchesWords(word, target, 0, i, contiguous)) === null) {
|
||||
i = nextWord(target, i + 1);
|
||||
}
|
||||
|
||||
@@ -287,7 +290,7 @@ function _matchesWords(word: string, target: string, i: number, j: number, conti
|
||||
return [];
|
||||
} else if (j === target.length) {
|
||||
return null;
|
||||
} else if (word[i] !== target[j].toLowerCase()) {
|
||||
} else if (word[i] !== target[j]) {
|
||||
return null;
|
||||
} else {
|
||||
let result: IMatch[] = null;
|
||||
@@ -341,7 +344,7 @@ export function matchesFuzzy(word: string, wordToMatchAgainst: string, enableSep
|
||||
return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
|
||||
}
|
||||
|
||||
export function skipScore(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): [number, number[]] {
|
||||
export function anyScore(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): FuzzyScore {
|
||||
pattern = pattern.toLowerCase();
|
||||
word = word.toLowerCase();
|
||||
|
||||
@@ -452,7 +455,9 @@ function isWhitespaceAtPos(value: string, index: number): boolean {
|
||||
|
||||
const enum Arrow { Top = 0b1, Diag = 0b10, Left = 0b100 }
|
||||
|
||||
export function fuzzyScore(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): [number, number[]] {
|
||||
export type FuzzyScore = [number, number[]];
|
||||
|
||||
export function fuzzyScore(pattern: string, word: string, patternMaxWhitespaceIgnore?: number, firstMatchCanBeWeak?: boolean): FuzzyScore {
|
||||
|
||||
const patternLen = pattern.length > 100 ? 100 : pattern.length;
|
||||
const wordLen = word.length > 100 ? 100 : word.length;
|
||||
@@ -514,7 +519,7 @@ export function fuzzyScore(pattern: string, word: string, patternMaxWhitespaceIg
|
||||
} else {
|
||||
score = 5;
|
||||
}
|
||||
} else if (lowWordChar !== word[wordPos - 1]) {
|
||||
} else if (lowWordChar !== word[wordPos - 1] && (wordPos === 1 || lowWord[wordPos - 2] === word[wordPos - 2])) {
|
||||
// hitting upper-case: `foo <-> forOthers`
|
||||
if (pattern[patternPos - 1] === word[wordPos - 1]) {
|
||||
score = 7;
|
||||
@@ -576,6 +581,7 @@ export function fuzzyScore(pattern: string, word: string, patternMaxWhitespaceIg
|
||||
_matchesCount = 0;
|
||||
_topScore = -100;
|
||||
_patternStartPos = patternStartPos;
|
||||
_firstMatchCanBeWeak = firstMatchCanBeWeak;
|
||||
_findAllMatches(patternLen, wordLen, patternLen === wordLen ? 1 : 0, new LazyArray(), false);
|
||||
|
||||
if (_matchesCount === 0) {
|
||||
@@ -589,6 +595,7 @@ let _matchesCount: number = 0;
|
||||
let _topMatch: LazyArray;
|
||||
let _topScore: number = 0;
|
||||
let _patternStartPos: number = 0;
|
||||
let _firstMatchCanBeWeak: boolean = false;
|
||||
|
||||
function _findAllMatches(patternPos: number, wordPos: number, total: number, matches: LazyArray, lastMatched: boolean): void {
|
||||
|
||||
@@ -642,7 +649,7 @@ function _findAllMatches(patternPos: number, wordPos: number, total: number, mat
|
||||
if (score === 1) {
|
||||
simpleMatchCount += 1;
|
||||
|
||||
if (patternPos === _patternStartPos) {
|
||||
if (patternPos === _patternStartPos && !_firstMatchCanBeWeak) {
|
||||
// when the first match is a weak
|
||||
// match we discard it
|
||||
return undefined;
|
||||
@@ -715,15 +722,15 @@ class LazyArray {
|
||||
|
||||
//#region --- graceful ---
|
||||
|
||||
export function fuzzyScoreGracefulAggressive(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): [number, number[]] {
|
||||
export function fuzzyScoreGracefulAggressive(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): FuzzyScore {
|
||||
return fuzzyScoreWithPermutations(pattern, word, true, patternMaxWhitespaceIgnore);
|
||||
}
|
||||
|
||||
export function fuzzyScoreGraceful(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): [number, number[]] {
|
||||
export function fuzzyScoreGraceful(pattern: string, word: string, patternMaxWhitespaceIgnore?: number): FuzzyScore {
|
||||
return fuzzyScoreWithPermutations(pattern, word, false, patternMaxWhitespaceIgnore);
|
||||
}
|
||||
|
||||
function fuzzyScoreWithPermutations(pattern: string, word: string, aggressive?: boolean, patternMaxWhitespaceIgnore?: number): [number, number[]] {
|
||||
function fuzzyScoreWithPermutations(pattern: string, word: string, aggressive?: boolean, patternMaxWhitespaceIgnore?: number): FuzzyScore {
|
||||
let top: [number, number[]] = fuzzyScore(pattern, word, patternMaxWhitespaceIgnore);
|
||||
|
||||
if (top && !aggressive) {
|
||||
|
||||
@@ -247,8 +247,8 @@ const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else
|
||||
|
||||
export type ParsedPattern = (path: string, basename?: string) => boolean;
|
||||
|
||||
// The ParsedExpression returns a Promise iff siblingsFn returns a Promise.
|
||||
export type ParsedExpression = (path: string, basename?: string, siblingsFn?: () => string[] | TPromise<string[]>) => string | TPromise<string> /* the matching pattern */;
|
||||
// The ParsedExpression returns a Promise iff hasSibling returns a Promise.
|
||||
export type ParsedExpression = (path: string, basename?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>) => string | TPromise<string> /* the matching pattern */;
|
||||
|
||||
export interface IGlobOptions {
|
||||
/**
|
||||
@@ -264,9 +264,8 @@ interface ParsedStringPattern {
|
||||
allBasenames?: string[];
|
||||
allPaths?: string[];
|
||||
}
|
||||
type SiblingsPattern = { siblings: string[], name: string };
|
||||
interface ParsedExpressionPattern {
|
||||
(path: string, basename: string, siblingsPatternFn: () => SiblingsPattern | TPromise<SiblingsPattern>): string | TPromise<string> /* the matching pattern */;
|
||||
(path: string, basename: string, name: string, hasSibling: (name: string) => boolean | TPromise<boolean>): string | TPromise<string> /* the matching pattern */;
|
||||
requiresSiblings?: boolean;
|
||||
allBasenames?: string[];
|
||||
allPaths?: string[];
|
||||
@@ -436,13 +435,13 @@ function toRegExp(pattern: string): ParsedStringPattern {
|
||||
* - character ranges (using [...])
|
||||
*/
|
||||
export function match(pattern: string | IRelativePattern, path: string): boolean;
|
||||
export function match(expression: IExpression, path: string, siblingsFn?: () => string[]): string /* the matching pattern */;
|
||||
export function match(arg1: string | IExpression | IRelativePattern, path: string, siblingsFn?: () => string[]): any {
|
||||
export function match(expression: IExpression, path: string, hasSibling?: (name: string) => boolean): string /* the matching pattern */;
|
||||
export function match(arg1: string | IExpression | IRelativePattern, path: string, hasSibling?: (name: string) => boolean): any {
|
||||
if (!arg1 || !path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parse(<IExpression>arg1)(path, undefined, siblingsFn);
|
||||
return parse(<IExpression>arg1)(path, undefined, hasSibling);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -482,6 +481,44 @@ export function parse(arg1: string | IExpression | IRelativePattern, options: IG
|
||||
return parsedExpression(<IExpression>arg1, options);
|
||||
}
|
||||
|
||||
export function hasSiblingPromiseFn(siblingsFn?: () => TPromise<string[]>) {
|
||||
if (!siblingsFn) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let siblings: TPromise<Record<string, true>>;
|
||||
return (name: string) => {
|
||||
if (!siblings) {
|
||||
siblings = (siblingsFn() || TPromise.as([]))
|
||||
.then(list => list ? listToMap(list) : {});
|
||||
}
|
||||
return siblings.then(map => !!map[name]);
|
||||
};
|
||||
}
|
||||
|
||||
export function hasSiblingFn(siblingsFn?: () => string[]) {
|
||||
if (!siblingsFn) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let siblings: Record<string, true>;
|
||||
return (name: string) => {
|
||||
if (!siblings) {
|
||||
const list = siblingsFn();
|
||||
siblings = list ? listToMap(list) : {};
|
||||
}
|
||||
return !!siblings[name];
|
||||
};
|
||||
}
|
||||
|
||||
function listToMap(list: string[]) {
|
||||
const map: Record<string, true> = {};
|
||||
for (const key of list) {
|
||||
map[key] = true;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function isRelativePattern(obj: any): obj is IRelativePattern {
|
||||
const rp = obj as IRelativePattern;
|
||||
|
||||
@@ -493,8 +530,8 @@ export function isRelativePattern(obj: any): obj is IRelativePattern {
|
||||
*/
|
||||
export function parseToAsync(expression: IExpression, options?: IGlobOptions): ParsedExpression {
|
||||
const parsedExpression = parse(expression, options);
|
||||
return (path: string, basename?: string, siblingsFn?: () => string[] | TPromise<string[]>): string | TPromise<string> => {
|
||||
const result = parsedExpression(path, basename, siblingsFn);
|
||||
return (path: string, basename?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>): string | TPromise<string> => {
|
||||
const result = parsedExpression(path, basename, hasSibling);
|
||||
return result instanceof TPromise ? result : TPromise.as(result);
|
||||
};
|
||||
}
|
||||
@@ -522,7 +559,7 @@ function parsedExpression(expression: IExpression, options: IGlobOptions): Parse
|
||||
return <ParsedStringPattern>parsedPatterns[0];
|
||||
}
|
||||
|
||||
const resultExpression: ParsedStringPattern = function (path: string, basename: string, siblingsFn?: () => string[]) {
|
||||
const resultExpression: ParsedStringPattern = function (path: string, basename: string) {
|
||||
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
|
||||
// Pattern matches path
|
||||
const result = (<ParsedStringPattern>parsedPatterns[i])(path, basename);
|
||||
@@ -547,38 +584,21 @@ function parsedExpression(expression: IExpression, options: IGlobOptions): Parse
|
||||
return resultExpression;
|
||||
}
|
||||
|
||||
const resultExpression: ParsedStringPattern = function (path: string, basename: string, siblingsFn?: () => string[] | TPromise<string[]>) {
|
||||
let siblingsPattern: SiblingsPattern | TPromise<SiblingsPattern>;
|
||||
let siblingsResolved = !siblingsFn;
|
||||
|
||||
function siblingsToSiblingsPattern(siblings: string[]) {
|
||||
if (siblings && siblings.length) {
|
||||
if (!basename) {
|
||||
basename = paths.basename(path);
|
||||
}
|
||||
const name = basename.substr(0, basename.length - paths.extname(path).length);
|
||||
return { siblings, name };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function siblingsPatternFn() {
|
||||
// Resolve siblings only once
|
||||
if (!siblingsResolved) {
|
||||
siblingsResolved = true;
|
||||
const siblings = siblingsFn();
|
||||
siblingsPattern = TPromise.is(siblings) ?
|
||||
siblings.then(siblingsToSiblingsPattern) :
|
||||
siblingsToSiblingsPattern(siblings);
|
||||
}
|
||||
|
||||
return siblingsPattern;
|
||||
}
|
||||
const resultExpression: ParsedStringPattern = function (path: string, basename: string, hasSibling?: (name: string) => boolean | TPromise<boolean>) {
|
||||
let name: string;
|
||||
|
||||
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
|
||||
// Pattern matches path
|
||||
const result = (<ParsedExpressionPattern>parsedPatterns[i])(path, basename, siblingsPatternFn);
|
||||
const parsedPattern = (<ParsedExpressionPattern>parsedPatterns[i]);
|
||||
if (parsedPattern.requiresSiblings && hasSibling) {
|
||||
if (!basename) {
|
||||
basename = paths.basename(path);
|
||||
}
|
||||
if (!name) {
|
||||
name = basename.substr(0, basename.length - paths.extname(path).length);
|
||||
}
|
||||
}
|
||||
const result = parsedPattern(path, basename, name, hasSibling);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
@@ -619,28 +639,16 @@ function parseExpressionPattern(pattern: string, value: any, options: IGlobOptio
|
||||
if (value) {
|
||||
const when = (<SiblingClause>value).when;
|
||||
if (typeof when === 'string') {
|
||||
const siblingsPatternToMatchingPattern = (siblingsPattern: SiblingsPattern): string => {
|
||||
let clausePattern = when.replace('$(basename)', siblingsPattern.name);
|
||||
if (siblingsPattern.siblings.indexOf(clausePattern) !== -1) {
|
||||
return pattern;
|
||||
} else {
|
||||
return null; // pattern does not match in the end because the when clause is not satisfied
|
||||
}
|
||||
};
|
||||
|
||||
const result: ParsedExpressionPattern = (path: string, basename: string, siblingsPatternFn: () => SiblingsPattern | TPromise<SiblingsPattern>) => {
|
||||
if (!parsedPattern(path, basename)) {
|
||||
const result: ParsedExpressionPattern = (path: string, basename: string, name: string, hasSibling: (name: string) => boolean | TPromise<boolean>) => {
|
||||
if (!hasSibling || !parsedPattern(path, basename)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const siblingsPattern = siblingsPatternFn();
|
||||
if (!siblingsPattern) {
|
||||
return null; // pattern is malformed or we don't have siblings
|
||||
}
|
||||
|
||||
return TPromise.is(siblingsPattern) ?
|
||||
siblingsPattern.then(siblingsPatternToMatchingPattern) :
|
||||
siblingsPatternToMatchingPattern(siblingsPattern);
|
||||
const clausePattern = when.replace('$(basename)', name);
|
||||
const matched = hasSibling(clausePattern);
|
||||
return TPromise.is(matched) ?
|
||||
matched.then(m => m ? pattern : null) :
|
||||
matched ? pattern : null;
|
||||
};
|
||||
result.requiresSiblings = true;
|
||||
return result;
|
||||
|
||||
@@ -27,26 +27,12 @@ export class HistoryNavigator<T> implements INavigator<T> {
|
||||
this._onChange();
|
||||
}
|
||||
|
||||
public addIfNotPresent(t: T) {
|
||||
if (!this._history.has(t)) {
|
||||
this.add(t);
|
||||
}
|
||||
}
|
||||
|
||||
public next(): T {
|
||||
if (this._navigator.next()) {
|
||||
return this._navigator.current();
|
||||
}
|
||||
this.last();
|
||||
return null;
|
||||
return this._navigator.next();
|
||||
}
|
||||
|
||||
public previous(): T {
|
||||
if (this._navigator.previous()) {
|
||||
return this._navigator.current();
|
||||
}
|
||||
this.first();
|
||||
return null;
|
||||
return this._navigator.previous();
|
||||
}
|
||||
|
||||
public current(): T {
|
||||
@@ -65,6 +51,10 @@ export class HistoryNavigator<T> implements INavigator<T> {
|
||||
return this._navigator.last();
|
||||
}
|
||||
|
||||
public has(t: T): boolean {
|
||||
return this._history.has(t);
|
||||
}
|
||||
|
||||
public clear(): void {
|
||||
this._initialize([]);
|
||||
this._onChange();
|
||||
@@ -72,8 +62,7 @@ export class HistoryNavigator<T> implements INavigator<T> {
|
||||
|
||||
private _onChange() {
|
||||
this._reduceToLimit();
|
||||
this._navigator = new ArrayNavigator(this._elements);
|
||||
this._navigator.last();
|
||||
this._navigator = new ArrayNavigator(this._elements, 0, this._elements.length, this._elements.length);
|
||||
}
|
||||
|
||||
private _reduceToLimit() {
|
||||
@@ -95,4 +84,4 @@ export class HistoryNavigator<T> implements INavigator<T> {
|
||||
this._history.forEach(e => elements.push(e));
|
||||
return elements;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,86 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
export interface IIterator<E> {
|
||||
next(): { readonly done: boolean, readonly value: E };
|
||||
export interface IteratorResult<T> {
|
||||
readonly done: boolean;
|
||||
readonly value: T | undefined;
|
||||
}
|
||||
|
||||
export interface Iterator<T> {
|
||||
next(): IteratorResult<T>;
|
||||
}
|
||||
|
||||
export module Iterator {
|
||||
const _empty: Iterator<any> = {
|
||||
next() {
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
};
|
||||
|
||||
export function empty<T>(): Iterator<T> {
|
||||
return _empty;
|
||||
}
|
||||
|
||||
export function iterate<T>(array: T[], index = 0, length = array.length): Iterator<T> {
|
||||
return {
|
||||
next(): IteratorResult<T> {
|
||||
if (index >= length) {
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
|
||||
return { done: false, value: array[index++] };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function map<T, R>(iterator: Iterator<T>, fn: (t: T) => R): Iterator<R> {
|
||||
return {
|
||||
next() {
|
||||
const { done, value } = iterator.next();
|
||||
return { done, value: done ? undefined : fn(value) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function filter<T>(iterator: Iterator<T>, fn: (t: T) => boolean): Iterator<T> {
|
||||
return {
|
||||
next() {
|
||||
while (true) {
|
||||
const { done, value } = iterator.next();
|
||||
|
||||
if (done) {
|
||||
return { done, value: undefined };
|
||||
}
|
||||
|
||||
if (fn(value)) {
|
||||
return { done, value };
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function forEach<T>(iterator: Iterator<T>, fn: (t: T) => void): void {
|
||||
for (let next = iterator.next(); !next.done; next = iterator.next()) {
|
||||
fn(next.value);
|
||||
}
|
||||
}
|
||||
|
||||
export function collect<T>(iterator: Iterator<T>): T[] {
|
||||
const result: T[] = [];
|
||||
forEach(iterator, value => result.push(value));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export type ISequence<T> = Iterator<T> | T[];
|
||||
|
||||
export function getSequenceIterator<T>(arg: Iterator<T> | T[]): Iterator<T> {
|
||||
if (Array.isArray(arg)) {
|
||||
return Iterator.iterate(arg);
|
||||
} else {
|
||||
return arg;
|
||||
}
|
||||
}
|
||||
|
||||
export interface INextIterator<T> {
|
||||
@@ -20,11 +98,11 @@ export class ArrayIterator<T> implements INextIterator<T> {
|
||||
protected end: number;
|
||||
protected index: number;
|
||||
|
||||
constructor(items: T[], start: number = 0, end: number = items.length) {
|
||||
constructor(items: T[], start: number = 0, end: number = items.length, index = start - 1) {
|
||||
this.items = items;
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.index = start - 1;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
public first(): T {
|
||||
@@ -48,8 +126,8 @@ export class ArrayIterator<T> implements INextIterator<T> {
|
||||
|
||||
export class ArrayNavigator<T> extends ArrayIterator<T> implements INavigator<T> {
|
||||
|
||||
constructor(items: T[], start: number = 0, end: number = items.length) {
|
||||
super(items, start, end);
|
||||
constructor(items: T[], start: number = 0, end: number = items.length, index = start - 1) {
|
||||
super(items, start, end, index);
|
||||
}
|
||||
|
||||
public current(): T {
|
||||
|
||||
@@ -407,6 +407,7 @@ export function createScanner(text: string, ignoreTrivia: boolean = false): JSON
|
||||
case CharacterCodes.doubleQuote:
|
||||
case CharacterCodes.colon:
|
||||
case CharacterCodes.comma:
|
||||
case CharacterCodes.slash:
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -628,7 +629,7 @@ export type JSONPath = Segment[];
|
||||
|
||||
export interface ParseOptions {
|
||||
disallowComments?: boolean;
|
||||
allowTrailingComma?: boolean;
|
||||
disallowTrailingComma?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -817,7 +818,7 @@ export function visit(text: string, visitor: JSONVisitor, options?: ParseOptions
|
||||
onError = toOneArgVisit(visitor.onError);
|
||||
|
||||
let disallowComments = options && options.disallowComments;
|
||||
let allowTrailingComma = options && options.allowTrailingComma;
|
||||
let disallowTrailingComma = options && options.disallowTrailingComma;
|
||||
function scanNext(): SyntaxKind {
|
||||
while (true) {
|
||||
let token = _scanner.scan();
|
||||
@@ -929,7 +930,7 @@ export function visit(text: string, visitor: JSONVisitor, options?: ParseOptions
|
||||
}
|
||||
onSeparator(',');
|
||||
scanNext(); // consume comma
|
||||
if (_scanner.getToken() === SyntaxKind.CloseBraceToken && allowTrailingComma) {
|
||||
if (_scanner.getToken() === SyntaxKind.CloseBraceToken && !disallowTrailingComma) {
|
||||
break;
|
||||
}
|
||||
} else if (needsComma) {
|
||||
@@ -961,7 +962,7 @@ export function visit(text: string, visitor: JSONVisitor, options?: ParseOptions
|
||||
}
|
||||
onSeparator(',');
|
||||
scanNext(); // consume comma
|
||||
if (_scanner.getToken() === SyntaxKind.CloseBracketToken && allowTrailingComma) {
|
||||
if (_scanner.getToken() === SyntaxKind.CloseBracketToken && !disallowTrailingComma) {
|
||||
break;
|
||||
}
|
||||
} else if (needsComma) {
|
||||
|
||||
@@ -59,6 +59,13 @@ export const UILabelProvider = new ModifierLabelProvider(
|
||||
altKey: nls.localize({ key: 'altKey', comment: ['This is the short form for the Alt key on the keyboard'] }, "Alt"),
|
||||
metaKey: nls.localize({ key: 'windowsKey', comment: ['This is the short form for the Windows key on the keyboard'] }, "Windows"),
|
||||
separator: '+',
|
||||
},
|
||||
{
|
||||
ctrlKey: nls.localize({ key: 'ctrlKey', comment: ['This is the short form for the Control key on the keyboard'] }, "Ctrl"),
|
||||
shiftKey: nls.localize({ key: 'shiftKey', comment: ['This is the short form for the Shift key on the keyboard'] }, "Shift"),
|
||||
altKey: nls.localize({ key: 'altKey', comment: ['This is the short form for the Alt key on the keyboard'] }, "Alt"),
|
||||
metaKey: nls.localize({ key: 'superKey', comment: ['This is the short form for the Super key on the keyboard'] }, "Super"),
|
||||
separator: '+',
|
||||
}
|
||||
);
|
||||
|
||||
@@ -79,6 +86,13 @@ export const AriaLabelProvider = new ModifierLabelProvider(
|
||||
altKey: nls.localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"),
|
||||
metaKey: nls.localize({ key: 'windowsKey.long', comment: ['This is the long form for the Windows key on the keyboard'] }, "Windows"),
|
||||
separator: '+',
|
||||
},
|
||||
{
|
||||
ctrlKey: nls.localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"),
|
||||
shiftKey: nls.localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"),
|
||||
altKey: nls.localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"),
|
||||
metaKey: nls.localize({ key: 'superKey.long', comment: ['This is the long form for the Super key on the keyboard'] }, "Super"),
|
||||
separator: '+',
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -5,15 +5,16 @@
|
||||
'use strict';
|
||||
|
||||
import URI from 'vs/base/common/uri';
|
||||
import { nativeSep, normalize, basename as pathsBasename, join, sep } from 'vs/base/common/paths';
|
||||
import { endsWith, ltrim, equalsIgnoreCase, startsWithIgnoreCase, rtrim, startsWith } from 'vs/base/common/strings';
|
||||
import { nativeSep, normalize, basename as pathsBasename, sep } from 'vs/base/common/paths';
|
||||
import { endsWith, ltrim, startsWithIgnoreCase, rtrim, startsWith } from 'vs/base/common/strings';
|
||||
import { Schemas } from 'vs/base/common/network';
|
||||
import { isLinux, isWindows, isMacintosh } from 'vs/base/common/platform';
|
||||
import { isEqual } from 'vs/base/common/resources';
|
||||
|
||||
export interface IWorkspaceFolderProvider {
|
||||
getWorkspaceFolder(resource: URI): { uri: URI };
|
||||
getWorkspaceFolder(resource: URI): { uri: URI, name?: string };
|
||||
getWorkspace(): {
|
||||
folders: { uri: URI }[];
|
||||
folders: { uri: URI, name?: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,7 +22,10 @@ export interface IUserHomeProvider {
|
||||
userHome: string;
|
||||
}
|
||||
|
||||
export function getPathLabel(resource: URI | string, rootProvider?: IWorkspaceFolderProvider, userHomeProvider?: IUserHomeProvider): string {
|
||||
/**
|
||||
* @deprecated use UriLabelService instead
|
||||
*/
|
||||
export function getPathLabel(resource: URI | string, userHomeProvider: IUserHomeProvider, rootProvider?: IWorkspaceFolderProvider): string {
|
||||
if (!resource) {
|
||||
return null;
|
||||
}
|
||||
@@ -30,31 +34,31 @@ export function getPathLabel(resource: URI | string, rootProvider?: IWorkspaceFo
|
||||
resource = URI.file(resource);
|
||||
}
|
||||
|
||||
// return early if the resource is neither file:// nor untitled://
|
||||
if (resource.scheme !== Schemas.file && resource.scheme !== Schemas.untitled) {
|
||||
return resource.with({ query: null, fragment: null }).toString(true);
|
||||
}
|
||||
|
||||
// return early if we can resolve a relative path label from the root
|
||||
const baseResource = rootProvider ? rootProvider.getWorkspaceFolder(resource) : null;
|
||||
if (baseResource) {
|
||||
const hasMultipleRoots = rootProvider.getWorkspace().folders.length > 1;
|
||||
|
||||
let pathLabel: string;
|
||||
if (isLinux ? baseResource.uri.fsPath === resource.fsPath : equalsIgnoreCase(baseResource.uri.fsPath, resource.fsPath)) {
|
||||
pathLabel = ''; // no label if pathes are identical
|
||||
if (isEqual(baseResource.uri, resource, !isLinux)) {
|
||||
pathLabel = ''; // no label if paths are identical
|
||||
} else {
|
||||
pathLabel = normalize(ltrim(resource.fsPath.substr(baseResource.uri.fsPath.length), nativeSep), true);
|
||||
pathLabel = normalize(ltrim(resource.path.substr(baseResource.uri.path.length), sep), true);
|
||||
}
|
||||
|
||||
if (hasMultipleRoots) {
|
||||
const rootName = pathsBasename(baseResource.uri.fsPath);
|
||||
pathLabel = pathLabel ? join(rootName, pathLabel) : rootName; // always show root basename if there are multiple
|
||||
const rootName = (baseResource && baseResource.name) ? baseResource.name : pathsBasename(baseResource.uri.fsPath);
|
||||
pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple
|
||||
}
|
||||
|
||||
return pathLabel;
|
||||
}
|
||||
|
||||
// return if the resource is neither file:// nor untitled:// and no baseResource was provided
|
||||
if (resource.scheme !== Schemas.file && resource.scheme !== Schemas.untitled) {
|
||||
return resource.with({ query: null, fragment: null }).toString(true);
|
||||
}
|
||||
|
||||
// convert c:\something => C:\something
|
||||
if (hasDriveLetter(resource.fsPath)) {
|
||||
return normalize(normalizeDriveLetter(resource.fsPath), true);
|
||||
@@ -78,7 +82,7 @@ export function getBaseLabel(resource: URI | string): string {
|
||||
resource = URI.file(resource);
|
||||
}
|
||||
|
||||
const base = pathsBasename(resource.fsPath) || resource.fsPath /* can be empty string if '/' is passed in */;
|
||||
const base = pathsBasename(resource.path) || (resource.scheme === Schemas.file ? resource.fsPath : resource.path) /* can be empty string if '/' is passed in */;
|
||||
|
||||
// convert c: => C:
|
||||
if (hasDriveLetter(base)) {
|
||||
|
||||
@@ -7,10 +7,6 @@
|
||||
|
||||
import { once } from 'vs/base/common/functional';
|
||||
|
||||
export const empty: IDisposable = Object.freeze<IDisposable>({
|
||||
dispose() { }
|
||||
});
|
||||
|
||||
export interface IDisposable {
|
||||
dispose(): void;
|
||||
}
|
||||
@@ -24,7 +20,6 @@ export function dispose<T extends IDisposable>(disposable: T): T;
|
||||
export function dispose<T extends IDisposable>(...disposables: T[]): T[];
|
||||
export function dispose<T extends IDisposable>(disposables: T[]): T[];
|
||||
export function dispose<T extends IDisposable>(first: T | T[], ...rest: T[]): T | T[] {
|
||||
|
||||
if (Array.isArray(first)) {
|
||||
first.forEach(d => d && d.dispose());
|
||||
return [];
|
||||
@@ -45,23 +40,16 @@ export function combinedDisposable(disposables: IDisposable[]): IDisposable {
|
||||
return { dispose: () => dispose(disposables) };
|
||||
}
|
||||
|
||||
export function toDisposable(...fns: (() => void)[]): IDisposable {
|
||||
return {
|
||||
dispose() {
|
||||
for (const fn of fns) {
|
||||
fn();
|
||||
}
|
||||
}
|
||||
};
|
||||
export function toDisposable(fn: () => void): IDisposable {
|
||||
return { dispose() { fn(); } };
|
||||
}
|
||||
|
||||
export abstract class Disposable implements IDisposable {
|
||||
|
||||
private _toDispose: IDisposable[];
|
||||
static None = Object.freeze<IDisposable>({ dispose() { } });
|
||||
|
||||
constructor() {
|
||||
this._toDispose = [];
|
||||
}
|
||||
protected _toDispose: IDisposable[] = [];
|
||||
protected get toDispose(): IDisposable[] { return this._toDispose; }
|
||||
|
||||
public dispose(): void {
|
||||
this._toDispose = dispose(this._toDispose);
|
||||
@@ -69,6 +57,7 @@ export abstract class Disposable implements IDisposable {
|
||||
|
||||
protected _register<T extends IDisposable>(t: T): T {
|
||||
this._toDispose.push(t);
|
||||
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import { IIterator } from 'vs/base/common/iterator';
|
||||
import { Iterator } from 'vs/base/common/iterator';
|
||||
|
||||
class Node<E> {
|
||||
element: E;
|
||||
@@ -94,7 +94,7 @@ export class LinkedList<E> {
|
||||
};
|
||||
}
|
||||
|
||||
iterator(): IIterator<E> {
|
||||
iterator(): Iterator<E> {
|
||||
let element = {
|
||||
done: undefined,
|
||||
value: undefined,
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
'use strict';
|
||||
|
||||
import URI from 'vs/base/common/uri';
|
||||
import { CharCode } from 'vs/base/common/charCode';
|
||||
import { Iterator } from './iterator';
|
||||
|
||||
export function values<V = any>(set: Set<V>): V[];
|
||||
export function values<K = any, V = any>(map: Map<K, V>): V[];
|
||||
@@ -35,7 +37,6 @@ export function getOrSet<K, V>(map: Map<K, V>, key: K, value: V): V {
|
||||
export interface IKeyIterator {
|
||||
reset(key: string): this;
|
||||
next(): this;
|
||||
join(parts: string[]): string;
|
||||
|
||||
hasNext(): boolean;
|
||||
cmp(a: string): number;
|
||||
@@ -58,10 +59,6 @@ export class StringIterator implements IKeyIterator {
|
||||
return this;
|
||||
}
|
||||
|
||||
join(parts: string[]): string {
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
hasNext(): boolean {
|
||||
return this._pos < this._value.length - 1;
|
||||
}
|
||||
@@ -79,9 +76,6 @@ export class StringIterator implements IKeyIterator {
|
||||
|
||||
export class PathIterator implements IKeyIterator {
|
||||
|
||||
private static readonly _fwd = '/'.charCodeAt(0);
|
||||
private static readonly _bwd = '\\'.charCodeAt(0);
|
||||
|
||||
private _value: string;
|
||||
private _from: number;
|
||||
private _to: number;
|
||||
@@ -97,17 +91,13 @@ export class PathIterator implements IKeyIterator {
|
||||
return this._to < this._value.length;
|
||||
}
|
||||
|
||||
join(parts: string[]): string {
|
||||
return parts.join('/');
|
||||
}
|
||||
|
||||
next(): this {
|
||||
// this._data = key.split(/[\\/]/).filter(s => !!s);
|
||||
this._from = this._to;
|
||||
let justSeps = true;
|
||||
for (; this._to < this._value.length; this._to++) {
|
||||
const ch = this._value.charCodeAt(this._to);
|
||||
if (ch === PathIterator._fwd || ch === PathIterator._bwd) {
|
||||
if (ch === CharCode.Slash || ch === CharCode.Backslash) {
|
||||
if (justSeps) {
|
||||
this._from++;
|
||||
} else {
|
||||
@@ -150,14 +140,15 @@ export class PathIterator implements IKeyIterator {
|
||||
}
|
||||
|
||||
class TernarySearchTreeNode<E> {
|
||||
str: string;
|
||||
element: E;
|
||||
segment: string;
|
||||
value: E;
|
||||
key: string;
|
||||
left: TernarySearchTreeNode<E>;
|
||||
mid: TernarySearchTreeNode<E>;
|
||||
right: TernarySearchTreeNode<E>;
|
||||
|
||||
isEmpty(): boolean {
|
||||
return !this.left && !this.mid && !this.right && !this.element;
|
||||
return !this.left && !this.mid && !this.right && !this.value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,17 +179,17 @@ export class TernarySearchTree<E> {
|
||||
|
||||
if (!this._root) {
|
||||
this._root = new TernarySearchTreeNode<E>();
|
||||
this._root.str = iter.value();
|
||||
this._root.segment = iter.value();
|
||||
}
|
||||
|
||||
node = this._root;
|
||||
while (true) {
|
||||
let val = iter.cmp(node.str);
|
||||
let val = iter.cmp(node.segment);
|
||||
if (val > 0) {
|
||||
// left
|
||||
if (!node.left) {
|
||||
node.left = new TernarySearchTreeNode<E>();
|
||||
node.left.str = iter.value();
|
||||
node.left.segment = iter.value();
|
||||
}
|
||||
node = node.left;
|
||||
|
||||
@@ -206,7 +197,7 @@ export class TernarySearchTree<E> {
|
||||
// right
|
||||
if (!node.right) {
|
||||
node.right = new TernarySearchTreeNode<E>();
|
||||
node.right.str = iter.value();
|
||||
node.right.segment = iter.value();
|
||||
}
|
||||
node = node.right;
|
||||
|
||||
@@ -215,15 +206,16 @@ export class TernarySearchTree<E> {
|
||||
iter.next();
|
||||
if (!node.mid) {
|
||||
node.mid = new TernarySearchTreeNode<E>();
|
||||
node.mid.str = iter.value();
|
||||
node.mid.segment = iter.value();
|
||||
}
|
||||
node = node.mid;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const oldElement = node.element;
|
||||
node.element = element;
|
||||
const oldElement = node.value;
|
||||
node.value = element;
|
||||
node.key = key;
|
||||
return oldElement;
|
||||
}
|
||||
|
||||
@@ -231,7 +223,7 @@ export class TernarySearchTree<E> {
|
||||
let iter = this._iter.reset(key);
|
||||
let node = this._root;
|
||||
while (node) {
|
||||
let val = iter.cmp(node.str);
|
||||
let val = iter.cmp(node.segment);
|
||||
if (val > 0) {
|
||||
// left
|
||||
node = node.left;
|
||||
@@ -246,7 +238,7 @@ export class TernarySearchTree<E> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return node ? node.element : undefined;
|
||||
return node ? node.value : undefined;
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
@@ -257,7 +249,7 @@ export class TernarySearchTree<E> {
|
||||
|
||||
// find and unset node
|
||||
while (node) {
|
||||
let val = iter.cmp(node.str);
|
||||
let val = iter.cmp(node.segment);
|
||||
if (val > 0) {
|
||||
// left
|
||||
stack.push([1, node]);
|
||||
@@ -273,7 +265,7 @@ export class TernarySearchTree<E> {
|
||||
node = node.mid;
|
||||
} else {
|
||||
// remove element
|
||||
node.element = undefined;
|
||||
node.value = undefined;
|
||||
|
||||
// clean up empty nodes
|
||||
while (stack.length > 0 && node.isEmpty()) {
|
||||
@@ -295,7 +287,7 @@ export class TernarySearchTree<E> {
|
||||
let node = this._root;
|
||||
let candidate: E;
|
||||
while (node) {
|
||||
let val = iter.cmp(node.str);
|
||||
let val = iter.cmp(node.segment);
|
||||
if (val > 0) {
|
||||
// left
|
||||
node = node.left;
|
||||
@@ -305,20 +297,20 @@ export class TernarySearchTree<E> {
|
||||
} else if (iter.hasNext()) {
|
||||
// mid
|
||||
iter.next();
|
||||
candidate = node.element || candidate;
|
||||
candidate = node.value || candidate;
|
||||
node = node.mid;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return node && node.element || candidate;
|
||||
return node && node.value || candidate;
|
||||
}
|
||||
|
||||
findSuperstr(key: string): TernarySearchTree<E> {
|
||||
findSuperstr(key: string): Iterator<E> {
|
||||
let iter = this._iter.reset(key);
|
||||
let node = this._root;
|
||||
while (node) {
|
||||
let val = iter.cmp(node.str);
|
||||
let val = iter.cmp(node.segment);
|
||||
if (val > 0) {
|
||||
// left
|
||||
node = node.left;
|
||||
@@ -333,35 +325,59 @@ export class TernarySearchTree<E> {
|
||||
// collect
|
||||
if (!node.mid) {
|
||||
return undefined;
|
||||
} else {
|
||||
return this._nodeIterator(node.mid);
|
||||
}
|
||||
let ret = new TernarySearchTree<E>(this._iter);
|
||||
ret._root = node.mid;
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
forEach(callback: (value: E, index: string) => any) {
|
||||
this._forEach(this._root, [], callback);
|
||||
private _nodeIterator(node: TernarySearchTreeNode<E>): Iterator<E> {
|
||||
let res = {
|
||||
done: false,
|
||||
value: undefined
|
||||
};
|
||||
let idx: number;
|
||||
let data: E[];
|
||||
let next = () => {
|
||||
if (!data) {
|
||||
// lazy till first invocation
|
||||
data = [];
|
||||
idx = 0;
|
||||
this._forEach(node, value => data.push(value));
|
||||
}
|
||||
if (idx >= data.length) {
|
||||
res.done = true;
|
||||
res.value = undefined;
|
||||
} else {
|
||||
res.done = false;
|
||||
res.value = data[idx++];
|
||||
}
|
||||
return res;
|
||||
};
|
||||
return { next };
|
||||
}
|
||||
|
||||
private _forEach(node: TernarySearchTreeNode<E>, parts: string[], callback: (value: E, index: string) => any) {
|
||||
forEach(callback: (value: E, index: string) => any) {
|
||||
this._forEach(this._root, callback);
|
||||
}
|
||||
|
||||
private _forEach(node: TernarySearchTreeNode<E>, callback: (value: E, index: string) => any) {
|
||||
if (node) {
|
||||
// left
|
||||
this._forEach(node.left, parts, callback);
|
||||
this._forEach(node.left, callback);
|
||||
|
||||
// node
|
||||
parts.push(node.str);
|
||||
if (node.element) {
|
||||
callback(node.element, this._iter.join(parts));
|
||||
if (node.value) {
|
||||
// callback(node.value, this._iter.join(parts));
|
||||
callback(node.value, node.key);
|
||||
}
|
||||
// mid
|
||||
this._forEach(node.mid, parts, callback);
|
||||
parts.pop();
|
||||
this._forEach(node.mid, callback);
|
||||
|
||||
// right
|
||||
this._forEach(node.right, parts, callback);
|
||||
this._forEach(node.right, callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -420,6 +436,14 @@ export class ResourceMap<T> {
|
||||
public keys(): URI[] {
|
||||
return keys(this.map).map(URI.parse);
|
||||
}
|
||||
|
||||
public clone(): ResourceMap<T> {
|
||||
const resourceMap = new ResourceMap<T>();
|
||||
|
||||
this.map.forEach((value, key) => resourceMap.map.set(key, value));
|
||||
|
||||
return resourceMap;
|
||||
}
|
||||
}
|
||||
|
||||
// We should fold BoundedMap and LinkedMap. See https://github.com/Microsoft/vscode/issues/28496
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* marked - a markdown parser
|
||||
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
|
||||
* Copyright (c) 2011-2014, Christopher Jeffrey. (Source EULAd)
|
||||
* https://github.com/markedjs/marked
|
||||
*/
|
||||
|
||||
var __marked_exports;
|
||||
|
||||
;(function(root) {
|
||||
; (function (root) {
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
@@ -18,20 +18,29 @@ var block = {
|
||||
code: /^( {4}[^\n]+\n*)+/,
|
||||
fences: noop,
|
||||
hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
|
||||
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
|
||||
heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,
|
||||
nptable: noop,
|
||||
blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
|
||||
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
|
||||
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
|
||||
html: '^ {0,3}(?:' // optional indentation
|
||||
+ '<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
|
||||
+ '|comment[^\\n]*(\\n+|$)' // (2)
|
||||
+ '|<\\?[\\s\\S]*?\\?>\\n*' // (3)
|
||||
+ '|<![A-Z][\\s\\S]*?>\\n*' // (4)
|
||||
+ '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*' // (5)
|
||||
+ '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' // (6)
|
||||
+ '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag
|
||||
+ '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag
|
||||
+ ')',
|
||||
def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
|
||||
table: noop,
|
||||
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
|
||||
paragraph: /^([^\n]+(?:\n?(?!hr|heading|lheading| {0,3}>|tag)[^\n]+)+)/,
|
||||
paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,
|
||||
text: /^[^\n]+/
|
||||
};
|
||||
|
||||
block._label = /(?:\\[\[\]]|[^\[\]])+/;
|
||||
block._title = /(?:"(?:\\"|[^"]|"[^"\n]*")*"|'\n?(?:[^'\n]+\n?)*'|\([^()]*\))/;
|
||||
block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;
|
||||
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
|
||||
block.def = edit(block.def)
|
||||
.replace('label', block._label)
|
||||
.replace('title', block._title)
|
||||
@@ -49,23 +58,24 @@ block.list = edit(block.list)
|
||||
.replace('def', '\\n+(?=' + block.def.source + ')')
|
||||
.getRegex();
|
||||
|
||||
block._tag = '(?!(?:'
|
||||
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
|
||||
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
|
||||
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b';
|
||||
|
||||
block.html = edit(block.html)
|
||||
.replace('comment', /<!--[\s\S]*?-->/)
|
||||
.replace('closed', /<(tag)[\s\S]+?<\/\1>/)
|
||||
.replace('closing', /<tag(?:"[^"]*"|'[^']*'|\s[^'"\/>\s]*)*?\/?>/)
|
||||
.replace(/tag/g, block._tag)
|
||||
block._tag = 'address|article|aside|base|basefont|blockquote|body|caption'
|
||||
+ '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
|
||||
+ '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
|
||||
+ '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
|
||||
+ '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
|
||||
+ '|track|ul';
|
||||
block._comment = /<!--(?!-?>)[\s\S]*?-->/;
|
||||
block.html = edit(block.html, 'i')
|
||||
.replace('comment', block._comment)
|
||||
.replace('tag', block._tag)
|
||||
.replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
|
||||
.getRegex();
|
||||
|
||||
block.paragraph = edit(block.paragraph)
|
||||
.replace('hr', block.hr)
|
||||
.replace('heading', block.heading)
|
||||
.replace('lheading', block.lheading)
|
||||
.replace('tag', '<' + block._tag)
|
||||
.replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
|
||||
.getRegex();
|
||||
|
||||
block.blockquote = edit(block.blockquote)
|
||||
@@ -99,8 +109,26 @@ block.gfm.paragraph = edit(block.paragraph)
|
||||
*/
|
||||
|
||||
block.tables = merge({}, block.gfm, {
|
||||
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
|
||||
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
|
||||
nptable: /^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,
|
||||
table: /^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/
|
||||
});
|
||||
|
||||
/**
|
||||
* Pedantic grammar
|
||||
*/
|
||||
|
||||
block.pedantic = merge({}, block.normal, {
|
||||
html: edit(
|
||||
'^ *(?:comment *(?:\\n|\\s*$)'
|
||||
+ '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
|
||||
+ '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
|
||||
.replace('comment', block._comment)
|
||||
.replace(/tag/g, '(?!(?:'
|
||||
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
|
||||
+ '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
|
||||
+ '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
|
||||
.getRegex(),
|
||||
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -113,7 +141,9 @@ function Lexer(options) {
|
||||
this.options = options || marked.defaults;
|
||||
this.rules = block.normal;
|
||||
|
||||
if (this.options.gfm) {
|
||||
if (this.options.pedantic) {
|
||||
this.rules = block.pedantic;
|
||||
} else if (this.options.gfm) {
|
||||
if (this.options.tables) {
|
||||
this.rules = block.tables;
|
||||
} else {
|
||||
@@ -167,7 +197,9 @@ Lexer.prototype.token = function(src, top) {
|
||||
i,
|
||||
tag,
|
||||
l,
|
||||
isordered;
|
||||
isordered,
|
||||
istask,
|
||||
ischecked;
|
||||
|
||||
while (src) {
|
||||
// newline
|
||||
@@ -187,7 +219,7 @@ Lexer.prototype.token = function(src, top) {
|
||||
this.tokens.push({
|
||||
type: 'code',
|
||||
text: !this.options.pedantic
|
||||
? cap.replace(/\n+$/, '')
|
||||
? rtrim(cap, '\n')
|
||||
: cap
|
||||
});
|
||||
continue;
|
||||
@@ -217,34 +249,36 @@ Lexer.prototype.token = function(src, top) {
|
||||
|
||||
// table no leading pipe (gfm)
|
||||
if (top && (cap = this.rules.nptable.exec(src))) {
|
||||
src = src.substring(cap[0].length);
|
||||
|
||||
item = {
|
||||
type: 'table',
|
||||
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
|
||||
header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
|
||||
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
|
||||
cells: cap[3].replace(/\n$/, '').split('\n')
|
||||
cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
|
||||
};
|
||||
|
||||
for (i = 0; i < item.align.length; i++) {
|
||||
if (/^ *-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'right';
|
||||
} else if (/^ *:-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'center';
|
||||
} else if (/^ *:-+ *$/.test(item.align[i])) {
|
||||
item.align[i] = 'left';
|
||||
} else {
|
||||
item.align[i] = null;
|
||||
if (item.header.length === item.align.length) {
|
||||
src = src.substring(cap[0].length);
|
||||
|
||||
for (i = 0; i < item.align.length; i++) {
|
||||
if (/^ *-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'right';
|
||||
} else if (/^ *:-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'center';
|
||||
} else if (/^ *:-+ *$/.test(item.align[i])) {
|
||||
item.align[i] = 'left';
|
||||
} else {
|
||||
item.align[i] = null;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < item.cells.length; i++) {
|
||||
item.cells[i] = splitCells(item.cells[i], item.header.length);
|
||||
}
|
||||
|
||||
this.tokens.push(item);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (i = 0; i < item.cells.length; i++) {
|
||||
item.cells[i] = item.cells[i].split(/ *\| */);
|
||||
}
|
||||
|
||||
this.tokens.push(item);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// hr
|
||||
@@ -333,10 +367,20 @@ Lexer.prototype.token = function(src, top) {
|
||||
if (!loose) loose = next;
|
||||
}
|
||||
|
||||
// Check for task list items
|
||||
istask = /^\[[ xX]\] /.test(item);
|
||||
ischecked = undefined;
|
||||
if (istask) {
|
||||
ischecked = item[1] !== ' ';
|
||||
item = item.replace(/^\[[ xX]\] +/, '');
|
||||
}
|
||||
|
||||
this.tokens.push({
|
||||
type: loose
|
||||
? 'loose_item_start'
|
||||
: 'list_item_start'
|
||||
: 'list_item_start',
|
||||
task: istask,
|
||||
checked: ischecked
|
||||
});
|
||||
|
||||
// Recurse.
|
||||
@@ -372,7 +416,7 @@ Lexer.prototype.token = function(src, top) {
|
||||
if (top && (cap = this.rules.def.exec(src))) {
|
||||
src = src.substring(cap[0].length);
|
||||
if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
|
||||
tag = cap[1].toLowerCase();
|
||||
tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
|
||||
if (!this.tokens.links[tag]) {
|
||||
this.tokens.links[tag] = {
|
||||
href: cap[2],
|
||||
@@ -384,36 +428,38 @@ Lexer.prototype.token = function(src, top) {
|
||||
|
||||
// table (gfm)
|
||||
if (top && (cap = this.rules.table.exec(src))) {
|
||||
src = src.substring(cap[0].length);
|
||||
|
||||
item = {
|
||||
type: 'table',
|
||||
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
|
||||
header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
|
||||
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
|
||||
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
|
||||
cells: cap[3] ? cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') : []
|
||||
};
|
||||
|
||||
for (i = 0; i < item.align.length; i++) {
|
||||
if (/^ *-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'right';
|
||||
} else if (/^ *:-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'center';
|
||||
} else if (/^ *:-+ *$/.test(item.align[i])) {
|
||||
item.align[i] = 'left';
|
||||
} else {
|
||||
item.align[i] = null;
|
||||
if (item.header.length === item.align.length) {
|
||||
src = src.substring(cap[0].length);
|
||||
|
||||
for (i = 0; i < item.align.length; i++) {
|
||||
if (/^ *-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'right';
|
||||
} else if (/^ *:-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'center';
|
||||
} else if (/^ *:-+ *$/.test(item.align[i])) {
|
||||
item.align[i] = 'left';
|
||||
} else {
|
||||
item.align[i] = null;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < item.cells.length; i++) {
|
||||
item.cells[i] = splitCells(
|
||||
item.cells[i].replace(/^ *\| *| *\| *$/g, ''),
|
||||
item.header.length);
|
||||
}
|
||||
|
||||
this.tokens.push(item);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (i = 0; i < item.cells.length; i++) {
|
||||
item.cells[i] = item.cells[i]
|
||||
.replace(/^ *\| *| *\| *$/g, '')
|
||||
.split(/ *\| */);
|
||||
}
|
||||
|
||||
this.tokens.push(item);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// lheading
|
||||
@@ -463,39 +509,54 @@ Lexer.prototype.token = function(src, top) {
|
||||
*/
|
||||
|
||||
var inline = {
|
||||
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
|
||||
escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
|
||||
autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
|
||||
url: noop,
|
||||
tag: /^<!--[\s\S]*?-->|^<\/?[a-zA-Z0-9\-]+(?:"[^"]*"|'[^']*'|\s[^<'">\/\s]*)*?\/?>/,
|
||||
link: /^!?\[(inside)\]\(href\)/,
|
||||
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
|
||||
nolink: /^!?\[((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\]/,
|
||||
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
|
||||
em: /^_([^\s_](?:[^_]|__)+?[^\s_])_\b|^\*((?:\*\*|[^*])+?)\*(?!\*)/,
|
||||
tag: '^comment'
|
||||
+ '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
|
||||
+ '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
|
||||
+ '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
|
||||
+ '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
|
||||
+ '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', // CDATA section
|
||||
link: /^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,
|
||||
reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
|
||||
nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
|
||||
strong: /^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)|^__([^\s])__(?!_)|^\*\*([^\s])\*\*(?!\*)/,
|
||||
em: /^_([^\s][\s\S]*?[^\s_])_(?!_)|^_([^\s_][\s\S]*?[^\s])_(?!_)|^\*([^\s][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*][\s\S]*?[^\s])\*(?!\*)|^_([^\s_])_(?!_)|^\*([^\s*])\*(?!\*)/,
|
||||
code: /^(`+)\s*([\s\S]*?[^`]?)\s*\1(?!`)/,
|
||||
br: /^ {2,}\n(?!\s*$)/,
|
||||
del: noop,
|
||||
text: /^[\s\S]+?(?=[\\<!\[`*]|\b_| {2,}\n|$)/
|
||||
};
|
||||
|
||||
inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
|
||||
|
||||
inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
|
||||
inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
|
||||
|
||||
inline.autolink = edit(inline.autolink)
|
||||
.replace('scheme', inline._scheme)
|
||||
.replace('email', inline._email)
|
||||
.getRegex()
|
||||
.getRegex();
|
||||
|
||||
inline._inside = /(?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]]|\](?=[^\[]*\]))*/;
|
||||
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
|
||||
inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
|
||||
|
||||
inline.tag = edit(inline.tag)
|
||||
.replace('comment', block._comment)
|
||||
.replace('attribute', inline._attribute)
|
||||
.getRegex();
|
||||
|
||||
inline._label = /(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?/;
|
||||
inline._href = /\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f()\\]*\)|[^\s\x00-\x1f()\\])*?)/;
|
||||
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
|
||||
|
||||
inline.link = edit(inline.link)
|
||||
.replace('inside', inline._inside)
|
||||
.replace('label', inline._label)
|
||||
.replace('href', inline._href)
|
||||
.replace('title', inline._title)
|
||||
.getRegex();
|
||||
|
||||
inline.reflink = edit(inline.reflink)
|
||||
.replace('inside', inline._inside)
|
||||
.replace('label', inline._label)
|
||||
.getRegex();
|
||||
|
||||
/**
|
||||
@@ -510,7 +571,13 @@ inline.normal = merge({}, inline);
|
||||
|
||||
inline.pedantic = merge({}, inline.normal, {
|
||||
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
|
||||
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
|
||||
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
|
||||
link: edit(/^!?\[(label)\]\((.*?)\)/)
|
||||
.replace('label', inline._label)
|
||||
.getRegex(),
|
||||
reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
|
||||
.replace('label', inline._label)
|
||||
.getRegex()
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -554,14 +621,14 @@ function InlineLexer(links, options) {
|
||||
throw new Error('Tokens array requires a `links` property.');
|
||||
}
|
||||
|
||||
if (this.options.gfm) {
|
||||
if (this.options.pedantic) {
|
||||
this.rules = inline.pedantic;
|
||||
} else if (this.options.gfm) {
|
||||
if (this.options.breaks) {
|
||||
this.rules = inline.breaks;
|
||||
} else {
|
||||
this.rules = inline.gfm;
|
||||
}
|
||||
} else if (this.options.pedantic) {
|
||||
this.rules = inline.pedantic;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -589,6 +656,7 @@ InlineLexer.prototype.output = function(src) {
|
||||
link,
|
||||
text,
|
||||
href,
|
||||
title,
|
||||
cap;
|
||||
|
||||
while (src) {
|
||||
@@ -652,9 +720,23 @@ InlineLexer.prototype.output = function(src) {
|
||||
if (cap = this.rules.link.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
this.inLink = true;
|
||||
href = cap[2];
|
||||
if (this.options.pedantic) {
|
||||
link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
|
||||
|
||||
if (link) {
|
||||
href = link[1];
|
||||
title = link[3];
|
||||
} else {
|
||||
title = '';
|
||||
}
|
||||
} else {
|
||||
title = cap[3] ? cap[3].slice(1, -1) : '';
|
||||
}
|
||||
href = href.trim().replace(/^<([\s\S]*)>$/, '$1');
|
||||
out += this.outputLink(cap, {
|
||||
href: cap[2],
|
||||
title: cap[3]
|
||||
href: InlineLexer.escapes(href),
|
||||
title: InlineLexer.escapes(title)
|
||||
});
|
||||
this.inLink = false;
|
||||
continue;
|
||||
@@ -680,14 +762,14 @@ InlineLexer.prototype.output = function(src) {
|
||||
// strong
|
||||
if (cap = this.rules.strong.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += this.renderer.strong(this.output(cap[2] || cap[1]));
|
||||
out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1]));
|
||||
continue;
|
||||
}
|
||||
|
||||
// em
|
||||
if (cap = this.rules.em.exec(src)) {
|
||||
src = src.substring(cap[0].length);
|
||||
out += this.renderer.em(this.output(cap[2] || cap[1]));
|
||||
out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -727,12 +809,16 @@ InlineLexer.prototype.output = function(src) {
|
||||
return out;
|
||||
};
|
||||
|
||||
InlineLexer.escapes = function(text) {
|
||||
return text ? text.replace(InlineLexer.rules._escapes, '$1') : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile Link
|
||||
*/
|
||||
|
||||
InlineLexer.prototype.outputLink = function(cap, link) {
|
||||
var href = escape(link.href),
|
||||
var href = link.href,
|
||||
title = link.title ? escape(link.title) : null;
|
||||
|
||||
return cap[0].charAt(0) !== '!'
|
||||
@@ -790,7 +876,7 @@ InlineLexer.prototype.mangle = function(text) {
|
||||
*/
|
||||
|
||||
function Renderer(options) {
|
||||
this.options = options || {};
|
||||
this.options = options || marked.defaults;
|
||||
}
|
||||
|
||||
Renderer.prototype.code = function(code, lang, escaped) {
|
||||
@@ -805,7 +891,7 @@ Renderer.prototype.code = function(code, lang, escaped) {
|
||||
if (!lang) {
|
||||
return '<pre><code>'
|
||||
+ (escaped ? code : escape(code, true))
|
||||
+ '\n</code></pre>';
|
||||
+ '</code></pre>';
|
||||
}
|
||||
|
||||
return '<pre><code class="'
|
||||
@@ -813,7 +899,7 @@ Renderer.prototype.code = function(code, lang, escaped) {
|
||||
+ escape(lang, true)
|
||||
+ '">'
|
||||
+ (escaped ? code : escape(code, true))
|
||||
+ '\n</code></pre>\n';
|
||||
+ '</code></pre>\n';
|
||||
};
|
||||
|
||||
Renderer.prototype.blockquote = function(quote) {
|
||||
@@ -825,16 +911,20 @@ Renderer.prototype.html = function(html) {
|
||||
};
|
||||
|
||||
Renderer.prototype.heading = function(text, level, raw) {
|
||||
return '<h'
|
||||
+ level
|
||||
+ ' id="'
|
||||
+ this.options.headerPrefix
|
||||
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
|
||||
+ '">'
|
||||
+ text
|
||||
+ '</h'
|
||||
+ level
|
||||
+ '>\n';
|
||||
if (this.options.headerIds) {
|
||||
return '<h'
|
||||
+ level
|
||||
+ ' id="'
|
||||
+ this.options.headerPrefix
|
||||
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
|
||||
+ '">'
|
||||
+ text
|
||||
+ '</h'
|
||||
+ level
|
||||
+ '>\n';
|
||||
}
|
||||
// ignore IDs
|
||||
return '<h' + level + '>' + text + '</h' + level + '>\n';
|
||||
};
|
||||
|
||||
Renderer.prototype.hr = function() {
|
||||
@@ -851,18 +941,26 @@ Renderer.prototype.listitem = function(text) {
|
||||
return '<li>' + text + '</li>\n';
|
||||
};
|
||||
|
||||
Renderer.prototype.checkbox = function(checked) {
|
||||
return '<input '
|
||||
+ (checked ? 'checked="" ' : '')
|
||||
+ 'disabled="" type="checkbox"'
|
||||
+ (this.options.xhtml ? ' /' : '')
|
||||
+ '> ';
|
||||
}
|
||||
|
||||
Renderer.prototype.paragraph = function(text) {
|
||||
return '<p>' + text + '</p>\n';
|
||||
};
|
||||
|
||||
Renderer.prototype.table = function(header, body) {
|
||||
if (body) body = '<tbody>' + body + '</tbody>';
|
||||
|
||||
return '<table>\n'
|
||||
+ '<thead>\n'
|
||||
+ header
|
||||
+ '</thead>\n'
|
||||
+ '<tbody>\n'
|
||||
+ body
|
||||
+ '</tbody>\n'
|
||||
+ '</table>\n';
|
||||
};
|
||||
|
||||
@@ -873,7 +971,7 @@ Renderer.prototype.tablerow = function(content) {
|
||||
Renderer.prototype.tablecell = function(content, flags) {
|
||||
var type = flags.header ? 'th' : 'td';
|
||||
var tag = flags.align
|
||||
? '<' + type + ' style="text-align:' + flags.align + '">'
|
||||
? '<' + type + ' align="' + flags.align + '">'
|
||||
: '<' + type + '>';
|
||||
return tag + content + '</' + type + '>\n';
|
||||
};
|
||||
@@ -915,7 +1013,12 @@ Renderer.prototype.link = function(href, title, text) {
|
||||
if (this.options.baseUrl && !originIndependentUrl.test(href)) {
|
||||
href = resolveUrl(this.options.baseUrl, href);
|
||||
}
|
||||
var out = '<a href="' + href + '"';
|
||||
try {
|
||||
href = encodeURI(href).replace(/%25/g, '%');
|
||||
} catch (e) {
|
||||
return text;
|
||||
}
|
||||
var out = '<a href="' + escape(href) + '"';
|
||||
if (title) {
|
||||
out += ' title="' + title + '"';
|
||||
}
|
||||
@@ -1117,6 +1220,10 @@ Parser.prototype.tok = function() {
|
||||
case 'list_item_start': {
|
||||
body = '';
|
||||
|
||||
if (this.token.task) {
|
||||
body += this.renderer.checkbox(this.token.checked);
|
||||
}
|
||||
|
||||
while (this.next().type !== 'list_item_end') {
|
||||
body += this.token.type === 'text'
|
||||
? this.parseText()
|
||||
@@ -1135,10 +1242,8 @@ Parser.prototype.tok = function() {
|
||||
return this.renderer.listitem(body);
|
||||
}
|
||||
case 'html': {
|
||||
var html = !this.token.pre && !this.options.pedantic
|
||||
? this.inline.output(this.token.text)
|
||||
: this.token.text;
|
||||
return this.renderer.html(html);
|
||||
// TODO parse inline content if parameter markdown=1
|
||||
return this.renderer.html(this.token.text);
|
||||
}
|
||||
case 'paragraph': {
|
||||
return this.renderer.paragraph(this.inline.output(this.token.text));
|
||||
@@ -1177,7 +1282,7 @@ function unescape(html) {
|
||||
}
|
||||
|
||||
function edit(regex, opt) {
|
||||
regex = regex.source;
|
||||
regex = regex.source || regex;
|
||||
opt = opt || '';
|
||||
return {
|
||||
replace: function(name, val) {
|
||||
@@ -1200,7 +1305,7 @@ function resolveUrl(base, href) {
|
||||
if (/^[^:]+:\/*[^/]*$/.test(base)) {
|
||||
baseUrls[' ' + base] = base + '/';
|
||||
} else {
|
||||
baseUrls[' ' + base] = base.replace(/[^/]*$/, '');
|
||||
baseUrls[' ' + base] = rtrim(base, '/', true);
|
||||
}
|
||||
}
|
||||
base = baseUrls[' ' + base];
|
||||
@@ -1236,6 +1341,64 @@ function merge(obj) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
function splitCells(tableRow, count) {
|
||||
// ensure that every cell-delimiting pipe has a space
|
||||
// before it to distinguish it from an escaped pipe
|
||||
var row = tableRow.replace(/\|/g, function (match, offset, str) {
|
||||
var escaped = false,
|
||||
curr = offset;
|
||||
while (--curr >= 0 && str[curr] === '\\') escaped = !escaped;
|
||||
if (escaped) {
|
||||
// odd number of slashes means | is escaped
|
||||
// so we leave it alone
|
||||
return '|';
|
||||
} else {
|
||||
// add space before unescaped |
|
||||
return ' |';
|
||||
}
|
||||
}),
|
||||
cells = row.split(/ \|/),
|
||||
i = 0;
|
||||
|
||||
if (cells.length > count) {
|
||||
cells.splice(count);
|
||||
} else {
|
||||
while (cells.length < count) cells.push('');
|
||||
}
|
||||
|
||||
for (; i < cells.length; i++) {
|
||||
// leading or trailing whitespace is ignored per the gfm spec
|
||||
cells[i] = cells[i].trim().replace(/\\\|/g, '|');
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
// Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
|
||||
// /c*$/ is vulnerable to REDOS.
|
||||
// invert: Remove suffix of non-c chars instead. Default falsey.
|
||||
function rtrim(str, c, invert) {
|
||||
if (str.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Length of suffix matching the invert condition.
|
||||
var suffLen = 0;
|
||||
|
||||
// Step left until we fail to match the invert condition.
|
||||
while (suffLen < str.length) {
|
||||
var currChar = str.charAt(str.length - suffLen - 1);
|
||||
if (currChar === c && !invert) {
|
||||
suffLen++;
|
||||
} else if (currChar !== c && invert) {
|
||||
suffLen++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return str.substr(0, str.length - suffLen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marked
|
||||
*/
|
||||
@@ -1343,24 +1506,29 @@ marked.setOptions = function(opt) {
|
||||
return marked;
|
||||
};
|
||||
|
||||
marked.defaults = {
|
||||
gfm: true,
|
||||
tables: true,
|
||||
breaks: false,
|
||||
pedantic: false,
|
||||
sanitize: false,
|
||||
sanitizer: null,
|
||||
mangle: true,
|
||||
smartLists: false,
|
||||
silent: false,
|
||||
highlight: null,
|
||||
langPrefix: 'lang-',
|
||||
smartypants: false,
|
||||
headerPrefix: '',
|
||||
renderer: new Renderer(),
|
||||
xhtml: false,
|
||||
baseUrl: null
|
||||
};
|
||||
marked.getDefaults = function () {
|
||||
return {
|
||||
baseUrl: null,
|
||||
breaks: false,
|
||||
gfm: true,
|
||||
headerIds: true,
|
||||
headerPrefix: '',
|
||||
highlight: null,
|
||||
langPrefix: 'language-',
|
||||
mangle: true,
|
||||
pedantic: false,
|
||||
renderer: new Renderer(),
|
||||
sanitize: false,
|
||||
sanitizer: null,
|
||||
silent: false,
|
||||
smartLists: false,
|
||||
smartypants: false,
|
||||
tables: true,
|
||||
xhtml: false
|
||||
};
|
||||
}
|
||||
|
||||
marked.defaults = marked.getDefaults();
|
||||
|
||||
/**
|
||||
* Expose
|
||||
@@ -1379,16 +1547,15 @@ marked.InlineLexer = InlineLexer;
|
||||
marked.inlineLexer = InlineLexer.output;
|
||||
|
||||
marked.parse = marked;
|
||||
|
||||
__marked_exports = marked;
|
||||
|
||||
}).call(this);
|
||||
|
||||
// ESM-comment-begin
|
||||
define([], function() {
|
||||
return {
|
||||
marked: __marked_exports
|
||||
};
|
||||
return {
|
||||
marked: __marked_exports
|
||||
};
|
||||
});
|
||||
// ESM-comment-end
|
||||
|
||||
|
||||
@@ -238,4 +238,63 @@ export function suggestFilename(langId: string, prefix: string): string {
|
||||
}
|
||||
|
||||
return prefix; // without any known extension, just return the prefix
|
||||
}
|
||||
|
||||
interface MapExtToMediaMimes {
|
||||
[index: string]: string;
|
||||
}
|
||||
|
||||
// Known media mimes that we can handle
|
||||
const mapExtToMediaMimes: MapExtToMediaMimes = {
|
||||
'.bmp': 'image/bmp',
|
||||
'.gif': 'image/gif',
|
||||
'.jpg': 'image/jpg',
|
||||
'.jpeg': 'image/jpg',
|
||||
'.jpe': 'image/jpg',
|
||||
'.png': 'image/png',
|
||||
'.tiff': 'image/tiff',
|
||||
'.tif': 'image/tiff',
|
||||
'.ico': 'image/x-icon',
|
||||
'.tga': 'image/x-tga',
|
||||
'.psd': 'image/vnd.adobe.photoshop',
|
||||
'.webp': 'image/webp',
|
||||
'.mid': 'audio/midi',
|
||||
'.midi': 'audio/midi',
|
||||
'.mp4a': 'audio/mp4',
|
||||
'.mpga': 'audio/mpeg',
|
||||
'.mp2': 'audio/mpeg',
|
||||
'.mp2a': 'audio/mpeg',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.m2a': 'audio/mpeg',
|
||||
'.m3a': 'audio/mpeg',
|
||||
'.oga': 'audio/ogg',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.spx': 'audio/ogg',
|
||||
'.aac': 'audio/x-aac',
|
||||
'.wav': 'audio/x-wav',
|
||||
'.wma': 'audio/x-ms-wma',
|
||||
'.mp4': 'video/mp4',
|
||||
'.mp4v': 'video/mp4',
|
||||
'.mpg4': 'video/mp4',
|
||||
'.mpeg': 'video/mpeg',
|
||||
'.mpg': 'video/mpeg',
|
||||
'.mpe': 'video/mpeg',
|
||||
'.m1v': 'video/mpeg',
|
||||
'.m2v': 'video/mpeg',
|
||||
'.ogv': 'video/ogg',
|
||||
'.qt': 'video/quicktime',
|
||||
'.mov': 'video/quicktime',
|
||||
'.webm': 'video/webm',
|
||||
'.mkv': 'video/x-matroska',
|
||||
'.mk3d': 'video/x-matroska',
|
||||
'.mks': 'video/x-matroska',
|
||||
'.wmv': 'video/x-ms-wmv',
|
||||
'.flv': 'video/x-flv',
|
||||
'.avi': 'video/x-msvideo',
|
||||
'.movie': 'video/x-sgi-movie'
|
||||
};
|
||||
|
||||
export function getMediaMime(path: string): string | undefined {
|
||||
const ext = paths.extname(path);
|
||||
return mapExtToMediaMimes[ext.toLowerCase()];
|
||||
}
|
||||
49
src/vs/base/common/normalization.ts
Normal file
49
src/vs/base/common/normalization.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { LRUCache } from 'vs/base/common/map';
|
||||
|
||||
/**
|
||||
* The normalize() method returns the Unicode Normalization Form of a given string. The form will be
|
||||
* the Normalization Form Canonical Composition.
|
||||
*
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize}
|
||||
*/
|
||||
export const canNormalize = typeof ((<any>'').normalize) === 'function';
|
||||
|
||||
const nfcCache = new LRUCache<string, string>(10000); // bounded to 10000 elements
|
||||
export function normalizeNFC(str: string): string {
|
||||
return normalize(str, 'NFC', nfcCache);
|
||||
}
|
||||
|
||||
const nfdCache = new LRUCache<string, string>(10000); // bounded to 10000 elements
|
||||
export function normalizeNFD(str: string): string {
|
||||
return normalize(str, 'NFD', nfdCache);
|
||||
}
|
||||
|
||||
const nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
|
||||
function normalize(str: string, form: string, normalizedCache: LRUCache<string, string>): string {
|
||||
if (!canNormalize || !str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
const cached = normalizedCache.get(str);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
let res: string;
|
||||
if (nonAsciiCharactersPattern.test(str)) {
|
||||
res = (<any>str).normalize(form);
|
||||
} else {
|
||||
res = str;
|
||||
}
|
||||
|
||||
// Use the cache for fast lookup
|
||||
normalizedCache.set(str, res);
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export function deepClone<T>(obj: T): T {
|
||||
return obj as any;
|
||||
}
|
||||
const result: any = Array.isArray(obj) ? [] : {};
|
||||
Object.keys(obj).forEach((key: keyof T) => {
|
||||
Object.keys(obj).forEach((key: string) => {
|
||||
if (obj[key] && typeof obj[key] === 'object') {
|
||||
result[key] = deepClone(obj[key]);
|
||||
} else {
|
||||
@@ -225,6 +225,7 @@ export function getOrDefault<T, R>(obj: T, fn: (obj: T) => R, defaultValue: R =
|
||||
return typeof result === 'undefined' ? defaultValue : result;
|
||||
}
|
||||
|
||||
type obj = { [key: string]: any; };
|
||||
/**
|
||||
* Returns an object that has keys for each value that is different in the base object. Keys
|
||||
* that do not exist in the target but in the base object are not considered.
|
||||
@@ -235,7 +236,6 @@ export function getOrDefault<T, R>(obj: T, fn: (obj: T) => R, defaultValue: R =
|
||||
* @param base the object to diff against
|
||||
* @param obj the object to use for diffing
|
||||
*/
|
||||
export type obj = { [key: string]: any; };
|
||||
export function distinct(base: obj, target: obj): obj {
|
||||
const result = Object.create(null);
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ export abstract class Parser {
|
||||
}
|
||||
|
||||
protected static merge<T>(destination: T, source: T, overwrite: boolean): void {
|
||||
Object.keys(source).forEach((key: keyof T) => {
|
||||
Object.keys(source).forEach((key: string) => {
|
||||
let destValue = destination[key];
|
||||
let sourceValue = source[key];
|
||||
if (Types.isUndefined(sourceValue)) {
|
||||
|
||||
@@ -53,7 +53,7 @@ export function basename(path: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {{.far}} from boo.far or the empty string.
|
||||
* @returns `.far` from `boo.far` or the empty string.
|
||||
*/
|
||||
export function extname(path: string): string {
|
||||
path = basename(path);
|
||||
@@ -328,7 +328,7 @@ export function isEqual(pathA: string, pathB: string, ignoreCase?: boolean): boo
|
||||
return equalsIgnoreCase(pathA, pathB);
|
||||
}
|
||||
|
||||
export function isEqualOrParent(path: string, candidate: string, ignoreCase?: boolean): boolean {
|
||||
export function isEqualOrParent(path: string, candidate: string, ignoreCase?: boolean, separator = nativeSep): boolean {
|
||||
if (path === candidate) {
|
||||
return true;
|
||||
}
|
||||
@@ -352,15 +352,15 @@ export function isEqualOrParent(path: string, candidate: string, ignoreCase?: bo
|
||||
}
|
||||
|
||||
let sepOffset = candidate.length;
|
||||
if (candidate.charAt(candidate.length - 1) === nativeSep) {
|
||||
if (candidate.charAt(candidate.length - 1) === separator) {
|
||||
sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character
|
||||
}
|
||||
|
||||
return path.charAt(sepOffset) === nativeSep;
|
||||
return path.charAt(sepOffset) === separator;
|
||||
}
|
||||
|
||||
if (candidate.charAt(candidate.length - 1) !== nativeSep) {
|
||||
candidate += nativeSep;
|
||||
if (candidate.charAt(candidate.length - 1) !== separator) {
|
||||
candidate += separator;
|
||||
}
|
||||
|
||||
return path.indexOf(candidate) === 0;
|
||||
|
||||
5
src/vs/base/common/performance.d.ts
vendored
5
src/vs/base/common/performance.d.ts
vendored
@@ -14,11 +14,6 @@ export function mark(name: string): void;
|
||||
|
||||
export function measure(name: string, from?: string, to?: string): PerformanceEntry;
|
||||
|
||||
/**
|
||||
* Time something, shorthant for `mark` and `measure`
|
||||
*/
|
||||
export function time(name: string): { stop(): void };
|
||||
|
||||
/**
|
||||
* All entries filtered by type and sorted by `startTime`.
|
||||
*/
|
||||
|
||||
@@ -42,31 +42,33 @@ define([], function () {
|
||||
function getEntries(type, name) {
|
||||
const result = [];
|
||||
const entries = global._performanceEntries;
|
||||
for (let i = 0; i < entries.length; i += 4) {
|
||||
for (let i = 0; i < entries.length; i += 5) {
|
||||
if (entries[i] === type && (name === void 0 || entries[i + 1] === name)) {
|
||||
result.push({
|
||||
type: entries[i],
|
||||
name: entries[i + 1],
|
||||
startTime: entries[i + 2],
|
||||
duration: entries[i + 3],
|
||||
seq: entries[i + 4],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result.sort((a, b) => {
|
||||
return a.startTime - b.startTime;
|
||||
return a.startTime - b.startTime || a.seq - b.seq;
|
||||
});
|
||||
}
|
||||
|
||||
function getEntry(type, name) {
|
||||
const entries = global._performanceEntries;
|
||||
for (let i = 0; i < entries.length; i += 4) {
|
||||
for (let i = 0; i < entries.length; i += 5) {
|
||||
if (entries[i] === type && entries[i + 1] === name) {
|
||||
return {
|
||||
type: entries[i],
|
||||
name: entries[i + 1],
|
||||
startTime: entries[i + 2],
|
||||
duration: entries[i + 3],
|
||||
seq: entries[i + 4],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -76,7 +78,7 @@ define([], function () {
|
||||
const entries = global._performanceEntries;
|
||||
let name = from;
|
||||
let startTime = 0;
|
||||
for (let i = 0; i < entries.length; i += 4) {
|
||||
for (let i = 0; i < entries.length; i += 5) {
|
||||
if (entries[i + 1] === name) {
|
||||
if (name === from) {
|
||||
// found `from` (start of interval)
|
||||
@@ -91,19 +93,15 @@ define([], function () {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
|
||||
function mark(name) {
|
||||
global._performanceEntries.push('mark', name, _now(), 0);
|
||||
global._performanceEntries.push('mark', name, _now(), 0, seq++);
|
||||
if (typeof console.timeStamp === 'function') {
|
||||
console.timeStamp(name);
|
||||
}
|
||||
}
|
||||
|
||||
function time(name) {
|
||||
let from = `${name}/start`;
|
||||
mark(from);
|
||||
return { stop() { measure(name, from); } };
|
||||
}
|
||||
|
||||
function measure(name, from, to) {
|
||||
|
||||
let startTime;
|
||||
@@ -127,9 +125,9 @@ define([], function () {
|
||||
|
||||
function _getLastStartTime(name) {
|
||||
const entries = global._performanceEntries;
|
||||
for (let i = entries.length - 1; i >= 0; i -= 4) {
|
||||
if (entries[i - 2] === name) {
|
||||
return entries[i - 1];
|
||||
for (let i = entries.length - 1; i >= 0; i -= 5) {
|
||||
if (entries[i - 3] === name) {
|
||||
return entries[i - 2];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +137,6 @@ define([], function () {
|
||||
var exports = {
|
||||
mark: mark,
|
||||
measure: measure,
|
||||
time: time,
|
||||
getEntries: getEntries,
|
||||
getEntry: getEntry,
|
||||
getDuration: getDuration,
|
||||
|
||||
@@ -46,6 +46,8 @@ if (typeof process === 'object' && typeof process.nextTick === 'function' && typ
|
||||
_isWindows = (process.platform === 'win32');
|
||||
_isMacintosh = (process.platform === 'darwin');
|
||||
_isLinux = (process.platform === 'linux');
|
||||
_locale = LANGUAGE_DEFAULT;
|
||||
_language = LANGUAGE_DEFAULT;
|
||||
const rawNlsConfig = process.env['VSCODE_NLS_CONFIG'];
|
||||
if (rawNlsConfig) {
|
||||
try {
|
||||
|
||||
@@ -7,6 +7,18 @@
|
||||
import * as paths from 'vs/base/common/paths';
|
||||
import uri from 'vs/base/common/uri';
|
||||
import { equalsIgnoreCase } from 'vs/base/common/strings';
|
||||
import { Schemas } from 'vs/base/common/network';
|
||||
import { isLinux } from 'vs/base/common/platform';
|
||||
|
||||
export function getComparisonKey(resource: uri): string {
|
||||
return hasToIgnoreCase(resource) ? resource.toString().toLowerCase() : resource.toString();
|
||||
}
|
||||
|
||||
export function hasToIgnoreCase(resource: uri): boolean {
|
||||
// A file scheme resource is in the same platform as code, so ignore case for non linux platforms
|
||||
// Resource can be from another platform. Lowering the case as an hack. Should come from File system provider
|
||||
return resource && resource.scheme === Schemas.file ? !isLinux : true;
|
||||
}
|
||||
|
||||
export function basenameOrAuthority(resource: uri): string {
|
||||
return paths.basename(resource.path) || resource.authority;
|
||||
@@ -18,7 +30,7 @@ export function isEqualOrParent(resource: uri, candidate: uri, ignoreCase?: bool
|
||||
return paths.isEqualOrParent(resource.fsPath, candidate.fsPath, ignoreCase);
|
||||
}
|
||||
|
||||
return paths.isEqualOrParent(resource.path, candidate.path, ignoreCase);
|
||||
return paths.isEqualOrParent(resource.path, candidate.path, ignoreCase, '/');
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -52,6 +64,13 @@ export function dirname(resource: uri): uri {
|
||||
});
|
||||
}
|
||||
|
||||
export function joinPath(resource: uri, pathFragment: string): uri {
|
||||
const joinedPath = paths.join(resource.path || '/', pathFragment);
|
||||
return resource.with({
|
||||
path: joinedPath
|
||||
});
|
||||
}
|
||||
|
||||
export function distinctParents<T>(items: T[], resourceAccessor: (item: T) => uri): T[] {
|
||||
const distinctParents: T[] = [];
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
|
||||
@@ -229,7 +229,7 @@ export class Scrollable extends Disposable {
|
||||
|
||||
/**
|
||||
* Returns the final scroll position that the instance will have once the smooth scroll animation concludes.
|
||||
* If no scroll animation is occuring, it will return the current scroll position instead.
|
||||
* If no scroll animation is occurring, it will return the current scroll position instead.
|
||||
*/
|
||||
public getFutureScrollPosition(): IScrollPosition {
|
||||
if (this._smoothScrolling) {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { LRUCache } from 'vs/base/common/map';
|
||||
import { CharCode } from 'vs/base/common/charCode';
|
||||
|
||||
/**
|
||||
@@ -239,48 +238,6 @@ export function regExpContainsBackreference(regexpValue: string): boolean {
|
||||
return !!regexpValue.match(/([^\\]|^)(\\\\)*\\\d+/);
|
||||
}
|
||||
|
||||
/**
|
||||
* The normalize() method returns the Unicode Normalization Form of a given string. The form will be
|
||||
* the Normalization Form Canonical Composition.
|
||||
*
|
||||
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize}
|
||||
*/
|
||||
export const canNormalize = typeof ((<any>'').normalize) === 'function';
|
||||
|
||||
const nfcCache = new LRUCache<string, string>(10000); // bounded to 10000 elements
|
||||
export function normalizeNFC(str: string): string {
|
||||
return normalize(str, 'NFC', nfcCache);
|
||||
}
|
||||
|
||||
const nfdCache = new LRUCache<string, string>(10000); // bounded to 10000 elements
|
||||
export function normalizeNFD(str: string): string {
|
||||
return normalize(str, 'NFD', nfdCache);
|
||||
}
|
||||
|
||||
const nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
|
||||
function normalize(str: string, form: string, normalizedCache: LRUCache<string, string>): string {
|
||||
if (!canNormalize || !str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
const cached = normalizedCache.get(str);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
let res: string;
|
||||
if (nonAsciiCharactersPattern.test(str)) {
|
||||
res = (<any>str).normalize(form);
|
||||
} else {
|
||||
res = str;
|
||||
}
|
||||
|
||||
// Use the cache for fast lookup
|
||||
normalizedCache.set(str, res);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns first index of the string that is not whitespace.
|
||||
* If string is empty or contains only whitespaces, returns -1
|
||||
@@ -376,11 +333,11 @@ export function compareIgnoreCase(a: string, b: string): number {
|
||||
}
|
||||
}
|
||||
|
||||
function isLowerAsciiLetter(code: number): boolean {
|
||||
export function isLowerAsciiLetter(code: number): boolean {
|
||||
return code >= CharCode.a && code <= CharCode.z;
|
||||
}
|
||||
|
||||
function isUpperAsciiLetter(code: number): boolean {
|
||||
export function isUpperAsciiLetter(code: number): boolean {
|
||||
return code >= CharCode.A && code <= CharCode.Z;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,22 +4,8 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import * as platform from 'vs/base/common/platform';
|
||||
|
||||
|
||||
function _encode(ch: string): string {
|
||||
return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
|
||||
}
|
||||
|
||||
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
|
||||
function encodeURIComponent2(str: string): string {
|
||||
return encodeURIComponent(str).replace(/[!'()*]/g, _encode);
|
||||
}
|
||||
|
||||
function encodeNoop(str: string): string {
|
||||
return str.replace(/[#?]/, _encode);
|
||||
}
|
||||
|
||||
import { isWindows } from 'vs/base/common/platform';
|
||||
import { CharCode } from 'vs/base/common/charCode';
|
||||
|
||||
const _schemePattern = /^\w[\w\d+.-]*$/;
|
||||
const _singleSlashStart = /^\//;
|
||||
@@ -50,12 +36,30 @@ function _validateUri(ret: URI): void {
|
||||
}
|
||||
}
|
||||
|
||||
// implements a bit of https://tools.ietf.org/html/rfc3986#section-5
|
||||
function _referenceResolution(scheme: string, path: string): string {
|
||||
|
||||
// the slash-character is our 'default base' as we don't
|
||||
// support constructing URIs relative to other URIs. This
|
||||
// also means that we alter and potentially break paths.
|
||||
// see https://tools.ietf.org/html/rfc3986#section-5.1.4
|
||||
switch (scheme) {
|
||||
case 'https':
|
||||
case 'http':
|
||||
case 'file':
|
||||
if (!path) {
|
||||
path = _slash;
|
||||
} else if (path[0] !== _slash) {
|
||||
path = _slash + path;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
const _empty = '';
|
||||
const _slash = '/';
|
||||
const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
|
||||
const _driveLetterPath = /^\/[a-zA-Z]:/;
|
||||
const _upperCaseDrive = /^(\/)?([A-Z]:)/;
|
||||
const _driveLetter = /^[a-zA-Z]:/;
|
||||
|
||||
/**
|
||||
* Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
|
||||
@@ -143,9 +147,10 @@ export default class URI implements UriComponents {
|
||||
} else {
|
||||
this.scheme = schemeOrData || _empty;
|
||||
this.authority = authority || _empty;
|
||||
this.path = path || _empty;
|
||||
this.path = _referenceResolution(this.scheme, path || _empty);
|
||||
this.query = query || _empty;
|
||||
this.fragment = fragment || _empty;
|
||||
|
||||
_validateUri(this);
|
||||
}
|
||||
}
|
||||
@@ -232,7 +237,7 @@ export default class URI implements UriComponents {
|
||||
// normalize to fwd-slashes on windows,
|
||||
// on other systems bwd-slashes are valid
|
||||
// filename character, eg /f\oo/ba\r.txt
|
||||
if (platform.isWindows) {
|
||||
if (isWindows) {
|
||||
path = path.replace(/\\/g, _slash);
|
||||
}
|
||||
|
||||
@@ -249,18 +254,6 @@ export default class URI implements UriComponents {
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure that path starts with a slash
|
||||
// or that it is at least a slash
|
||||
if (_driveLetter.test(path)) {
|
||||
path = _slash + path;
|
||||
|
||||
} else if (path[0] !== _slash) {
|
||||
// tricky -> makes invalid paths
|
||||
// but otherwise we have to stop
|
||||
// allowing relative paths...
|
||||
path = _slash + path;
|
||||
}
|
||||
|
||||
return new _URI('file', authority, path, _empty, _empty);
|
||||
}
|
||||
|
||||
@@ -285,33 +278,7 @@ export default class URI implements UriComponents {
|
||||
}
|
||||
|
||||
public toJSON(): object {
|
||||
const res = <UriState>{
|
||||
$mid: 1,
|
||||
fsPath: this.fsPath,
|
||||
external: this.toString(),
|
||||
};
|
||||
|
||||
if (this.path) {
|
||||
res.path = this.path;
|
||||
}
|
||||
|
||||
if (this.scheme) {
|
||||
res.scheme = this.scheme;
|
||||
}
|
||||
|
||||
if (this.authority) {
|
||||
res.authority = this.authority;
|
||||
}
|
||||
|
||||
if (this.query) {
|
||||
res.query = this.query;
|
||||
}
|
||||
|
||||
if (this.fragment) {
|
||||
res.fragment = this.fragment;
|
||||
}
|
||||
|
||||
return res;
|
||||
return this;
|
||||
}
|
||||
|
||||
static revive(data: UriComponents | any): URI {
|
||||
@@ -367,8 +334,141 @@ class _URI extends URI {
|
||||
return _asFormatted(this, true);
|
||||
}
|
||||
}
|
||||
|
||||
toJSON(): object {
|
||||
const res = <UriState>{
|
||||
$mid: 1
|
||||
};
|
||||
// cached state
|
||||
if (this._fsPath) {
|
||||
res.fsPath = this._fsPath;
|
||||
}
|
||||
if (this._formatted) {
|
||||
res.external = this._formatted;
|
||||
}
|
||||
// uri components
|
||||
if (this.path) {
|
||||
res.path = this.path;
|
||||
}
|
||||
if (this.scheme) {
|
||||
res.scheme = this.scheme;
|
||||
}
|
||||
if (this.authority) {
|
||||
res.authority = this.authority;
|
||||
}
|
||||
if (this.query) {
|
||||
res.query = this.query;
|
||||
}
|
||||
if (this.fragment) {
|
||||
res.fragment = this.fragment;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
|
||||
const encodeTable: { [ch: number]: string } = {
|
||||
[CharCode.Colon]: '%3A', // gen-delims
|
||||
[CharCode.Slash]: '%2F',
|
||||
[CharCode.QuestionMark]: '%3F',
|
||||
[CharCode.Hash]: '%23',
|
||||
[CharCode.OpenSquareBracket]: '%5B',
|
||||
[CharCode.CloseSquareBracket]: '%5D',
|
||||
[CharCode.AtSign]: '%40',
|
||||
|
||||
[CharCode.ExclamationMark]: '%21', // sub-delims
|
||||
[CharCode.DollarSign]: '%24',
|
||||
[CharCode.Ampersand]: '%26',
|
||||
[CharCode.SingleQuote]: '%27',
|
||||
[CharCode.OpenParen]: '%28',
|
||||
[CharCode.CloseParen]: '%29',
|
||||
[CharCode.Asterisk]: '%2A',
|
||||
[CharCode.Plus]: '%2B',
|
||||
[CharCode.Comma]: '%2C',
|
||||
[CharCode.Semicolon]: '%3B',
|
||||
[CharCode.Equals]: '%3D',
|
||||
|
||||
[CharCode.Space]: '%20',
|
||||
};
|
||||
|
||||
function encodeURIComponentFast(uriComponent: string, allowSlash: boolean): string {
|
||||
let res: string = undefined;
|
||||
let nativeEncodePos = -1;
|
||||
|
||||
for (let pos = 0; pos < uriComponent.length; pos++) {
|
||||
let code = uriComponent.charCodeAt(pos);
|
||||
|
||||
// unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
|
||||
if (
|
||||
(code >= CharCode.a && code <= CharCode.z)
|
||||
|| (code >= CharCode.A && code <= CharCode.Z)
|
||||
|| (code >= CharCode.Digit0 && code <= CharCode.Digit9)
|
||||
|| code === CharCode.Dash
|
||||
|| code === CharCode.Period
|
||||
|| code === CharCode.Underline
|
||||
|| code === CharCode.Tilde
|
||||
|| (allowSlash && code === CharCode.Slash)
|
||||
) {
|
||||
// check if we are delaying native encode
|
||||
if (nativeEncodePos !== -1) {
|
||||
res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
|
||||
nativeEncodePos = -1;
|
||||
}
|
||||
// check if we write into a new string (by default we try to return the param)
|
||||
if (res !== undefined) {
|
||||
res += uriComponent.charAt(pos);
|
||||
}
|
||||
|
||||
} else {
|
||||
// encoding needed, we need to allocate a new string
|
||||
if (res === undefined) {
|
||||
res = uriComponent.substr(0, pos);
|
||||
}
|
||||
|
||||
// check with default table first
|
||||
let escaped = encodeTable[code];
|
||||
if (escaped !== undefined) {
|
||||
|
||||
// check if we are delaying native encode
|
||||
if (nativeEncodePos !== -1) {
|
||||
res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
|
||||
nativeEncodePos = -1;
|
||||
}
|
||||
|
||||
// append escaped variant to result
|
||||
res += escaped;
|
||||
|
||||
} else if (nativeEncodePos === -1) {
|
||||
// use native encode only when needed
|
||||
nativeEncodePos = pos;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nativeEncodePos !== -1) {
|
||||
res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
|
||||
}
|
||||
|
||||
return res !== undefined ? res : uriComponent;
|
||||
}
|
||||
|
||||
function encodeURIComponentMinimal(path: string): string {
|
||||
let res: string = undefined;
|
||||
for (let pos = 0; pos < path.length; pos++) {
|
||||
let code = path.charCodeAt(pos);
|
||||
if (code === CharCode.Hash || code === CharCode.QuestionMark) {
|
||||
if (res === undefined) {
|
||||
res = path.substr(0, pos);
|
||||
}
|
||||
res += encodeTable[code];
|
||||
} else {
|
||||
if (res !== undefined) {
|
||||
res += path[pos];
|
||||
}
|
||||
}
|
||||
}
|
||||
return res !== undefined ? res : path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute `fsPath` for the given uri
|
||||
@@ -377,17 +477,21 @@ class _URI extends URI {
|
||||
function _makeFsPath(uri: URI): string {
|
||||
|
||||
let value: string;
|
||||
if (uri.authority && uri.path && uri.scheme === 'file') {
|
||||
if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
|
||||
// unc path: file://shares/c$/far/boo
|
||||
value = `//${uri.authority}${uri.path}`;
|
||||
} else if (_driveLetterPath.test(uri.path)) {
|
||||
} else if (
|
||||
uri.path.charCodeAt(0) === CharCode.Slash
|
||||
&& (uri.path.charCodeAt(1) >= CharCode.A && uri.path.charCodeAt(1) <= CharCode.Z || uri.path.charCodeAt(1) >= CharCode.a && uri.path.charCodeAt(1) <= CharCode.z)
|
||||
&& uri.path.charCodeAt(2) === CharCode.Colon
|
||||
) {
|
||||
// windows drive letter: file:///c:/far/boo
|
||||
value = uri.path[1].toLowerCase() + uri.path.substr(2);
|
||||
} else {
|
||||
// other path
|
||||
value = uri.path;
|
||||
}
|
||||
if (platform.isWindows) {
|
||||
if (isWindows) {
|
||||
value = value.replace(/\//g, '\\');
|
||||
}
|
||||
return value;
|
||||
@@ -399,71 +503,69 @@ function _makeFsPath(uri: URI): string {
|
||||
function _asFormatted(uri: URI, skipEncoding: boolean): string {
|
||||
|
||||
const encoder = !skipEncoding
|
||||
? encodeURIComponent2
|
||||
: encodeNoop;
|
||||
|
||||
const parts: string[] = [];
|
||||
? encodeURIComponentFast
|
||||
: encodeURIComponentMinimal;
|
||||
|
||||
let res = '';
|
||||
let { scheme, authority, path, query, fragment } = uri;
|
||||
if (scheme) {
|
||||
parts.push(scheme, ':');
|
||||
res += scheme;
|
||||
res += ':';
|
||||
}
|
||||
if (authority || scheme === 'file') {
|
||||
parts.push('//');
|
||||
res += _slash;
|
||||
res += _slash;
|
||||
}
|
||||
if (authority) {
|
||||
let idx = authority.indexOf('@');
|
||||
if (idx !== -1) {
|
||||
// <user>@<auth>
|
||||
const userinfo = authority.substr(0, idx);
|
||||
authority = authority.substr(idx + 1);
|
||||
idx = userinfo.indexOf(':');
|
||||
if (idx === -1) {
|
||||
parts.push(encoder(userinfo));
|
||||
res += encoder(userinfo, false);
|
||||
} else {
|
||||
parts.push(encoder(userinfo.substr(0, idx)), ':', encoder(userinfo.substr(idx + 1)));
|
||||
// <user>:<pass>@<auth>
|
||||
res += encoder(userinfo.substr(0, idx), false);
|
||||
res += ':';
|
||||
res += encoder(userinfo.substr(idx + 1), false);
|
||||
}
|
||||
parts.push('@');
|
||||
res += '@';
|
||||
}
|
||||
authority = authority.toLowerCase();
|
||||
idx = authority.indexOf(':');
|
||||
if (idx === -1) {
|
||||
parts.push(encoder(authority));
|
||||
res += encoder(authority, false);
|
||||
} else {
|
||||
parts.push(encoder(authority.substr(0, idx)), authority.substr(idx));
|
||||
// <auth>:<port>
|
||||
res += encoder(authority.substr(0, idx), false);
|
||||
res += authority.substr(idx);
|
||||
}
|
||||
}
|
||||
if (path) {
|
||||
// lower-case windows drive letters in /C:/fff or C:/fff
|
||||
const m = _upperCaseDrive.exec(path);
|
||||
if (m) {
|
||||
if (m[1]) {
|
||||
path = '/' + m[2].toLowerCase() + path.substr(3); // "/c:".length === 3
|
||||
} else {
|
||||
path = m[2].toLowerCase() + path.substr(2); // // "c:".length === 2
|
||||
if (path.length >= 3 && path.charCodeAt(0) === CharCode.Slash && path.charCodeAt(2) === CharCode.Colon) {
|
||||
let code = path.charCodeAt(1);
|
||||
if (code >= CharCode.A && code <= CharCode.Z) {
|
||||
path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3
|
||||
}
|
||||
} else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) {
|
||||
let code = path.charCodeAt(0);
|
||||
if (code >= CharCode.A && code <= CharCode.Z) {
|
||||
path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3
|
||||
}
|
||||
}
|
||||
|
||||
// encode every segement but not slashes
|
||||
// make sure that # and ? are always encoded
|
||||
// when occurring in paths - otherwise the result
|
||||
// cannot be parsed back again
|
||||
let lastIdx = 0;
|
||||
while (true) {
|
||||
let idx = path.indexOf(_slash, lastIdx);
|
||||
if (idx === -1) {
|
||||
parts.push(encoder(path.substring(lastIdx)));
|
||||
break;
|
||||
}
|
||||
parts.push(encoder(path.substring(lastIdx, idx)), _slash);
|
||||
lastIdx = idx + 1;
|
||||
}
|
||||
// encode the rest of the path
|
||||
res += encoder(path, true);
|
||||
}
|
||||
if (query) {
|
||||
parts.push('?', encoder(query));
|
||||
res += '?';
|
||||
res += encoder(query, false);
|
||||
}
|
||||
if (fragment) {
|
||||
parts.push('#', encoder(fragment));
|
||||
res += '#';
|
||||
res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
|
||||
}
|
||||
|
||||
return parts.join(_empty);
|
||||
return res;
|
||||
}
|
||||
|
||||
18
src/vs/base/common/uriIpc.ts
Normal file
18
src/vs/base/common/uriIpc.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import URI, { UriComponents } from 'vs/base/common/uri';
|
||||
|
||||
export interface IURITransformer {
|
||||
transformIncoming(uri: UriComponents): UriComponents;
|
||||
transformOutgoing(uri: URI): URI;
|
||||
}
|
||||
|
||||
export const DefaultURITransformer: IURITransformer = {
|
||||
transformIncoming: (uri: UriComponents) => uri,
|
||||
transformOutgoing: (uri: URI) => uri,
|
||||
};
|
||||
@@ -28,7 +28,7 @@ class ValueUUID implements UUID {
|
||||
|
||||
class V4UUID extends ValueUUID {
|
||||
|
||||
private static readonly _chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
|
||||
private static readonly _chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
|
||||
|
||||
private static readonly _timeHighBits = ['8', '9', 'a', 'b'];
|
||||
|
||||
|
||||
1
src/vs/base/common/winjs.base.d.ts
vendored
1
src/vs/base/common/winjs.base.d.ts
vendored
@@ -39,7 +39,6 @@ export declare class Promise<T = any, TProgress = any> {
|
||||
|
||||
public static join<T1, T2>(promises: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
|
||||
public static join<T>(promises: (T | PromiseLike<T>)[]): Promise<T[]>;
|
||||
public static join<T>(promises: { [n: string]: T | PromiseLike<T> }): Promise<{ [n: string]: T }>;
|
||||
|
||||
public static any<T>(promises: (T | PromiseLike<T>)[]): Promise<{ key: string; value: Promise<T>; }>;
|
||||
|
||||
|
||||
@@ -1038,6 +1038,12 @@ _winjs("WinJS/Promise/_StateMachine", ["WinJS/Core/_Global","WinJS/Core/_BaseCor
|
||||
/// error function.
|
||||
/// </returns>
|
||||
/// </signature>
|
||||
// BEGIN monaco change
|
||||
if (this.then !== Promise_then) {
|
||||
this.then(onComplete, onError, onProgress);
|
||||
return;
|
||||
}
|
||||
// END monaco change
|
||||
return this._state.then(this, onComplete, onError, onProgress);
|
||||
},
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ class SimpleWorkerProtocol {
|
||||
c: null,
|
||||
e: null
|
||||
};
|
||||
let result = new TPromise<any>((c, e, p) => {
|
||||
let result = new TPromise<any>((c, e) => {
|
||||
reply.c = c;
|
||||
reply.e = e;
|
||||
}, () => {
|
||||
@@ -232,7 +232,7 @@ export class SimpleWorkerClient<T> extends Disposable {
|
||||
loaderConfiguration = (<any>self).requirejs.s.contexts._.config;
|
||||
}
|
||||
|
||||
this._lazyProxy = new TPromise<T>((c, e, p) => {
|
||||
this._lazyProxy = new TPromise<T>((c, e) => {
|
||||
lazyProxyFulfill = c;
|
||||
lazyProxyReject = e;
|
||||
}, () => { /* no cancel */ });
|
||||
@@ -273,7 +273,7 @@ export class SimpleWorkerClient<T> extends Disposable {
|
||||
}
|
||||
|
||||
private _request(method: string, args: any[]): TPromise<any> {
|
||||
return new TPromise<any>((c, e, p) => {
|
||||
return new TPromise<any>((c, e) => {
|
||||
this._onModuleLoaded.then(() => {
|
||||
this._protocol.sendMessage(method, args).then(c, e);
|
||||
}, e);
|
||||
@@ -290,6 +290,7 @@ export class SimpleWorkerClient<T> extends Disposable {
|
||||
|
||||
export interface IRequestHandler {
|
||||
_requestHandlerBrand: any;
|
||||
[prop: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -362,7 +363,7 @@ export class SimpleWorkerServer {
|
||||
|
||||
let cc: ValueCallback;
|
||||
let ee: ErrorCallback;
|
||||
let r = new TPromise<any>((c, e, p) => {
|
||||
let r = new TPromise<any>((c, e) => {
|
||||
cc = c;
|
||||
ee = e;
|
||||
});
|
||||
|
||||
@@ -171,7 +171,7 @@ export class ConfigWatcher<T> implements IConfigWatcher<T>, IDisposable {
|
||||
// Windows: in some cases the filename contains artifacts from the absolute path
|
||||
// see https://github.com/nodejs/node/issues/19170
|
||||
// As such, we have to ensure that the filename basename is used for comparison.
|
||||
if (isWindows && filename !== this.configName) {
|
||||
if (isWindows && filename && filename !== this.configName) {
|
||||
filename = basename(filename);
|
||||
}
|
||||
|
||||
|
||||
64
src/vs/base/node/cpuUsage.sh
Executable file
64
src/vs/base/node/cpuUsage.sh
Executable file
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
|
||||
function get_total_cpu_time() {
|
||||
# Read the first line of /proc/stat and remove the cpu prefix
|
||||
CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
|
||||
|
||||
# Sum all of the values in CPU to get total time
|
||||
for VALUE in "${CPU[@]}"; do
|
||||
let $1=$1+$VALUE
|
||||
done
|
||||
}
|
||||
|
||||
TOTAL_TIME_BEFORE=0
|
||||
get_total_cpu_time TOTAL_TIME_BEFORE
|
||||
|
||||
# Loop over the arguments, which are a list of PIDs
|
||||
# The 13th and 14th words in /proc/<PID>/stat are the user and system time
|
||||
# the process has used, so sum these to get total process run time
|
||||
declare -a PROCESS_BEFORE_TIMES
|
||||
ITER=0
|
||||
for PID in "$@"; do
|
||||
if [ -f /proc/$PID/stat ]
|
||||
then
|
||||
PROCESS_STATS=`cat /proc/$PID/stat`
|
||||
PROCESS_STAT_ARRAY=($PROCESS_STATS)
|
||||
|
||||
let PROCESS_TIME_BEFORE="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}"
|
||||
else
|
||||
let PROCESS_TIME_BEFORE=0
|
||||
fi
|
||||
|
||||
PROCESS_BEFORE_TIMES[$ITER]=$PROCESS_TIME_BEFORE
|
||||
((ITER++))
|
||||
done
|
||||
|
||||
# Wait for a second
|
||||
sleep 1
|
||||
|
||||
TOTAL_TIME_AFTER=0
|
||||
get_total_cpu_time TOTAL_TIME_AFTER
|
||||
|
||||
# Check the user and system time sum of each process again and compute the change
|
||||
# in process time used over total system time
|
||||
ITER=0
|
||||
for PID in "$@"; do
|
||||
if [ -f /proc/$PID/stat ]
|
||||
then
|
||||
PROCESS_STATS=`cat /proc/$PID/stat`
|
||||
PROCESS_STAT_ARRAY=($PROCESS_STATS)
|
||||
|
||||
let PROCESS_TIME_AFTER="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}"
|
||||
else
|
||||
let PROCESS_TIME_AFTER=${PROCESS_BEFORE_TIMES[$ITER]}
|
||||
fi
|
||||
|
||||
PROCESS_TIME_BEFORE=${PROCESS_BEFORE_TIMES[$ITER]}
|
||||
let PROCESS_DELTA=$PROCESS_TIME_AFTER-$PROCESS_TIME_BEFORE
|
||||
let TOTAL_DELTA=$TOTAL_TIME_AFTER-$TOTAL_TIME_BEFORE
|
||||
CPU_USAGE=`echo "100*$PROCESS_DELTA/$TOTAL_DELTA" | bc -l`
|
||||
|
||||
# Parent script reads from stdout, so echo result to be read
|
||||
echo $CPU_USAGE
|
||||
((ITER++))
|
||||
done
|
||||
@@ -11,6 +11,7 @@ import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { isLinux, isMacintosh } from 'vs/base/common/platform';
|
||||
import { exec } from 'child_process';
|
||||
import { Readable, Writable, WritableOptions } from 'stream';
|
||||
import { toWinJsPromise } from 'vs/base/common/async';
|
||||
|
||||
export const UTF8 = 'utf8';
|
||||
export const UTF8_with_bom = 'utf8bom';
|
||||
@@ -88,6 +89,7 @@ export function toDecodeStream(readable: Readable, options: IDecodeStreamOptions
|
||||
resolve({ detected, stream: this._decodeStream });
|
||||
|
||||
}, err => {
|
||||
this.emit('error', err);
|
||||
callback(err);
|
||||
});
|
||||
}
|
||||
@@ -191,25 +193,25 @@ const IGNORE_ENCODINGS = ['ascii', 'utf-8', 'utf-16', 'utf-32'];
|
||||
/**
|
||||
* Guesses the encoding from buffer.
|
||||
*/
|
||||
export async function guessEncodingByBuffer(buffer: NodeBuffer): TPromise<string> {
|
||||
const jschardet = await import('jschardet');
|
||||
export function guessEncodingByBuffer(buffer: NodeBuffer): TPromise<string> {
|
||||
return toWinJsPromise(import('jschardet')).then(jschardet => {
|
||||
jschardet.Constants.MINIMUM_THRESHOLD = MINIMUM_THRESHOLD;
|
||||
|
||||
jschardet.Constants.MINIMUM_THRESHOLD = MINIMUM_THRESHOLD;
|
||||
const guessed = jschardet.detect(buffer);
|
||||
if (!guessed || !guessed.encoding) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const guessed = jschardet.detect(buffer);
|
||||
if (!guessed || !guessed.encoding) {
|
||||
return null;
|
||||
}
|
||||
const enc = guessed.encoding.toLowerCase();
|
||||
|
||||
const enc = guessed.encoding.toLowerCase();
|
||||
// Ignore encodings that cannot guess correctly
|
||||
// (http://chardet.readthedocs.io/en/latest/supported-encodings.html)
|
||||
if (0 <= IGNORE_ENCODINGS.indexOf(enc)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Ignore encodings that cannot guess correctly
|
||||
// (http://chardet.readthedocs.io/en/latest/supported-encodings.html)
|
||||
if (0 <= IGNORE_ENCODINGS.indexOf(enc)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return toIconvLiteEncoding(guessed.encoding);
|
||||
return toIconvLiteEncoding(guessed.encoding);
|
||||
});
|
||||
}
|
||||
|
||||
const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = {
|
||||
|
||||
@@ -5,15 +5,16 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import * as uuid from 'vs/base/common/uuid';
|
||||
import * as strings from 'vs/base/common/strings';
|
||||
import * as platform from 'vs/base/common/platform';
|
||||
import * as flow from 'vs/base/node/flow';
|
||||
import * as fs from 'fs';
|
||||
import * as paths from 'path';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { nfcall } from 'vs/base/common/async';
|
||||
import { normalizeNFC } from 'vs/base/common/normalization';
|
||||
import * as platform from 'vs/base/common/platform';
|
||||
import * as strings from 'vs/base/common/strings';
|
||||
import * as uuid from 'vs/base/common/uuid';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { encode, encodeStream } from 'vs/base/node/encoding';
|
||||
import * as flow from 'vs/base/node/flow';
|
||||
|
||||
const loop = flow.loop;
|
||||
|
||||
@@ -21,7 +22,7 @@ export function readdirSync(path: string): string[] {
|
||||
// Mac: uses NFD unicode form on disk, but we want NFC
|
||||
// See also https://github.com/nodejs/node/issues/2165
|
||||
if (platform.isMacintosh) {
|
||||
return fs.readdirSync(path).map(c => strings.normalizeNFC(c));
|
||||
return fs.readdirSync(path).map(c => normalizeNFC(c));
|
||||
}
|
||||
|
||||
return fs.readdirSync(path);
|
||||
@@ -36,7 +37,7 @@ export function readdir(path: string, callback: (error: Error, files: string[])
|
||||
return callback(error, null);
|
||||
}
|
||||
|
||||
return callback(null, children.map(c => strings.normalizeNFC(c)));
|
||||
return callback(null, children.map(c => normalizeNFC(c)));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -129,17 +130,27 @@ function doCopyFile(source: string, target: string, mode: number, callback: (err
|
||||
}
|
||||
|
||||
export function mkdirp(path: string, mode?: number): TPromise<boolean> {
|
||||
const mkdir = () => nfcall(fs.mkdir, path, mode)
|
||||
.then(null, (err: NodeJS.ErrnoException) => {
|
||||
if (err.code === 'EEXIST') {
|
||||
return nfcall(fs.stat, path)
|
||||
.then((stat: fs.Stats) => stat.isDirectory
|
||||
? null
|
||||
: TPromise.wrapError(new Error(`'${path}' exists and is not a directory.`)));
|
||||
const mkdir = () => {
|
||||
return nfcall(fs.mkdir, path, mode).then(null, (mkdirErr: NodeJS.ErrnoException) => {
|
||||
|
||||
// ENOENT: a parent folder does not exist yet
|
||||
if (mkdirErr.code === 'ENOENT') {
|
||||
return TPromise.wrapError(mkdirErr);
|
||||
}
|
||||
|
||||
return TPromise.wrapError<boolean>(err);
|
||||
// Any other error: check if folder exists and
|
||||
// return normally in that case if its a folder
|
||||
return nfcall(fs.stat, path).then((stat: fs.Stats) => {
|
||||
if (!stat.isDirectory()) {
|
||||
return TPromise.wrapError(new Error(`'${path}' exists and is not a directory.`));
|
||||
}
|
||||
|
||||
return null;
|
||||
}, statErr => {
|
||||
return TPromise.wrapError(mkdirErr); // bubble up original mkdir error
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// stop at root
|
||||
if (path === paths.dirname(path)) {
|
||||
@@ -148,10 +159,14 @@ export function mkdirp(path: string, mode?: number): TPromise<boolean> {
|
||||
|
||||
// recursively mkdir
|
||||
return mkdir().then(null, (err: NodeJS.ErrnoException) => {
|
||||
|
||||
// ENOENT: a parent folder does not exist yet, continue
|
||||
// to create the parent folder and then try again.
|
||||
if (err.code === 'ENOENT') {
|
||||
return mkdirp(paths.dirname(path), mode).then(mkdir);
|
||||
}
|
||||
|
||||
// Any other error
|
||||
return TPromise.wrapError<boolean>(err);
|
||||
});
|
||||
}
|
||||
@@ -619,7 +634,7 @@ function normalizePath(path: string): string {
|
||||
return strings.rtrim(paths.normalize(path), paths.sep);
|
||||
}
|
||||
|
||||
export function watch(path: string, onChange: (type: string, path: string) => void, onError: (error: string) => void): fs.FSWatcher {
|
||||
export function watch(path: string, onChange: (type: string, path?: string) => void, onError: (error: string) => void): fs.FSWatcher {
|
||||
try {
|
||||
const watcher = fs.watch(path);
|
||||
|
||||
@@ -630,7 +645,7 @@ export function watch(path: string, onChange: (type: string, path: string) => vo
|
||||
if (platform.isMacintosh) {
|
||||
// Mac: uses NFD unicode form on disk, but we want NFC
|
||||
// See also https://github.com/nodejs/node/issues/2165
|
||||
file = strings.normalizeNFC(file);
|
||||
file = normalizeNFC(file);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ const writeFilePathQueue: { [path: string]: Queue<void> } = Object.create(null);
|
||||
|
||||
export function writeFile(path: string, data: string, options?: extfs.IWriteFileOptions): TPromise<void>;
|
||||
export function writeFile(path: string, data: NodeBuffer, options?: extfs.IWriteFileOptions): TPromise<void>;
|
||||
export function writeFile(path: string, data: Uint8Array, options?: extfs.IWriteFileOptions): TPromise<void>;
|
||||
export function writeFile(path: string, data: NodeJS.ReadableStream, options?: extfs.IWriteFileOptions): TPromise<void>;
|
||||
export function writeFile(path: string, data: any, options?: extfs.IWriteFileOptions): TPromise<void> {
|
||||
const queueKey = toQueueKey(path);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user