hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 7,
"code_window": [
"\n",
"\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json');\n",
"\t\tthis.disposables.push(configFileWatcher);\n",
"\t\tconfigFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables);\n",
"\t\tconfigFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables);\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher(tsconfigGlob);\n"
],
"file_path": "extensions/typescript/src/utils/tsconfigProvider.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"transposeLetters.label": "Transport letras"
} | i18n/ptb/src/vs/editor/contrib/caretOperations/common/transpose.i18n.json | 0 | https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b | [
0.00017642925377003849,
0.00017642925377003849,
0.00017642925377003849,
0.00017642925377003849,
0
] |
{
"id": 7,
"code_window": [
"\n",
"\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json');\n",
"\t\tthis.disposables.push(configFileWatcher);\n",
"\t\tconfigFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables);\n",
"\t\tconfigFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables);\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst configFileWatcher = vscode.workspace.createFileSystemWatcher(tsconfigGlob);\n"
],
"file_path": "extensions/typescript/src/utils/tsconfigProvider.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"updateNow": "μ§κΈ μ
λ°μ΄νΈ",
"later": "λμ€μ",
"unassigned": "ν λΉλμ§ μμ",
"releaseNotes": "λ¦΄λ¦¬μ€ μ 보",
"showReleaseNotes": "λ¦΄λ¦¬μ€ μ 보 νμ",
"downloadNow": "μ§κΈ λ€μ΄λ‘λ",
"read the release notes": "{0} v{1}μ(λ₯Ό) μμν©λλ€. λ¦΄λ¦¬μ€ μ 보λ₯Ό νμΈνμκ² μ΅λκΉ?",
"licenseChanged": "μ¬μ© μ‘°κ±΄μ΄ λ³κ²½λμμ΅λλ€. μμΈν μ½μ΄λ³΄μΈμ.",
"license": "λΌμ΄μ μ€ μ½κΈ°",
"neveragain": "λ€μ νμ μ ν¨",
"learn more": "μμΈν μ 보",
"thereIsUpdateAvailable": "μ¬μ© κ°λ₯ν μ
λ°μ΄νΈκ° μμ΅λλ€.",
"updateAvailable": "λ€μ μμνλ©΄ {0}μ΄(κ°) μ
λ°μ΄νΈλ©λλ€.",
"noUpdatesAvailable": "νμ¬ μ¬μ© κ°λ₯ν μ
λ°μ΄νΈκ° μμ΅λλ€.",
"commandPalette": "λͺ
λ Ή νλ νΈ...",
"settings": "μ€μ ",
"keyboardShortcuts": "λ°λ‘ κ°κΈ° ν€(&&K)",
"selectTheme.label": "μ ν
λ§",
"themes.selectIconTheme.label": "νμΌ μμ΄μ½ ν
λ§",
"not available": "μ
λ°μ΄νΈλ₯Ό μ¬μ©ν μ μμ",
"checkingForUpdates": "μ
λ°μ΄νΈλ₯Ό νμΈνλ μ€...",
"DownloadUpdate": "μ¬μ© κ°λ₯ν μ
λ°μ΄νΈ λ€μ΄λ‘λ",
"DownloadingUpdate": "μ
λ°μ΄νΈλ₯Ό λ€μ΄λ‘λνλ μ€...",
"InstallingUpdate": "μ
λ°μ΄νΈλ₯Ό μ€μΉνλ μ€...",
"restartToUpdate": "μ
λ°μ΄νΈνκΈ° μν΄ λ€μ μμ...",
"checkForUpdates": "μ
λ°μ΄νΈ νμΈ..."
} | i18n/kor/src/vs/workbench/parts/update/electron-browser/update.i18n.json | 0 | https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b | [
0.00018716299382504076,
0.00017604476306587458,
0.00016960162611212581,
0.00017370721616316587,
0.000006635572390223388
] |
{
"id": 8,
"code_window": [
"\n",
"\tprivate async reloadWorkspaceConfigs(): Promise<this> {\n",
"\t\tthis.tsconfigs.clear();\n",
"\t\tfor (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {\n",
"\t\t\tthis.handleProjectCreate(config);\n",
"\t\t}\n",
"\t\treturn this;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfor (const config of await vscode.workspace.findFiles(tsconfigGlob, '**/node_modules/**')) {\n"
],
"file_path": "extensions/typescript/src/utils/tsconfigProvider.ts",
"type": "replace",
"edit_start_line_idx": 55
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
export interface TSConfig {
path: string;
workspaceFolder?: vscode.WorkspaceFolder;
}
export default class TsConfigProvider extends vscode.Disposable {
private readonly tsconfigs = new Map<string, TSConfig>();
private activated: boolean = false;
private disposables: vscode.Disposable[] = [];
constructor() {
super(() => this.dispose());
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> {
if (!vscode.workspace.workspaceFolders) {
return [];
}
await this.ensureActivated();
return this.tsconfigs.values();
}
private async ensureActivated(): Promise<this> {
if (this.activated) {
return this;
}
this.activated = true;
this.reloadWorkspaceConfigs();
const configFileWatcher = vscode.workspace.createFileSystemWatcher('**/tsconfig*.json');
this.disposables.push(configFileWatcher);
configFileWatcher.onDidCreate(this.handleProjectCreate, this, this.disposables);
configFileWatcher.onDidDelete(this.handleProjectDelete, this, this.disposables);
vscode.workspace.onDidChangeWorkspaceFolders(() => {
this.reloadWorkspaceConfigs();
}, this, this.disposables);
return this;
}
private async reloadWorkspaceConfigs(): Promise<this> {
this.tsconfigs.clear();
for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {
this.handleProjectCreate(config);
}
return this;
}
private handleProjectCreate(config: vscode.Uri) {
const root = vscode.workspace.getWorkspaceFolder(config);
if (root) {
this.tsconfigs.set(config.fsPath, {
path: config.fsPath,
workspaceFolder: root
});
}
}
private handleProjectDelete(e: vscode.Uri) {
this.tsconfigs.delete(e.fsPath);
}
}
| extensions/typescript/src/utils/tsconfigProvider.ts | 1 | https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b | [
0.9990652203559875,
0.3775915801525116,
0.0011916953371837735,
0.008756096474826336,
0.4809779226779938
] |
{
"id": 8,
"code_window": [
"\n",
"\tprivate async reloadWorkspaceConfigs(): Promise<this> {\n",
"\t\tthis.tsconfigs.clear();\n",
"\t\tfor (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {\n",
"\t\t\tthis.handleProjectCreate(config);\n",
"\t\t}\n",
"\t\treturn this;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfor (const config of await vscode.workspace.findFiles(tsconfigGlob, '**/node_modules/**')) {\n"
],
"file_path": "extensions/typescript/src/utils/tsconfigProvider.ts",
"type": "replace",
"edit_start_line_idx": 55
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./minimap';
import { ViewPart, PartFingerprint, PartFingerprints } from 'vs/editor/browser/view/viewPart';
import { ViewContext } from 'vs/editor/common/view/viewContext';
import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext';
import { getOrCreateMinimapCharRenderer } from 'vs/editor/common/view/runtimeMinimapCharRenderer';
import * as dom from 'vs/base/browser/dom';
import { MinimapCharRenderer, MinimapTokensColorTracker, Constants } from 'vs/editor/common/view/minimapCharRenderer';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { CharCode } from 'vs/base/common/charCode';
import { ViewLineData } from 'vs/editor/common/viewModel/viewModel';
import { ColorId } from 'vs/editor/common/modes';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { IDisposable } from 'vs/base/common/lifecycle';
import { RenderedLinesCollection, ILine } from 'vs/editor/browser/view/viewLayer';
import { Range } from 'vs/editor/common/core/range';
import { RGBA } from 'vs/base/common/color';
import * as viewEvents from 'vs/editor/common/view/viewEvents';
import { GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger } from 'vs/base/browser/globalMouseMoveMonitor';
import * as platform from 'vs/base/common/platform';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground, scrollbarShadow } from 'vs/platform/theme/common/colorRegistry';
const enum RenderMinimap {
None = 0,
Small = 1,
Large = 2,
SmallBlocks = 3,
LargeBlocks = 4,
}
function getMinimapLineHeight(renderMinimap: RenderMinimap): number {
if (renderMinimap === RenderMinimap.Large) {
return Constants.x2_CHAR_HEIGHT;
}
if (renderMinimap === RenderMinimap.LargeBlocks) {
return Constants.x2_CHAR_HEIGHT + 2;
}
if (renderMinimap === RenderMinimap.Small) {
return Constants.x1_CHAR_HEIGHT;
}
// RenderMinimap.SmallBlocks
return Constants.x1_CHAR_HEIGHT + 1;
}
function getMinimapCharWidth(renderMinimap: RenderMinimap): number {
if (renderMinimap === RenderMinimap.Large) {
return Constants.x2_CHAR_WIDTH;
}
if (renderMinimap === RenderMinimap.LargeBlocks) {
return Constants.x2_CHAR_WIDTH;
}
if (renderMinimap === RenderMinimap.Small) {
return Constants.x1_CHAR_WIDTH;
}
// RenderMinimap.SmallBlocks
return Constants.x1_CHAR_WIDTH;
}
/**
* The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
*/
const MOUSE_DRAG_RESET_DISTANCE = 140;
class MinimapOptions {
public readonly renderMinimap: RenderMinimap;
public readonly scrollBeyondLastLine: boolean;
public readonly showSlider: 'always' | 'mouseover';
public readonly pixelRatio: number;
public readonly typicalHalfwidthCharacterWidth: number;
public readonly lineHeight: number;
/**
* container dom node width (in CSS px)
*/
public readonly minimapWidth: number;
/**
* container dom node height (in CSS px)
*/
public readonly minimapHeight: number;
/**
* canvas backing store width (in device px)
*/
public readonly canvasInnerWidth: number;
/**
* canvas backing store height (in device px)
*/
public readonly canvasInnerHeight: number;
/**
* canvas width (in CSS px)
*/
public readonly canvasOuterWidth: number;
/**
* canvas height (in CSS px)
*/
public readonly canvasOuterHeight: number;
constructor(configuration: editorCommon.IConfiguration) {
const pixelRatio = configuration.editor.pixelRatio;
const layoutInfo = configuration.editor.layoutInfo;
const viewInfo = configuration.editor.viewInfo;
const fontInfo = configuration.editor.fontInfo;
this.renderMinimap = layoutInfo.renderMinimap | 0;
this.scrollBeyondLastLine = viewInfo.scrollBeyondLastLine;
this.showSlider = viewInfo.minimap.showSlider;
this.pixelRatio = pixelRatio;
this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
this.lineHeight = configuration.editor.lineHeight;
this.minimapWidth = layoutInfo.minimapWidth;
this.minimapHeight = layoutInfo.height;
this.canvasInnerWidth = Math.max(1, Math.floor(pixelRatio * this.minimapWidth));
this.canvasInnerHeight = Math.max(1, Math.floor(pixelRatio * this.minimapHeight));
this.canvasOuterWidth = this.canvasInnerWidth / pixelRatio;
this.canvasOuterHeight = this.canvasInnerHeight / pixelRatio;
}
public equals(other: MinimapOptions): boolean {
return (this.renderMinimap === other.renderMinimap
&& this.scrollBeyondLastLine === other.scrollBeyondLastLine
&& this.showSlider === other.showSlider
&& this.pixelRatio === other.pixelRatio
&& this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth
&& this.lineHeight === other.lineHeight
&& this.minimapWidth === other.minimapWidth
&& this.minimapHeight === other.minimapHeight
&& this.canvasInnerWidth === other.canvasInnerWidth
&& this.canvasInnerHeight === other.canvasInnerHeight
&& this.canvasOuterWidth === other.canvasOuterWidth
&& this.canvasOuterHeight === other.canvasOuterHeight
);
}
}
class MinimapLayout {
/**
* The given editor scrollTop (input).
*/
public readonly scrollTop: number;
/**
* The given editor scrollHeight (input).
*/
public readonly scrollHeight: number;
private readonly _computedSliderRatio: number;
/**
* slider dom node top (in CSS px)
*/
public readonly sliderTop: number;
/**
* slider dom node height (in CSS px)
*/
public readonly sliderHeight: number;
/**
* minimap render start line number.
*/
public readonly startLineNumber: number;
/**
* minimap render end line number.
*/
public readonly endLineNumber: number;
constructor(
scrollTop: number,
scrollHeight: number,
computedSliderRatio: number,
sliderTop: number,
sliderHeight: number,
startLineNumber: number,
endLineNumber: number
) {
this.scrollTop = scrollTop;
this.scrollHeight = scrollHeight;
this._computedSliderRatio = computedSliderRatio;
this.sliderTop = sliderTop;
this.sliderHeight = sliderHeight;
this.startLineNumber = startLineNumber;
this.endLineNumber = endLineNumber;
}
/**
* Compute a desired `scrollPosition` such that the slider moves by `delta`.
*/
public getDesiredScrollTopFromDelta(delta: number): number {
let desiredSliderPosition = this.sliderTop + delta;
return Math.round(desiredSliderPosition / this._computedSliderRatio);
}
public static create(
options: MinimapOptions,
viewportStartLineNumber: number,
viewportEndLineNumber: number,
viewportHeight: number,
viewportContainsWhitespaceGaps: boolean,
lineCount: number,
scrollTop: number,
scrollHeight: number,
previousLayout: MinimapLayout
): MinimapLayout {
const pixelRatio = options.pixelRatio;
const minimapLineHeight = getMinimapLineHeight(options.renderMinimap);
const minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight);
const lineHeight = options.lineHeight;
// The visible line count in a viewport can change due to a number of reasons:
// a) with the same viewport width, different scroll positions can result in partial lines being visible:
// e.g. for a line height of 20, and a viewport height of 600
// * scrollTop = 0 => visible lines are [1, 30]
// * scrollTop = 10 => visible lines are [1, 31] (with lines 1 and 31 partially visible)
// * scrollTop = 20 => visible lines are [2, 31]
// b) whitespace gaps might make their way in the viewport (which results in a decrease in the visible line count)
// c) we could be in the scroll beyond last line case (which also results in a decrease in the visible line count, down to possibly only one line being visible)
// We must first establish a desirable slider height.
let sliderHeight: number;
if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
// case b) from above: there are whitespace gaps in the viewport.
// In this case, the height of the slider directly reflects the visible line count.
const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
} else {
// The slider has a stable height
const expectedViewportLineCount = viewportHeight / lineHeight;
sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
}
let maxMinimapSliderTop: number;
if (options.scrollBeyondLastLine) {
// The minimap slider, when dragged all the way down, will contain the last line at its top
maxMinimapSliderTop = (lineCount - 1) * minimapLineHeight / pixelRatio;
} else {
// The minimap slider, when dragged all the way down, will contain the last line at its bottom
maxMinimapSliderTop = Math.max(0, lineCount * minimapLineHeight / pixelRatio - sliderHeight);
}
maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop);
// The slider can move from 0 to `maxMinimapSliderTop`
// in the same way `scrollTop` can move from 0 to `scrollHeight` - `viewportHeight`.
const computedSliderRatio = (maxMinimapSliderTop) / (scrollHeight - viewportHeight);
const sliderTop = (scrollTop * computedSliderRatio);
if (minimapLinesFitting >= lineCount) {
// All lines fit in the minimap
const startLineNumber = 1;
const endLineNumber = lineCount;
return new MinimapLayout(scrollTop, scrollHeight, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber);
} else {
let startLineNumber = Math.max(1, Math.floor(viewportStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
// Avoid flickering caused by a partial viewport start line
// by being consistent w.r.t. the previous layout decision
if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
if (previousLayout.scrollTop > scrollTop) {
// Scrolling up => never increase `startLineNumber`
startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
}
if (previousLayout.scrollTop < scrollTop) {
// Scrolling down => never decrease `startLineNumber`
startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
}
}
const endLineNumber = Math.min(lineCount, startLineNumber + minimapLinesFitting - 1);
return new MinimapLayout(scrollTop, scrollHeight, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber);
}
}
}
class MinimapLine implements ILine {
public static INVALID = new MinimapLine(-1);
dy: number;
constructor(dy: number) {
this.dy = dy;
}
public onContentChanged(): void {
this.dy = -1;
}
public onTokensChanged(): void {
this.dy = -1;
}
}
class RenderData {
/**
* last rendered layout.
*/
public readonly renderedLayout: MinimapLayout;
private readonly _imageData: ImageData;
private readonly _renderedLines: RenderedLinesCollection<MinimapLine>;
constructor(
renderedLayout: MinimapLayout,
imageData: ImageData,
lines: MinimapLine[]
) {
this.renderedLayout = renderedLayout;
this._imageData = imageData;
this._renderedLines = new RenderedLinesCollection(
() => MinimapLine.INVALID
);
this._renderedLines._set(renderedLayout.startLineNumber, lines);
}
/**
* Check if the current RenderData matches accurately the new desired layout and no painting is needed.
*/
public linesEquals(layout: MinimapLayout): boolean {
if (this.renderedLayout.startLineNumber !== layout.startLineNumber) {
return false;
}
if (this.renderedLayout.endLineNumber !== layout.endLineNumber) {
return false;
}
const tmp = this._renderedLines._get();
const lines = tmp.lines;
for (let i = 0, len = lines.length; i < len; i++) {
if (lines[i].dy === -1) {
// This line is invalid
return false;
}
}
return true;
}
_get(): { imageData: ImageData; rendLineNumberStart: number; lines: MinimapLine[]; } {
let tmp = this._renderedLines._get();
return {
imageData: this._imageData,
rendLineNumberStart: tmp.rendLineNumberStart,
lines: tmp.lines
};
}
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
return this._renderedLines.onLinesChanged(e.fromLineNumber, e.toLineNumber);
}
public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): void {
this._renderedLines.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
}
public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): void {
this._renderedLines.onLinesInserted(e.fromLineNumber, e.toLineNumber);
}
public onTokensChanged(e: viewEvents.ViewTokensChangedEvent): boolean {
return this._renderedLines.onTokensChanged(e.ranges);
}
}
/**
* Some sort of double buffering.
*
* Keeps two buffers around that will be rotated for painting.
* Always gives a buffer that is filled with the background color.
*/
class MinimapBuffers {
private readonly _backgroundFillData: Uint8ClampedArray;
private readonly _buffers: [ImageData, ImageData];
private _lastUsedBuffer: number;
constructor(ctx: CanvasRenderingContext2D, WIDTH: number, HEIGHT: number, background: RGBA) {
this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background);
this._buffers = [
ctx.createImageData(WIDTH, HEIGHT),
ctx.createImageData(WIDTH, HEIGHT)
];
this._lastUsedBuffer = 0;
}
public getBuffer(): ImageData {
// rotate buffers
this._lastUsedBuffer = 1 - this._lastUsedBuffer;
let result = this._buffers[this._lastUsedBuffer];
// fill with background color
result.data.set(this._backgroundFillData);
return result;
}
private static _createBackgroundFillData(WIDTH: number, HEIGHT: number, background: RGBA): Uint8ClampedArray {
const backgroundR = background.r;
const backgroundG = background.g;
const backgroundB = background.b;
let result = new Uint8ClampedArray(WIDTH * HEIGHT * 4);
let offset = 0;
for (let i = 0; i < HEIGHT; i++) {
for (let j = 0; j < WIDTH; j++) {
result[offset] = backgroundR;
result[offset + 1] = backgroundG;
result[offset + 2] = backgroundB;
result[offset + 3] = 255;
offset += 4;
}
}
return result;
}
}
export class Minimap extends ViewPart {
private readonly _domNode: FastDomNode<HTMLElement>;
private readonly _shadow: FastDomNode<HTMLElement>;
private readonly _canvas: FastDomNode<HTMLCanvasElement>;
private readonly _slider: FastDomNode<HTMLElement>;
private readonly _sliderHorizontal: FastDomNode<HTMLElement>;
private readonly _tokensColorTracker: MinimapTokensColorTracker;
private readonly _mouseDownListener: IDisposable;
private readonly _sliderMouseMoveMonitor: GlobalMouseMoveMonitor<IStandardMouseMoveEventData>;
private readonly _sliderMouseDownListener: IDisposable;
private readonly _minimapCharRenderer: MinimapCharRenderer;
private _options: MinimapOptions;
private _lastRenderData: RenderData;
private _buffers: MinimapBuffers;
constructor(context: ViewContext) {
super(context);
this._options = new MinimapOptions(this._context.configuration);
this._lastRenderData = null;
this._buffers = null;
this._domNode = createFastDomNode(document.createElement('div'));
PartFingerprints.write(this._domNode, PartFingerprint.Minimap);
this._domNode.setClassName(this._getMinimapDomNodeClassName());
this._domNode.setPosition('absolute');
this._domNode.setAttribute('role', 'presentation');
this._domNode.setAttribute('aria-hidden', 'true');
this._domNode.setRight(this._context.configuration.editor.layoutInfo.verticalScrollbarWidth);
this._shadow = createFastDomNode(document.createElement('div'));
this._shadow.setClassName('minimap-shadow-hidden');
this._domNode.appendChild(this._shadow);
this._canvas = createFastDomNode(document.createElement('canvas'));
this._canvas.setPosition('absolute');
this._canvas.setLeft(0);
this._domNode.appendChild(this._canvas);
this._slider = createFastDomNode(document.createElement('div'));
this._slider.setPosition('absolute');
this._slider.setClassName('minimap-slider');
this._slider.setLayerHinting(true);
this._domNode.appendChild(this._slider);
this._sliderHorizontal = createFastDomNode(document.createElement('div'));
this._sliderHorizontal.setPosition('absolute');
this._sliderHorizontal.setClassName('minimap-slider-horizontal');
this._slider.appendChild(this._sliderHorizontal);
this._tokensColorTracker = MinimapTokensColorTracker.getInstance();
this._minimapCharRenderer = getOrCreateMinimapCharRenderer();
this._applyLayout();
this._mouseDownListener = dom.addStandardDisposableListener(this._canvas.domNode, 'mousedown', (e) => {
e.preventDefault();
const renderMinimap = this._options.renderMinimap;
if (renderMinimap === RenderMinimap.None) {
return;
}
if (!this._lastRenderData) {
return;
}
const minimapLineHeight = getMinimapLineHeight(renderMinimap);
const internalOffsetY = this._options.pixelRatio * e.browserEvent.offsetY;
const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber;
lineNumber = Math.min(lineNumber, this._context.model.getLineCount());
this._context.privateViewEventBus.emit(new viewEvents.ViewRevealRangeRequestEvent(
new Range(lineNumber, 1, lineNumber, 1),
viewEvents.VerticalRevealType.Center,
false
));
});
this._sliderMouseMoveMonitor = new GlobalMouseMoveMonitor<IStandardMouseMoveEventData>();
this._sliderMouseDownListener = dom.addStandardDisposableListener(this._slider.domNode, 'mousedown', (e) => {
e.preventDefault();
if (e.leftButton && this._lastRenderData) {
const initialMousePosition = e.posy;
const initialMouseOrthogonalPosition = e.posx;
const initialSliderState = this._lastRenderData.renderedLayout;
this._slider.toggleClassName('active', true);
this._sliderMouseMoveMonitor.startMonitoring(
standardMouseMoveMerger,
(mouseMoveData: IStandardMouseMoveEventData) => {
const mouseOrthogonalDelta = Math.abs(mouseMoveData.posx - initialMouseOrthogonalPosition);
if (platform.isWindows && mouseOrthogonalDelta > MOUSE_DRAG_RESET_DISTANCE) {
// The mouse has wondered away from the scrollbar => reset dragging
this._context.viewLayout.setScrollPosition({
scrollTop: initialSliderState.scrollTop
});
return;
}
const mouseDelta = mouseMoveData.posy - initialMousePosition;
this._context.viewLayout.setScrollPosition({
scrollTop: initialSliderState.getDesiredScrollTopFromDelta(mouseDelta)
});
},
() => {
this._slider.toggleClassName('active', false);
}
);
}
});
}
public dispose(): void {
this._mouseDownListener.dispose();
this._sliderMouseMoveMonitor.dispose();
this._sliderMouseDownListener.dispose();
super.dispose();
}
private _getMinimapDomNodeClassName(): string {
if (this._options.showSlider === 'always') {
return 'minimap slider-always';
}
return 'minimap slider-mouseover';
}
public getDomNode(): FastDomNode<HTMLElement> {
return this._domNode;
}
private _applyLayout(): void {
this._domNode.setWidth(this._options.minimapWidth);
this._domNode.setHeight(this._options.minimapHeight);
this._shadow.setHeight(this._options.minimapHeight);
this._canvas.setWidth(this._options.canvasOuterWidth);
this._canvas.setHeight(this._options.canvasOuterHeight);
this._canvas.domNode.width = this._options.canvasInnerWidth;
this._canvas.domNode.height = this._options.canvasInnerHeight;
this._slider.setWidth(this._options.minimapWidth);
}
private _getBuffer(): ImageData {
if (!this._buffers) {
this._buffers = new MinimapBuffers(
this._canvas.domNode.getContext('2d'),
this._options.canvasInnerWidth,
this._options.canvasInnerHeight,
this._tokensColorTracker.getColor(ColorId.DefaultBackground)
);
}
return this._buffers.getBuffer();
}
private _onOptionsMaybeChanged(): boolean {
let opts = new MinimapOptions(this._context.configuration);
if (this._options.equals(opts)) {
return false;
}
this._options = opts;
this._lastRenderData = null;
this._buffers = null;
this._applyLayout();
this._domNode.setClassName(this._getMinimapDomNodeClassName());
return true;
}
// ---- begin view event handlers
public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
return this._onOptionsMaybeChanged();
}
public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
this._lastRenderData = null;
return true;
}
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
if (this._lastRenderData) {
return this._lastRenderData.onLinesChanged(e);
}
return false;
}
public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean {
if (this._lastRenderData) {
this._lastRenderData.onLinesDeleted(e);
}
return true;
}
public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean {
if (this._lastRenderData) {
this._lastRenderData.onLinesInserted(e);
}
return true;
}
public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
return true;
}
public onTokensChanged(e: viewEvents.ViewTokensChangedEvent): boolean {
if (this._lastRenderData) {
return this._lastRenderData.onTokensChanged(e);
}
return false;
}
public onTokensColorsChanged(e: viewEvents.ViewTokensColorsChangedEvent): boolean {
this._lastRenderData = null;
this._buffers = null;
return true;
}
public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
this._lastRenderData = null;
return true;
}
// --- end event handlers
public prepareRender(ctx: RenderingContext): void {
// Nothing to read
}
public render(renderingCtx: RestrictedRenderingContext): void {
const renderMinimap = this._options.renderMinimap;
if (renderMinimap === RenderMinimap.None) {
this._shadow.setClassName('minimap-shadow-hidden');
return;
}
if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
this._shadow.setClassName('minimap-shadow-hidden');
} else {
this._shadow.setClassName('minimap-shadow-visible');
}
const layout = MinimapLayout.create(
this._options,
renderingCtx.visibleRange.startLineNumber,
renderingCtx.visibleRange.endLineNumber,
renderingCtx.viewportHeight,
(renderingCtx.viewportData.whitespaceViewportData.length > 0),
this._context.model.getLineCount(),
renderingCtx.scrollTop,
renderingCtx.scrollHeight,
this._lastRenderData ? this._lastRenderData.renderedLayout : null
);
this._slider.setTop(layout.sliderTop);
this._slider.setHeight(layout.sliderHeight);
// Compute horizontal slider coordinates
const scrollLeftChars = renderingCtx.scrollLeft / this._options.typicalHalfwidthCharacterWidth;
const horizontalSliderLeft = Math.min(this._options.minimapWidth, Math.round(scrollLeftChars * getMinimapCharWidth(this._options.renderMinimap) / this._options.pixelRatio));
this._sliderHorizontal.setLeft(horizontalSliderLeft);
this._sliderHorizontal.setWidth(this._options.minimapWidth - horizontalSliderLeft);
this._sliderHorizontal.setTop(0);
this._sliderHorizontal.setHeight(layout.sliderHeight);
this._lastRenderData = this.renderLines(layout);
}
private renderLines(layout: MinimapLayout): RenderData {
const renderMinimap = this._options.renderMinimap;
const startLineNumber = layout.startLineNumber;
const endLineNumber = layout.endLineNumber;
const minimapLineHeight = getMinimapLineHeight(renderMinimap);
// Check if nothing changed w.r.t. lines from last frame
if (this._lastRenderData && this._lastRenderData.linesEquals(layout)) {
const _lastData = this._lastRenderData._get();
// Nice!! Nothing changed from last frame
return new RenderData(layout, _lastData.imageData, _lastData.lines);
}
// Oh well!! We need to repaint some lines...
const imageData = this._getBuffer();
// Render untouched lines by using last rendered data.
let needed = Minimap._renderUntouchedLines(
imageData,
startLineNumber,
endLineNumber,
minimapLineHeight,
this._lastRenderData
);
// Fetch rendering info from view model for rest of lines that need rendering.
const lineInfo = this._context.model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
const tabSize = lineInfo.tabSize;
const background = this._tokensColorTracker.getColor(ColorId.DefaultBackground);
const useLighterFont = this._tokensColorTracker.backgroundIsLight();
// Render the rest of lines
let dy = 0;
let renderedLines: MinimapLine[] = [];
for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
if (needed[lineIndex]) {
Minimap._renderLine(
imageData,
background,
useLighterFont,
renderMinimap,
this._tokensColorTracker,
this._minimapCharRenderer,
dy,
tabSize,
lineInfo.data[lineIndex]
);
}
renderedLines[lineIndex] = new MinimapLine(dy);
dy += minimapLineHeight;
}
// Finally, paint to the canvas
const ctx = this._canvas.domNode.getContext('2d');
ctx.putImageData(imageData, 0, 0);
// Save rendered data for reuse on next frame if possible
return new RenderData(
layout,
imageData,
renderedLines
);
}
private static _renderUntouchedLines(
target: ImageData,
startLineNumber: number,
endLineNumber: number,
minimapLineHeight: number,
lastRenderData: RenderData,
): boolean[] {
let needed: boolean[] = [];
if (!lastRenderData) {
for (let i = 0, len = endLineNumber - startLineNumber + 1; i < len; i++) {
needed[i] = true;
}
return needed;
}
const _lastData = lastRenderData._get();
const lastTargetData = _lastData.imageData.data;
const lastStartLineNumber = _lastData.rendLineNumberStart;
const lastLines = _lastData.lines;
const lastLinesLength = lastLines.length;
const WIDTH = target.width;
const targetData = target.data;
let copySourceStart = -1;
let copySourceEnd = -1;
let copyDestStart = -1;
let copyDestEnd = -1;
let dest_dy = 0;
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
const lineIndex = lineNumber - startLineNumber;
const lastLineIndex = lineNumber - lastStartLineNumber;
const source_dy = (lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1);
if (source_dy === -1) {
needed[lineIndex] = true;
dest_dy += minimapLineHeight;
continue;
}
let sourceStart = source_dy * WIDTH * 4;
let sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4;
let destStart = dest_dy * WIDTH * 4;
let destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4;
if (copySourceEnd === sourceStart && copyDestEnd === destStart) {
// contiguous zone => extend copy request
copySourceEnd = sourceEnd;
copyDestEnd = destEnd;
} else {
if (copySourceStart !== -1) {
// flush existing copy request
targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
}
copySourceStart = sourceStart;
copySourceEnd = sourceEnd;
copyDestStart = destStart;
copyDestEnd = destEnd;
}
needed[lineIndex] = false;
dest_dy += minimapLineHeight;
}
if (copySourceStart !== -1) {
// flush existing copy request
targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
}
return needed;
}
private static _renderLine(
target: ImageData,
backgroundColor: RGBA,
useLighterFont: boolean,
renderMinimap: RenderMinimap,
colorTracker: MinimapTokensColorTracker,
minimapCharRenderer: MinimapCharRenderer,
dy: number,
tabSize: number,
lineData: ViewLineData
): void {
const content = lineData.content;
const tokens = lineData.tokens;
const charWidth = getMinimapCharWidth(renderMinimap);
const maxDx = target.width - charWidth;
let dx = 0;
let charIndex = 0;
let tabsCharDelta = 0;
for (let tokenIndex = 0, tokensLen = tokens.length; tokenIndex < tokensLen; tokenIndex++) {
const token = tokens[tokenIndex];
const tokenEndIndex = token.endIndex;
const tokenColorId = token.getForeground();
const tokenColor = colorTracker.getColor(tokenColorId);
for (; charIndex < tokenEndIndex; charIndex++) {
if (dx > maxDx) {
// hit edge of minimap
return;
}
const charCode = content.charCodeAt(charIndex);
if (charCode === CharCode.Tab) {
let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
tabsCharDelta += insertSpacesCount - 1;
// No need to render anything since tab is invisible
dx += insertSpacesCount * charWidth;
} else if (charCode === CharCode.Space) {
// No need to render anything since space is invisible
dx += charWidth;
} else {
if (renderMinimap === RenderMinimap.Large) {
minimapCharRenderer.x2RenderChar(target, dx, dy, charCode, tokenColor, backgroundColor, useLighterFont);
} else if (renderMinimap === RenderMinimap.Small) {
minimapCharRenderer.x1RenderChar(target, dx, dy, charCode, tokenColor, backgroundColor, useLighterFont);
} else if (renderMinimap === RenderMinimap.LargeBlocks) {
minimapCharRenderer.x2BlockRenderChar(target, dx, dy, tokenColor, backgroundColor, useLighterFont);
} else {
// RenderMinimap.SmallBlocks
minimapCharRenderer.x1BlockRenderChar(target, dx, dy, tokenColor, backgroundColor, useLighterFont);
}
dx += charWidth;
}
}
}
}
}
registerThemingParticipant((theme, collector) => {
const sliderBackground = theme.getColor(scrollbarSliderBackground);
if (sliderBackground) {
const halfSliderBackground = sliderBackground.transparent(0.5);
collector.addRule(`.monaco-editor .minimap-slider, .monaco-editor .minimap-slider .minimap-slider-horizontal { background: ${halfSliderBackground}; }`);
}
const sliderHoverBackground = theme.getColor(scrollbarSliderHoverBackground);
if (sliderHoverBackground) {
const halfSliderHoverBackground = sliderHoverBackground.transparent(0.5);
collector.addRule(`.monaco-editor .minimap-slider:hover, .monaco-editor .minimap-slider:hover .minimap-slider-horizontal { background: ${halfSliderHoverBackground}; }`);
}
const sliderActiveBackground = theme.getColor(scrollbarSliderActiveBackground);
if (sliderActiveBackground) {
const halfSliderActiveBackground = sliderActiveBackground.transparent(0.5);
collector.addRule(`.monaco-editor .minimap-slider.active, .monaco-editor .minimap-slider.active .minimap-slider-horizontal { background: ${halfSliderActiveBackground}; }`);
}
const shadow = theme.getColor(scrollbarShadow);
if (shadow) {
collector.addRule(`.monaco-editor .minimap-shadow-visible { box-shadow: ${shadow} -6px 0 6px -6px inset; }`);
}
}); | src/vs/editor/browser/viewParts/minimap/minimap.ts | 0 | https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b | [
0.00017858929641079158,
0.00017386766558047384,
0.00016088125994428992,
0.00017465987184550613,
0.000003300348225820926
] |
{
"id": 8,
"code_window": [
"\n",
"\tprivate async reloadWorkspaceConfigs(): Promise<this> {\n",
"\t\tthis.tsconfigs.clear();\n",
"\t\tfor (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {\n",
"\t\t\tthis.handleProjectCreate(config);\n",
"\t\t}\n",
"\t\treturn this;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfor (const config of await vscode.workspace.findFiles(tsconfigGlob, '**/node_modules/**')) {\n"
],
"file_path": "extensions/typescript/src/utils/tsconfigProvider.ts",
"type": "replace",
"edit_start_line_idx": 55
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"collapse": "Comprimi tutto"
} | i18n/ita/src/vs/workbench/browser/viewlet.i18n.json | 0 | https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b | [
0.0001764640910550952,
0.0001764640910550952,
0.0001764640910550952,
0.0001764640910550952,
0
] |
{
"id": 8,
"code_window": [
"\n",
"\tprivate async reloadWorkspaceConfigs(): Promise<this> {\n",
"\t\tthis.tsconfigs.clear();\n",
"\t\tfor (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {\n",
"\t\t\tthis.handleProjectCreate(config);\n",
"\t\t}\n",
"\t\treturn this;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tfor (const config of await vscode.workspace.findFiles(tsconfigGlob, '**/node_modules/**')) {\n"
],
"file_path": "extensions/typescript/src/utils/tsconfigProvider.ts",
"type": "replace",
"edit_start_line_idx": 55
} | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 260 260" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:1.41421;">
<g transform="matrix(1,0,0,1,-589,-1078)">
<g transform="matrix(1,0,0,1,0,999)">
<g opacity="0.1">
<g transform="matrix(1.06122,0,0,1.03704,-43.4898,-1044.78)">
<path d="M841,1317L596,1317L596,1101L841,1101L841,1317ZM601.654,1106.79L601.654,1311.21L835.346,1311.21L835.346,1106.79L601.654,1106.79Z"/>
</g>
<g transform="matrix(1,0,0,1,1,-999)">
<rect x="665" y="1100" width="18" height="216"/>
</g>
<g transform="matrix(1,0,0,1,0,-1000)">
<rect x="701" y="1121" width="70" height="18"/>
</g>
<g transform="matrix(1,0,0,1,0,-860)">
<rect x="701" y="1121" width="70" height="18"/>
</g>
<g transform="matrix(1.25714,0,0,1,-162.757,-965)">
<rect x="701" y="1121" width="70" height="18"/>
</g>
<g transform="matrix(1.25714,0,0,1,-162.757,-930)">
<rect x="701" y="1121" width="70" height="18"/>
</g>
<g transform="matrix(1.25714,0,0,1,-162.757,-895)">
<rect x="701" y="1121" width="70" height="18"/>
</g>
</g>
</g>
</g>
</svg>
| resources/letterpress.svg | 0 | https://github.com/microsoft/vscode/commit/20519a8fe1fe565cd3a7618089beba6d66266b5b | [
0.00017825141549110413,
0.00017678277799859643,
0.00017377562471665442,
0.0001775520358933136,
0.000001785094355000183
] |
{
"id": 0,
"code_window": [
"\tlanguageId: string;\n",
"\tnoThrow: boolean;\n",
"\tignoreCase: boolean;\n",
"\tusesEmbedded: boolean;\n",
"\tdefaultToken: string;\n",
"\tstateNames: { [stateName: string]: any; };\n",
"\t[attr: string]: any;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.9954113364219666,
0.05561935529112816,
0.00016542657976970077,
0.00017286595539189875,
0.225341334939003
] |
{
"id": 0,
"code_window": [
"\tlanguageId: string;\n",
"\tnoThrow: boolean;\n",
"\tignoreCase: boolean;\n",
"\tusesEmbedded: boolean;\n",
"\tdefaultToken: string;\n",
"\tstateNames: { [stateName: string]: any; };\n",
"\t[attr: string]: any;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ExtensionRecommendations, ExtensionRecommendation } from 'vs/workbench/contrib/extensions/browser/extensionRecommendations';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IProductService } from 'vs/platform/product/common/productService';
import { ExtensionRecommendationReason } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IStorageKeysSyncRegistryService } from 'vs/platform/userDataSync/common/storageKeys';
export class KeymapRecommendations extends ExtensionRecommendations {
private _recommendations: ExtensionRecommendation[] = [];
get recommendations(): ReadonlyArray<ExtensionRecommendation> { return this._recommendations; }
constructor(
isExtensionAllowedToBeRecommended: (extensionId: string) => boolean,
@IProductService private readonly productService: IProductService,
@IInstantiationService instantiationService: IInstantiationService,
@IConfigurationService configurationService: IConfigurationService,
@INotificationService notificationService: INotificationService,
@ITelemetryService telemetryService: ITelemetryService,
@IStorageService storageService: IStorageService,
@IStorageKeysSyncRegistryService storageKeysSyncRegistryService: IStorageKeysSyncRegistryService,
) {
super(isExtensionAllowedToBeRecommended, instantiationService, configurationService, notificationService, telemetryService, storageService, storageKeysSyncRegistryService);
}
protected async doActivate(): Promise<void> {
if (this.productService.keymapExtensionTips) {
this._recommendations = this.productService.keymapExtensionTips.map(extensionId => (<ExtensionRecommendation>{
extensionId: extensionId.toLowerCase(),
source: 'application',
reason: {
reasonId: ExtensionRecommendationReason.Application,
reasonText: ''
}
}));
}
}
}
| src/vs/workbench/contrib/extensions/browser/keymapRecommendations.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00020695989951491356,
0.0001792377734091133,
0.0001695608807494864,
0.0001730329095153138,
0.000013935067727288697
] |
{
"id": 0,
"code_window": [
"\tlanguageId: string;\n",
"\tnoThrow: boolean;\n",
"\tignoreCase: boolean;\n",
"\tusesEmbedded: boolean;\n",
"\tdefaultToken: string;\n",
"\tstateNames: { [stateName: string]: any; };\n",
"\t[attr: string]: any;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 26
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "mmims/language-batchfile",
"repositoryUrl": "https://github.com/mmims/language-batchfile",
"commitHash": "95ea8c699f7a8296b15767069868532d52631c46"
}
},
"license": "MIT",
"version": "0.7.5"
}
],
"version": 1
} | extensions/bat/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017351981659885496,
0.00017128810577560216,
0.00016905639495234936,
0.00017128810577560216,
0.000002231710823252797
] |
{
"id": 0,
"code_window": [
"\tlanguageId: string;\n",
"\tnoThrow: boolean;\n",
"\tignoreCase: boolean;\n",
"\tusesEmbedded: boolean;\n",
"\tdefaultToken: string;\n",
"\tstateNames: { [stateName: string]: any; };\n",
"\t[attr: string]: any;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable, IReference } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { ITextModel, ITextSnapshot } from 'vs/editor/common/model';
import { IEditorModel } from 'vs/platform/editor/common/editor';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const ITextModelService = createDecorator<ITextModelService>('textModelService');
export interface ITextModelService {
_serviceBrand: undefined;
/**
* Provided a resource URI, it will return a model reference
* which should be disposed once not needed anymore.
*/
createModelReference(resource: URI): Promise<IReference<IResolvedTextEditorModel>>;
/**
* Registers a specific `scheme` content provider.
*/
registerTextModelContentProvider(scheme: string, provider: ITextModelContentProvider): IDisposable;
/**
* Check if the given resource can be resolved to a text model.
*/
canHandleResource(resource: URI): boolean;
}
export interface ITextModelContentProvider {
/**
* Given a resource, return the content of the resource as `ITextModel`.
*/
provideTextContent(resource: URI): Promise<ITextModel | null> | null;
}
export interface ITextEditorModel extends IEditorModel {
/**
* Provides access to the underlying `ITextModel`.
*/
readonly textEditorModel: ITextModel | null;
/**
* Creates a snapshot of the model's contents.
*/
createSnapshot(this: IResolvedTextEditorModel): ITextSnapshot;
createSnapshot(this: ITextEditorModel): ITextSnapshot | null;
/**
* Signals if this model is readonly or not.
*/
isReadonly(): boolean;
/**
* Figure out if this model is resolved or not.
*/
isResolved(): this is IResolvedTextEditorModel;
/**
* The mode id of the text model if known.
*/
getMode(): string | undefined;
}
export interface IResolvedTextEditorModel extends ITextEditorModel {
/**
* Same as ITextEditorModel#textEditorModel, but never null.
*/
readonly textEditorModel: ITextModel;
}
| src/vs/editor/common/services/resolverService.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00028902472695335746,
0.00018599137547425926,
0.00016622190014459193,
0.00017131067579612136,
0.000039210055547300726
] |
{
"id": 1,
"code_window": [
"export interface ILexer extends ILexerMin {\n",
"\tmaxStack: number;\n",
"\tstart: string | null;\n",
"\tignoreCase: boolean;\n",
"\ttokenPostfix: string;\n",
"\n",
"\ttokenizer: { [stateName: string]: IRule[]; };\n",
"\tbrackets: IBracket[];\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 36
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.9987592697143555,
0.15582360327243805,
0.00016474341100547463,
0.00018288943101651967,
0.3526449501514435
] |
{
"id": 1,
"code_window": [
"export interface ILexer extends ILexerMin {\n",
"\tmaxStack: number;\n",
"\tstart: string | null;\n",
"\tignoreCase: boolean;\n",
"\ttokenPostfix: string;\n",
"\n",
"\ttokenizer: { [stateName: string]: IRule[]; };\n",
"\tbrackets: IBracket[];\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 36
} | {
"iconDefinitions": {
"_root_folder_dark": {
"iconPath": "./images/root-folder-dark.svg"
},
"_root_folder_open_dark": {
"iconPath": "./images/root-folder-open-dark.svg"
},
"_folder_dark": {
"iconPath": "./images/folder-dark.svg"
},
"_folder_open_dark": {
"iconPath": "./images/folder-open-dark.svg"
},
"_file_dark": {
"iconPath": "./images/document-dark.svg"
},
"_root_folder": {
"iconPath": "./images/root-folder-light.svg"
},
"_root_folder_open": {
"iconPath": "./images/root-folder-open-light.svg"
},
"_folder_light": {
"iconPath": "./images/folder-light.svg"
},
"_folder_open_light": {
"iconPath": "./images/folder-open-light.svg"
},
"_file_light": {
"iconPath": "./images/document-light.svg"
}
},
"folderExpanded": "_folder_open_dark",
"folder": "_folder_dark",
"file": "_file_dark",
"rootFolderExpanded": "_root_folder_open_dark",
"rootFolder": "_root_folder_dark",
"fileExtensions": {
// icons by file extension
},
"fileNames": {
// icons by file name
},
"languageIds": {
// icons by language id
},
"light": {
"folderExpanded": "_folder_open_light",
"folder": "_folder_light",
"rootFolderExpanded": "_root_folder_open",
"rootFolder": "_root_folder",
"file": "_file_light",
"fileExtensions": {
// icons by file extension
},
"fileNames": {
// icons by file name
},
"languageIds": {
// icons by language id
}
},
"highContrast": {
// overrides for high contrast
}
} | extensions/theme-defaults/fileicons/vs_minimal-icon-theme.json | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017543432477395982,
0.00017431039304938167,
0.00017279943858738989,
0.00017426545673515648,
7.458391451109492e-7
] |
{
"id": 1,
"code_window": [
"export interface ILexer extends ILexerMin {\n",
"\tmaxStack: number;\n",
"\tstart: string | null;\n",
"\tignoreCase: boolean;\n",
"\ttokenPostfix: string;\n",
"\n",
"\ttokenizer: { [stateName: string]: IRule[]; };\n",
"\tbrackets: IBracket[];\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 36
} | [
{
"c": "#",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown punctuation.definition.heading.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": " ",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": "h",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown entity.name.section.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": "<",
"t": "text.html.markdown meta.tag.structure.pre.start.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "pre",
"t": "text.html.markdown meta.tag.structure.pre.start.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.html.markdown meta.tag.structure.pre.start.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "<",
"t": "text.html.markdown meta.tag.inline.code.start.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "code",
"t": "text.html.markdown meta.tag.inline.code.start.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.html.markdown meta.tag.inline.code.start.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "# a",
"t": "text.html.markdown",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "</",
"t": "text.html.markdown meta.tag.inline.code.end.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "code",
"t": "text.html.markdown meta.tag.inline.code.end.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.html.markdown meta.tag.inline.code.end.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "</",
"t": "text.html.markdown meta.tag.structure.pre.end.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "pre",
"t": "text.html.markdown meta.tag.structure.pre.end.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.html.markdown meta.tag.structure.pre.end.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "#",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown punctuation.definition.heading.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": " ",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": "h",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown entity.name.section.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": "<",
"t": "text.html.markdown meta.tag.structure.pre.start.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "pre",
"t": "text.html.markdown meta.tag.structure.pre.start.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.html.markdown meta.tag.structure.pre.start.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "# a",
"t": "text.html.markdown",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "a",
"t": "text.html.markdown",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "</",
"t": "text.html.markdown meta.tag.structure.pre.end.html punctuation.definition.tag.begin.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "pre",
"t": "text.html.markdown meta.tag.structure.pre.end.html entity.name.tag.html",
"r": {
"dark_plus": "entity.name.tag: #569CD6",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag: #569CD6",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag: #569CD6"
}
},
{
"c": ">",
"t": "text.html.markdown meta.tag.structure.pre.end.html punctuation.definition.tag.end.html",
"r": {
"dark_plus": "punctuation.definition.tag: #808080",
"light_plus": "punctuation.definition.tag: #800000",
"dark_vs": "punctuation.definition.tag: #808080",
"light_vs": "punctuation.definition.tag: #800000",
"hc_black": "punctuation.definition.tag: #808080"
}
},
{
"c": "#",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown punctuation.definition.heading.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": " ",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
},
{
"c": "h",
"t": "text.html.markdown markup.heading.markdown heading.1.markdown entity.name.section.markdown",
"r": {
"dark_plus": "markup.heading: #569CD6",
"light_plus": "markup.heading: #800000",
"dark_vs": "markup.heading: #569CD6",
"light_vs": "markup.heading: #800000",
"hc_black": "markup.heading: #6796E6"
}
}
] | extensions/markdown-basics/test/colorize-results/test-33886_md.json | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.0001797914446797222,
0.0001751274394337088,
0.0001724500034470111,
0.0001751470990711823,
0.0000016060772622950026
] |
{
"id": 1,
"code_window": [
"export interface ILexer extends ILexerMin {\n",
"\tmaxStack: number;\n",
"\tstart: string | null;\n",
"\tignoreCase: boolean;\n",
"\ttokenPostfix: string;\n",
"\n",
"\ttokenizer: { [stateName: string]: IRule[]; };\n",
"\tbrackets: IBracket[];\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tunicode: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCommon.ts",
"type": "add",
"edit_start_line_idx": 36
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as words from '../utils/strings';
suite('HTML Words', () => {
let wordRegex = /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g;
function assertWord(value: string, expected: string): void {
let offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
let actualRange = words.getWordAtText(value, offset, wordRegex);
assert(actualRange.start <= offset);
assert(actualRange.start + actualRange.length >= offset);
assert.equal(value.substr(actualRange.start, actualRange.length), expected);
}
test('Basic', function (): any {
assertWord('|var x1 = new F<A>(a, b);', 'var');
assertWord('v|ar x1 = new F<A>(a, b);', 'var');
assertWord('var| x1 = new F<A>(a, b);', 'var');
assertWord('var |x1 = new F<A>(a, b);', 'x1');
assertWord('var x1| = new F<A>(a, b);', 'x1');
assertWord('var x1 = new |F<A>(a, b);', 'F');
assertWord('var x1 = new F<|A>(a, b);', 'A');
assertWord('var x1 = new F<A>(|a, b);', 'a');
assertWord('var x1 = new F<A>(a, b|);', 'b');
assertWord('var x1 = new F<A>(a, b)|;', '');
assertWord('var x1 = new F<A>(a, b)|;|', '');
assertWord('var x1 = | new F<A>(a, b)|;|', '');
});
test('Multiline', function (): any {
assertWord('console.log("hello");\n|var x1 = new F<A>(a, b);', 'var');
assertWord('console.log("hello");\n|\nvar x1 = new F<A>(a, b);', '');
assertWord('console.log("hello");\n\r |var x1 = new F<A>(a, b);', 'var');
});
}); | extensions/html-language-features/server/src/test/words.test.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017843779642134905,
0.0001755821576807648,
0.0001728894276311621,
0.00017540740373078734,
0.0000023055267774907406
] |
{
"id": 2,
"code_window": [
"// Lexer helpers\n",
"\n",
"/**\n",
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.\n",
" * Also replaces @\\w+ or sequences with the content of the specified attribute\n",
" */\n",
"function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set, and the 'u' flag if 'unicode' is set.\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.9989814162254333,
0.12133587151765823,
0.00016636017244309187,
0.001316966488957405,
0.29906049370765686
] |
{
"id": 2,
"code_window": [
"// Lexer helpers\n",
"\n",
"/**\n",
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.\n",
" * Also replaces @\\w+ or sequences with the content of the specified attribute\n",
" */\n",
"function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set, and the 'u' flag if 'unicode' is set.\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/repl';
import { URI as uri } from 'vs/base/common/uri';
import { IAction, IActionViewItem, Action } from 'vs/base/common/actions';
import * as dom from 'vs/base/browser/dom';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { CancellationToken } from 'vs/base/common/cancellation';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { SuggestController } from 'vs/editor/contrib/suggest/suggestController';
import { ITextModel } from 'vs/editor/common/model';
import { Range } from 'vs/editor/common/core/range';
import { Position } from 'vs/editor/common/core/position';
import { registerEditorAction, ServicesAccessor, EditorAction } from 'vs/editor/browser/editorExtensions';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { memoize } from 'vs/base/common/decorators';
import { dispose, IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { IDebugService, DEBUG_SCHEME, CONTEXT_IN_DEBUG_REPL, IDebugSession, State, IReplElement, IDebugConfiguration, REPL_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug';
import { HistoryNavigator } from 'vs/base/common/history';
import { IHistoryNavigationWidget } from 'vs/base/browser/history';
import { createAndBindHistoryNavigationWidgetScopedContextKeyService } from 'vs/platform/browser/contextScopedHistoryWidget';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { getSimpleEditorOptions, getSimpleCodeEditorWidgetOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IDecorationOptions } from 'vs/editor/common/editorCommon';
import { transparent, editorForeground } from 'vs/platform/theme/common/colorRegistry';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { FocusSessionActionViewItem } from 'vs/workbench/contrib/debug/browser/debugActionViewItems';
import { CompletionContext, CompletionList, CompletionProviderRegistry, CompletionItem, completionKindFromString, CompletionItemKind, CompletionItemInsertTextRule } from 'vs/editor/common/modes';
import { first } from 'vs/base/common/arrays';
import { ITreeNode, ITreeContextMenuEvent, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { removeAnsiEscapeCodes } from 'vs/base/common/strings';
import { WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfigurationService';
import { RunOnceScheduler } from 'vs/base/common/async';
import { FuzzyScore } from 'vs/base/common/filters';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ReplDelegate, ReplVariablesRenderer, ReplSimpleElementsRenderer, ReplEvaluationInputsRenderer, ReplEvaluationResultsRenderer, ReplRawObjectsRenderer, ReplDataSource, ReplAccessibilityProvider, ReplGroupRenderer } from 'vs/workbench/contrib/debug/browser/replViewer';
import { localize } from 'vs/nls';
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IViewsService, IViewDescriptorService } from 'vs/workbench/common/views';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { ReplGroup } from 'vs/workbench/contrib/debug/common/replModel';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { EDITOR_FONT_DEFAULTS, EditorOption } from 'vs/editor/common/config/editorOptions';
import { MOUSE_CURSOR_TEXT_CSS_CLASS_NAME } from 'vs/base/browser/ui/mouseCursor/mouseCursor';
const $ = dom.$;
const HISTORY_STORAGE_KEY = 'debug.repl.history';
const DECORATION_KEY = 'replinputdecoration';
function revealLastElement(tree: WorkbenchAsyncDataTree<any, any, any>) {
tree.scrollTop = tree.scrollHeight - tree.renderHeight;
}
const sessionsToIgnore = new Set<IDebugSession>();
export class Repl extends ViewPane implements IHistoryNavigationWidget {
_serviceBrand: undefined;
private static readonly REFRESH_DELAY = 100; // delay in ms to refresh the repl for new elements to show
private static readonly URI = uri.parse(`${DEBUG_SCHEME}:replinput`);
private history: HistoryNavigator<string>;
private tree!: WorkbenchAsyncDataTree<IDebugSession, IReplElement, FuzzyScore>;
private replDelegate!: ReplDelegate;
private container!: HTMLElement;
private replInput!: CodeEditorWidget;
private replInputContainer!: HTMLElement;
private dimension!: dom.Dimension;
private replInputLineCount = 1;
private model: ITextModel | undefined;
private historyNavigationEnablement!: IContextKey<boolean>;
private scopedInstantiationService!: IInstantiationService;
private replElementsChangeListener: IDisposable | undefined;
private styleElement: HTMLStyleElement | undefined;
private completionItemProvider: IDisposable | undefined;
private modelChangeListener: IDisposable = Disposable.None;
constructor(
options: IViewPaneOptions,
@IDebugService private readonly debugService: IDebugService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@IThemeService themeService: IThemeService,
@IModelService private readonly modelService: IModelService,
@IContextKeyService contextKeyService: IContextKeyService,
@ICodeEditorService codeEditorService: ICodeEditorService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IContextMenuService contextMenuService: IContextMenuService,
@IConfigurationService configurationService: IConfigurationService,
@ITextResourcePropertiesService private readonly textResourcePropertiesService: ITextResourcePropertiesService,
@IClipboardService private readonly clipboardService: IClipboardService,
@IEditorService private readonly editorService: IEditorService,
@IKeybindingService keybindingService: IKeybindingService,
@IOpenerService openerService: IOpenerService,
@ITelemetryService telemetryService: ITelemetryService,
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.history = new HistoryNavigator(JSON.parse(this.storageService.get(HISTORY_STORAGE_KEY, StorageScope.WORKSPACE, '[]')), 50);
codeEditorService.registerDecorationType(DECORATION_KEY, {});
this.registerListeners();
}
private registerListeners(): void {
this._register(this.debugService.getViewModel().onDidFocusSession(async session => {
if (session) {
sessionsToIgnore.delete(session);
if (this.completionItemProvider) {
this.completionItemProvider.dispose();
}
if (session.capabilities.supportsCompletionsRequest) {
this.completionItemProvider = CompletionProviderRegistry.register({ scheme: DEBUG_SCHEME, pattern: '**/replinput', hasAccessToAllModels: true }, {
triggerCharacters: session.capabilities.completionTriggerCharacters || ['.'],
provideCompletionItems: async (_: ITextModel, position: Position, _context: CompletionContext, token: CancellationToken): Promise<CompletionList> => {
// Disable history navigation because up and down are used to navigate through the suggest widget
this.historyNavigationEnablement.set(false);
const model = this.replInput.getModel();
if (model) {
const word = model.getWordAtPosition(position);
const overwriteBefore = word ? word.word.length : 0;
const text = model.getValue();
const focusedStackFrame = this.debugService.getViewModel().focusedStackFrame;
const frameId = focusedStackFrame ? focusedStackFrame.frameId : undefined;
const response = await session.completions(frameId, text, position, overwriteBefore, token);
const suggestions: CompletionItem[] = [];
const computeRange = (length: number) => Range.fromPositions(position.delta(0, -length), position);
if (response && response.body && response.body.targets) {
response.body.targets.forEach(item => {
if (item && item.label) {
let insertTextRules: CompletionItemInsertTextRule | undefined = undefined;
let insertText = item.text || item.label;
if (typeof item.selectionStart === 'number') {
// If a debug completion item sets a selection we need to use snippets to make sure the selection is selected #90974
insertTextRules = CompletionItemInsertTextRule.InsertAsSnippet;
const selectionLength = typeof item.selectionLength === 'number' ? item.selectionLength : 0;
const placeholder = selectionLength > 0 ? '${1:' + insertText.substr(item.selectionStart, selectionLength) + '}$0' : '$0';
insertText = insertText.substr(0, item.selectionStart) + placeholder + insertText.substr(item.selectionStart + selectionLength);
}
suggestions.push({
label: item.label,
insertText,
kind: completionKindFromString(item.type || 'property'),
filterText: (item.start && item.length) ? text.substr(item.start, item.length).concat(item.label) : undefined,
range: computeRange(item.length || overwriteBefore),
sortText: item.sortText,
insertTextRules
});
}
});
}
if (this.configurationService.getValue<IDebugConfiguration>('debug').console.historySuggestions) {
const history = this.history.getHistory();
history.forEach(h => suggestions.push({
label: h,
insertText: h,
kind: CompletionItemKind.Text,
range: computeRange(h.length),
sortText: 'ZZZ'
}));
}
return { suggestions };
}
return Promise.resolve({ suggestions: [] });
}
});
}
}
await this.selectSession();
}));
this._register(this.debugService.onWillNewSession(async newSession => {
// Need to listen to output events for sessions which are not yet fully initialised
const input = this.tree.getInput();
if (!input || input.state === State.Inactive) {
await this.selectSession(newSession);
}
this.updateActions();
}));
this._register(this.themeService.onDidColorThemeChange(() => {
this.refreshReplElements(false);
if (this.isVisible()) {
this.updateInputDecoration();
}
}));
this._register(this.onDidChangeBodyVisibility(visible => {
if (!visible) {
dispose(this.model);
} else {
this.model = this.modelService.getModel(Repl.URI) || this.modelService.createModel('', null, Repl.URI, true);
this.setMode();
this.replInput.setModel(this.model);
this.updateInputDecoration();
this.refreshReplElements(true);
}
}));
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('debug.console.lineHeight') || e.affectsConfiguration('debug.console.fontSize') || e.affectsConfiguration('debug.console.fontFamily')) {
this.onDidStyleChange();
}
}));
this._register(this.themeService.onDidColorThemeChange(e => {
this.onDidStyleChange();
}));
this._register(this.viewDescriptorService.onDidChangeLocation(e => {
if (e.views.some(v => v.id === this.id)) {
this.onDidStyleChange();
}
}));
this._register(this.editorService.onDidActiveEditorChange(() => {
this.setMode();
}));
}
get isReadonly(): boolean {
// Do not allow to edit inactive sessions
const session = this.tree.getInput();
if (session && session.state !== State.Inactive) {
return false;
}
return true;
}
showPreviousValue(): void {
this.navigateHistory(true);
}
showNextValue(): void {
this.navigateHistory(false);
}
focusRepl(): void {
this.tree.domFocus();
}
private setMode(): void {
if (!this.isVisible()) {
return;
}
const activeEditorControl = this.editorService.activeTextEditorControl;
if (isCodeEditor(activeEditorControl)) {
this.modelChangeListener.dispose();
this.modelChangeListener = activeEditorControl.onDidChangeModelLanguage(() => this.setMode());
if (this.model && activeEditorControl.hasModel()) {
this.model.setMode(activeEditorControl.getModel().getLanguageIdentifier());
}
}
}
private onDidStyleChange(): void {
if (this.styleElement) {
const debugConsole = this.configurationService.getValue<IDebugConfiguration>('debug').console;
const fontSize = debugConsole.fontSize;
const fontFamily = debugConsole.fontFamily === 'default' ? 'var(--monaco-monospace-font)' : debugConsole.fontFamily;
const lineHeight = debugConsole.lineHeight ? `${debugConsole.lineHeight}px` : '1.4em';
const backgroundColor = this.themeService.getColorTheme().getColor(this.getBackgroundColor());
this.replInput.updateOptions({
fontSize,
lineHeight: debugConsole.lineHeight,
fontFamily: debugConsole.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : debugConsole.fontFamily
});
const replInputLineHeight = this.replInput.getOption(EditorOption.lineHeight);
// Set the font size, font family, line height and align the twistie to be centered, and input theme color
this.styleElement.innerHTML = `
.repl .repl-tree .expression {
font-size: ${fontSize}px;
font-family: ${fontFamily};
}
.repl .repl-tree .expression {
line-height: ${lineHeight};
}
.repl .repl-tree .monaco-tl-twistie {
background-position-y: calc(100% - ${fontSize * 1.4 / 2 - 8}px);
}
.repl .repl-input-wrapper .repl-input-chevron {
line-height: ${replInputLineHeight}px
}
.repl .repl-input-wrapper .monaco-editor .lines-content {
background-color: ${backgroundColor};
}
`;
this.tree.rerender();
if (this.dimension) {
this.layoutBody(this.dimension.height, this.dimension.width);
}
}
}
private navigateHistory(previous: boolean): void {
const historyInput = previous ? this.history.previous() : this.history.next();
if (historyInput) {
this.replInput.setValue(historyInput);
aria.status(historyInput);
// always leave cursor at the end.
this.replInput.setPosition({ lineNumber: 1, column: historyInput.length + 1 });
this.historyNavigationEnablement.set(true);
}
}
async selectSession(session?: IDebugSession): Promise<void> {
const treeInput = this.tree.getInput();
if (!session) {
const focusedSession = this.debugService.getViewModel().focusedSession;
// If there is a focusedSession focus on that one, otherwise just show any other not ignored session
if (focusedSession) {
session = focusedSession;
} else if (!treeInput || sessionsToIgnore.has(treeInput)) {
session = first(this.debugService.getModel().getSessions(true), s => !sessionsToIgnore.has(s)) || undefined;
}
}
if (session) {
if (this.replElementsChangeListener) {
this.replElementsChangeListener.dispose();
}
this.replElementsChangeListener = session.onDidChangeReplElements(() => {
this.refreshReplElements(session!.getReplElements().length === 0);
});
if (this.tree && treeInput !== session) {
await this.tree.setInput(session);
revealLastElement(this.tree);
}
}
this.replInput.updateOptions({ readOnly: this.isReadonly });
this.updateInputDecoration();
}
async clearRepl(): Promise<void> {
const session = this.tree.getInput();
if (session) {
session.removeReplExpressions();
if (session.state === State.Inactive) {
// Ignore inactive sessions which got cleared - so they are not shown any more
sessionsToIgnore.add(session);
await this.selectSession();
this.updateActions();
}
}
this.replInput.focus();
}
acceptReplInput(): void {
const session = this.tree.getInput();
if (session) {
session.addReplExpression(this.debugService.getViewModel().focusedStackFrame, this.replInput.getValue());
revealLastElement(this.tree);
this.history.add(this.replInput.getValue());
this.replInput.setValue('');
const shouldRelayout = this.replInputLineCount > 1;
this.replInputLineCount = 1;
if (shouldRelayout) {
// Trigger a layout to shrink a potential multi line input
this.layoutBody(this.dimension.height, this.dimension.width);
}
}
}
getVisibleContent(): string {
let text = '';
if (this.model) {
const lineDelimiter = this.textResourcePropertiesService.getEOL(this.model.uri);
const traverseAndAppend = (node: ITreeNode<IReplElement, FuzzyScore>) => {
node.children.forEach(child => {
text += child.element.toString().trimRight() + lineDelimiter;
if (!child.collapsed && child.children.length) {
traverseAndAppend(child);
}
});
};
traverseAndAppend(this.tree.getNode());
}
return removeAnsiEscapeCodes(text);
}
protected layoutBody(height: number, width: number): void {
super.layoutBody(height, width);
this.dimension = new dom.Dimension(width, height);
const replInputHeight = Math.min(this.replInput.getContentHeight(), height);
if (this.tree) {
const lastElementVisible = this.tree.scrollTop + this.tree.renderHeight >= this.tree.scrollHeight;
const treeHeight = height - replInputHeight;
this.tree.getHTMLElement().style.height = `${treeHeight}px`;
this.tree.layout(treeHeight, width);
if (lastElementVisible) {
revealLastElement(this.tree);
}
}
this.replInputContainer.style.height = `${replInputHeight}px`;
this.replInput.layout({ width: width - 30, height: replInputHeight });
}
focus(): void {
setTimeout(() => this.replInput.focus(), 0);
}
getActionViewItem(action: IAction): IActionViewItem | undefined {
if (action.id === SelectReplAction.ID) {
return this.instantiationService.createInstance(SelectReplActionViewItem, this.selectReplAction);
}
return undefined;
}
getActions(): IAction[] {
const result: IAction[] = [];
if (this.debugService.getModel().getSessions(true).filter(s => s.hasSeparateRepl() && !sessionsToIgnore.has(s)).length > 1) {
result.push(this.selectReplAction);
}
result.push(this.clearReplAction);
result.forEach(a => this._register(a));
return result;
}
// --- Cached locals
@memoize
private get selectReplAction(): SelectReplAction {
return this.instantiationService.createInstance(SelectReplAction, SelectReplAction.ID, SelectReplAction.LABEL);
}
@memoize
private get clearReplAction(): ClearReplAction {
return this.instantiationService.createInstance(ClearReplAction, ClearReplAction.ID, ClearReplAction.LABEL);
}
@memoize
private get refreshScheduler(): RunOnceScheduler {
const autoExpanded = new Set<string>();
return new RunOnceScheduler(async () => {
if (!this.tree.getInput()) {
return;
}
const lastElementVisible = this.tree.scrollTop + this.tree.renderHeight >= this.tree.scrollHeight;
await this.tree.updateChildren();
const session = this.tree.getInput();
if (session) {
// Automatically expand repl group elements when specified
const autoExpandElements = async (elements: IReplElement[]) => {
for (let element of elements) {
if (element instanceof ReplGroup) {
if (element.autoExpand && !autoExpanded.has(element.getId())) {
autoExpanded.add(element.getId());
await this.tree.expand(element);
}
if (!this.tree.isCollapsed(element)) {
// Repl groups can have children which are repl groups thus we might need to expand those as well
await autoExpandElements(element.getChildren());
}
}
}
};
await autoExpandElements(session.getReplElements());
}
if (lastElementVisible) {
// Only scroll if we were scrolled all the way down before tree refreshed #10486
revealLastElement(this.tree);
}
}, Repl.REFRESH_DELAY);
}
// --- Creation
protected renderBody(parent: HTMLElement): void {
super.renderBody(parent);
this.container = dom.append(parent, $('.repl'));
const treeContainer = dom.append(this.container, $(`.repl-tree.${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`));
this.createReplInput(this.container);
this.replDelegate = new ReplDelegate(this.configurationService);
const wordWrap = this.configurationService.getValue<IDebugConfiguration>('debug').console.wordWrap;
dom.toggleClass(treeContainer, 'word-wrap', wordWrap);
const linkDetector = this.instantiationService.createInstance(LinkDetector);
this.tree = <WorkbenchAsyncDataTree<IDebugSession, IReplElement, FuzzyScore>>this.instantiationService.createInstance(
WorkbenchAsyncDataTree,
'DebugRepl',
treeContainer,
this.replDelegate,
[
this.instantiationService.createInstance(ReplVariablesRenderer, linkDetector),
this.instantiationService.createInstance(ReplSimpleElementsRenderer, linkDetector),
new ReplEvaluationInputsRenderer(),
new ReplGroupRenderer(),
new ReplEvaluationResultsRenderer(linkDetector),
new ReplRawObjectsRenderer(linkDetector),
],
// https://github.com/microsoft/TypeScript/issues/32526
new ReplDataSource() as IAsyncDataSource<IDebugSession, IReplElement>,
{
accessibilityProvider: new ReplAccessibilityProvider(),
identityProvider: { getId: (element: IReplElement) => element.getId() },
mouseSupport: false,
keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: IReplElement) => e },
horizontalScrolling: !wordWrap,
setRowLineHeight: false,
supportDynamicHeights: wordWrap,
overrideStyles: {
listBackground: this.getBackgroundColor()
}
});
this._register(this.tree.onContextMenu(e => this.onContextMenu(e)));
let lastSelectedString: string;
this._register(this.tree.onMouseClick(() => {
const selection = window.getSelection();
if (!selection || selection.type !== 'Range' || lastSelectedString === selection.toString()) {
// only focus the input if the user is not currently selecting.
this.replInput.focus();
}
lastSelectedString = selection ? selection.toString() : '';
}));
// Make sure to select the session if debugging is already active
this.selectSession();
this.styleElement = dom.createStyleSheet(this.container);
this.onDidStyleChange();
}
private createReplInput(container: HTMLElement): void {
this.replInputContainer = dom.append(container, $('.repl-input-wrapper'));
dom.append(this.replInputContainer, $('.repl-input-chevron.codicon.codicon-chevron-right'));
const { scopedContextKeyService, historyNavigationEnablement } = createAndBindHistoryNavigationWidgetScopedContextKeyService(this.contextKeyService, { target: this.replInputContainer, historyNavigator: this });
this.historyNavigationEnablement = historyNavigationEnablement;
this._register(scopedContextKeyService);
CONTEXT_IN_DEBUG_REPL.bindTo(scopedContextKeyService).set(true);
this.scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]));
const options = getSimpleEditorOptions();
options.readOnly = true;
options.ariaLabel = localize('debugConsole', "Debug Console");
this.replInput = this.scopedInstantiationService.createInstance(CodeEditorWidget, this.replInputContainer, options, getSimpleCodeEditorWidgetOptions());
this._register(this.replInput.onDidChangeModelContent(() => {
const model = this.replInput.getModel();
this.historyNavigationEnablement.set(!!model && model.getValue() === '');
const lineCount = model ? Math.min(10, model.getLineCount()) : 1;
if (lineCount !== this.replInputLineCount) {
this.replInputLineCount = lineCount;
this.layoutBody(this.dimension.height, this.dimension.width);
}
}));
// We add the input decoration only when the focus is in the input #61126
this._register(this.replInput.onDidFocusEditorText(() => this.updateInputDecoration()));
this._register(this.replInput.onDidBlurEditorText(() => this.updateInputDecoration()));
this._register(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.FOCUS, () => dom.addClass(this.replInputContainer, 'synthetic-focus')));
this._register(dom.addStandardDisposableListener(this.replInputContainer, dom.EventType.BLUR, () => dom.removeClass(this.replInputContainer, 'synthetic-focus')));
}
private onContextMenu(e: ITreeContextMenuEvent<IReplElement>): void {
const actions: IAction[] = [];
actions.push(new Action('debug.replCopy', localize('copy', "Copy"), undefined, true, async () => {
const nativeSelection = window.getSelection();
if (nativeSelection) {
await this.clipboardService.writeText(nativeSelection.toString());
}
return Promise.resolve();
}));
actions.push(new Action('workbench.debug.action.copyAll', localize('copyAll', "Copy All"), undefined, true, async () => {
await this.clipboardService.writeText(this.getVisibleContent());
return Promise.resolve();
}));
actions.push(new Action('debug.collapseRepl', localize('collapse', "Collapse All"), undefined, true, () => {
this.tree.collapseAll();
this.replInput.focus();
return Promise.resolve();
}));
actions.push(new Separator());
actions.push(this.clearReplAction);
this.contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => actions,
getActionsContext: () => e.element,
onHide: () => dispose(actions)
});
}
// --- Update
private refreshReplElements(noDelay: boolean): void {
if (this.tree && this.isVisible()) {
if (this.refreshScheduler.isScheduled()) {
return;
}
this.refreshScheduler.schedule(noDelay ? 0 : undefined);
}
}
private updateInputDecoration(): void {
if (!this.replInput) {
return;
}
const decorations: IDecorationOptions[] = [];
if (this.isReadonly && this.replInput.hasTextFocus() && !this.replInput.getValue()) {
const transparentForeground = transparent(editorForeground, 0.4)(this.themeService.getColorTheme());
decorations.push({
range: {
startLineNumber: 0,
endLineNumber: 0,
startColumn: 0,
endColumn: 1
},
renderOptions: {
after: {
contentText: localize('startDebugFirst', "Please start a debug session to evaluate expressions"),
color: transparentForeground ? transparentForeground.toString() : undefined
}
}
});
}
this.replInput.setDecorations(DECORATION_KEY, decorations);
}
saveState(): void {
const replHistory = this.history.getHistory();
if (replHistory.length) {
this.storageService.store(HISTORY_STORAGE_KEY, JSON.stringify(replHistory), StorageScope.WORKSPACE);
} else {
this.storageService.remove(HISTORY_STORAGE_KEY, StorageScope.WORKSPACE);
}
super.saveState();
}
dispose(): void {
this.replInput.dispose();
if (this.replElementsChangeListener) {
this.replElementsChangeListener.dispose();
}
this.refreshScheduler.dispose();
this.modelChangeListener.dispose();
super.dispose();
}
}
// Repl actions and commands
class AcceptReplInputAction extends EditorAction {
constructor() {
super({
id: 'repl.action.acceptInput',
label: localize({ key: 'actions.repl.acceptInput', comment: ['Apply input from the debug console input box'] }, "REPL Accept Input"),
alias: 'REPL Accept Input',
precondition: CONTEXT_IN_DEBUG_REPL,
kbOpts: {
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.Enter,
weight: KeybindingWeight.EditorContrib
}
});
}
run(accessor: ServicesAccessor, editor: ICodeEditor): void | Promise<void> {
SuggestController.get(editor).acceptSelectedSuggestion(false, true);
const repl = getReplView(accessor.get(IViewsService));
repl?.acceptReplInput();
}
}
class FilterReplAction extends EditorAction {
constructor() {
super({
id: 'repl.action.filter',
label: localize('repl.action.filter', "REPL Focus Content to Filter"),
alias: 'REPL Filter',
precondition: CONTEXT_IN_DEBUG_REPL,
kbOpts: {
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyMod.CtrlCmd | KeyCode.KEY_F,
weight: KeybindingWeight.EditorContrib
}
});
}
run(accessor: ServicesAccessor, editor: ICodeEditor): void | Promise<void> {
SuggestController.get(editor).acceptSelectedSuggestion(false, true);
const repl = getReplView(accessor.get(IViewsService));
repl?.focusRepl();
}
}
class ReplCopyAllAction extends EditorAction {
constructor() {
super({
id: 'repl.action.copyAll',
label: localize('actions.repl.copyAll', "Debug: Console Copy All"),
alias: 'Debug Console Copy All',
precondition: CONTEXT_IN_DEBUG_REPL,
});
}
run(accessor: ServicesAccessor, editor: ICodeEditor): void | Promise<void> {
const clipboardService = accessor.get(IClipboardService);
const repl = getReplView(accessor.get(IViewsService));
if (repl) {
return clipboardService.writeText(repl.getVisibleContent());
}
}
}
registerEditorAction(AcceptReplInputAction);
registerEditorAction(ReplCopyAllAction);
registerEditorAction(FilterReplAction);
class SelectReplActionViewItem extends FocusSessionActionViewItem {
protected getSessions(): ReadonlyArray<IDebugSession> {
return this.debugService.getModel().getSessions(true).filter(s => s.hasSeparateRepl() && !sessionsToIgnore.has(s));
}
protected mapFocusedSessionToSelected(focusedSession: IDebugSession): IDebugSession {
while (focusedSession.parentSession && !focusedSession.hasSeparateRepl()) {
focusedSession = focusedSession.parentSession;
}
return focusedSession;
}
}
class SelectReplAction extends Action {
static readonly ID = 'workbench.action.debug.selectRepl';
static readonly LABEL = localize('selectRepl', "Select Debug Console");
constructor(id: string, label: string,
@IDebugService private readonly debugService: IDebugService,
@IViewsService private readonly viewsService: IViewsService
) {
super(id, label);
}
async run(session: IDebugSession): Promise<any> {
// If session is already the focused session we need to manualy update the tree since view model will not send a focused change event
if (session && session.state !== State.Inactive && session !== this.debugService.getViewModel().focusedSession) {
await this.debugService.focusStackFrame(undefined, undefined, session, true);
} else {
const repl = getReplView(this.viewsService);
if (repl) {
await repl.selectSession(session);
}
}
}
}
export class ClearReplAction extends Action {
static readonly ID = 'workbench.debug.panel.action.clearReplAction';
static readonly LABEL = localize('clearRepl', "Clear Console");
constructor(id: string, label: string,
@IViewsService private readonly viewsService: IViewsService
) {
super(id, label, 'debug-action codicon-clear-all');
}
async run(): Promise<any> {
const view = await this.viewsService.openView(REPL_VIEW_ID) as Repl;
await view.clearRepl();
aria.status(localize('debugConsoleCleared', "Debug console was cleared"));
}
}
function getReplView(viewsService: IViewsService): Repl | undefined {
return viewsService.getActiveViewWithId(REPL_VIEW_ID) as Repl ?? undefined;
}
| src/vs/workbench/contrib/debug/browser/repl.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00018388379248790443,
0.00017089715402107686,
0.0001651362981647253,
0.00017067932640202343,
0.000003122162070212653
] |
{
"id": 2,
"code_window": [
"// Lexer helpers\n",
"\n",
"/**\n",
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.\n",
" * Also replaces @\\w+ or sequences with the content of the specified attribute\n",
" */\n",
"function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set, and the 'u' flag if 'unicode' is set.\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { EditorModel, EditorInput, SideBySideEditorInput, TEXT_DIFF_EDITOR_ID, BINARY_DIFF_EDITOR_ID } from 'vs/workbench/common/editor';
import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel';
import { DiffEditorModel } from 'vs/workbench/common/editor/diffEditorModel';
import { TextDiffEditorModel } from 'vs/workbench/common/editor/textDiffEditorModel';
import { localize } from 'vs/nls';
/**
* The base editor input for the diff editor. It is made up of two editor inputs, the original version
* and the modified version.
*/
export class DiffEditorInput extends SideBySideEditorInput {
static readonly ID = 'workbench.editors.diffEditorInput';
private cachedModel: DiffEditorModel | undefined = undefined;
constructor(
protected name: string | undefined,
description: string | undefined,
public readonly originalInput: EditorInput,
public readonly modifiedInput: EditorInput,
private readonly forceOpenAsBinary?: boolean
) {
super(name, description, originalInput, modifiedInput);
}
getTypeId(): string {
return DiffEditorInput.ID;
}
getName(): string {
if (!this.name) {
return localize('sideBySideLabels', "{0} β {1}", this.originalInput.getName(), this.modifiedInput.getName());
}
return this.name;
}
async resolve(): Promise<EditorModel> {
// Create Model - we never reuse our cached model if refresh is true because we cannot
// decide for the inputs within if the cached model can be reused or not. There may be
// inputs that need to be loaded again and thus we always recreate the model and dispose
// the previous one - if any.
const resolvedModel = await this.createModel();
if (this.cachedModel) {
this.cachedModel.dispose();
}
this.cachedModel = resolvedModel;
return this.cachedModel;
}
getPreferredEditorId(candidates: string[]): string {
return this.forceOpenAsBinary ? BINARY_DIFF_EDITOR_ID : TEXT_DIFF_EDITOR_ID;
}
private async createModel(): Promise<DiffEditorModel> {
// Join resolve call over two inputs and build diff editor model
const models = await Promise.all([
this.originalInput.resolve(),
this.modifiedInput.resolve()
]);
const originalEditorModel = models[0];
const modifiedEditorModel = models[1];
// If both are text models, return textdiffeditor model
if (modifiedEditorModel instanceof BaseTextEditorModel && originalEditorModel instanceof BaseTextEditorModel) {
return new TextDiffEditorModel(originalEditorModel, modifiedEditorModel);
}
// Otherwise return normal diff model
return new DiffEditorModel(originalEditorModel, modifiedEditorModel);
}
matches(otherInput: unknown): boolean {
if (!super.matches(otherInput)) {
return false;
}
return otherInput instanceof DiffEditorInput && otherInput.forceOpenAsBinary === this.forceOpenAsBinary;
}
dispose(): void {
// Free the diff editor model but do not propagate the dispose() call to the two inputs
// We never created the two inputs (original and modified) so we can not dispose
// them without sideeffects.
if (this.cachedModel) {
this.cachedModel.dispose();
this.cachedModel = undefined;
}
super.dispose();
}
}
| src/vs/workbench/common/editor/diffEditorInput.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017833351739682257,
0.00017155784007627517,
0.00016714596131350845,
0.0001698234846116975,
0.0000034093131944246124
] |
{
"id": 2,
"code_window": [
"// Lexer helpers\n",
"\n",
"/**\n",
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.\n",
" * Also replaces @\\w+ or sequences with the content of the specified attribute\n",
" */\n",
"function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set, and the 'u' flag if 'unicode' is set.\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 81
} | #!/usr/bin/env bash
set -e
# publish the build
node build/azure-pipelines/common/createAsset.js \
darwin \
archive \
"VSCode-darwin-$VSCODE_QUALITY.zip" \
../VSCode-darwin.zip
# package Remote Extension Host
pushd .. && mv vscode-reh-darwin vscode-server-darwin && zip -Xry vscode-server-darwin.zip vscode-server-darwin && popd
# publish Remote Extension Host
node build/azure-pipelines/common/createAsset.js \
server-darwin \
archive-unsigned \
"vscode-server-darwin.zip" \
../vscode-server-darwin.zip
| build/azure-pipelines/darwin/publish.sh | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00016970546857919544,
0.0001692304213065654,
0.0001687553885858506,
0.0001692304213065654,
4.750399966724217e-7
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\treturn new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n",
"}\n",
"\n",
"/**\n",
" * Compiles guard functions for case matches.\n",
" * This compiles 'cases' attributes into efficient match functions.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlet flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');\n",
"\treturn new RegExp(str, flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 105
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.009322172030806541,
0.00040654235635884106,
0.00016445368237327784,
0.0001668361946940422,
0.001256737275980413
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\treturn new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n",
"}\n",
"\n",
"/**\n",
" * Compiles guard functions for case matches.\n",
" * This compiles 'cases' attributes into efficient match functions.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlet flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');\n",
"\treturn new RegExp(str, flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 105
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService';
import { WorkspaceEdit } from 'vs/editor/common/modes';
import { BulkEditPane } from 'vs/workbench/contrib/bulkEdit/browser/bulkEditPane';
import { IViewContainersRegistry, Extensions as ViewContainerExtensions, ViewContainerLocation, IViewsRegistry, FocusedViewContext, IViewsService } from 'vs/workbench/common/views';
import { localize } from 'vs/nls';
import { ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { RawContextKey, IContextKeyService, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { BulkEditPreviewProvider } from 'vs/workbench/contrib/bulkEdit/browser/bulkEditPreview';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { WorkbenchListFocusContextKey } from 'vs/platform/list/browser/listService';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { URI } from 'vs/base/common/uri';
import { MenuId, registerAction2, Action2 } from 'vs/platform/actions/common/actions';
import { IEditorInput } from 'vs/workbench/common/editor';
import type { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import Severity from 'vs/base/common/severity';
async function getBulkEditPane(viewsService: IViewsService): Promise<BulkEditPane | undefined> {
const view = await viewsService.openView(BulkEditPane.ID, true);
if (view instanceof BulkEditPane) {
return view;
}
return undefined;
}
class UXState {
private readonly _activePanel: string | undefined;
constructor(
@IPanelService private readonly _panelService: IPanelService,
@IEditorGroupsService private readonly _editorGroupsService: IEditorGroupsService,
) {
this._activePanel = _panelService.getActivePanel()?.getId();
}
async restore(): Promise<void> {
// (1) restore previous panel
if (typeof this._activePanel === 'string') {
await this._panelService.openPanel(this._activePanel);
} else {
this._panelService.hideActivePanel();
}
// (2) close preview editors
for (let group of this._editorGroupsService.groups) {
let previewEditors: IEditorInput[] = [];
for (let input of group.editors) {
let resource: URI | undefined;
if (input instanceof DiffEditorInput) {
resource = input.modifiedInput.resource;
} else {
resource = input.resource;
}
if (resource?.scheme === BulkEditPreviewProvider.Schema) {
previewEditors.push(input);
}
}
if (previewEditors.length) {
group.closeEditors(previewEditors, { preserveFocus: true });
}
}
}
}
class PreviewSession {
constructor(
readonly uxState: UXState,
readonly cts: CancellationTokenSource = new CancellationTokenSource(),
) { }
}
class BulkEditPreviewContribution {
static readonly ctxEnabled = new RawContextKey('refactorPreview.enabled', false);
private readonly _ctxEnabled: IContextKey<boolean>;
private _activeSession: PreviewSession | undefined;
constructor(
@IPanelService private readonly _panelService: IPanelService,
@IViewsService private readonly _viewsService: IViewsService,
@IEditorGroupsService private readonly _editorGroupsService: IEditorGroupsService,
@IDialogService private readonly _dialogService: IDialogService,
@IBulkEditService bulkEditService: IBulkEditService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
bulkEditService.setPreviewHandler((edit) => this._previewEdit(edit));
this._ctxEnabled = BulkEditPreviewContribution.ctxEnabled.bindTo(contextKeyService);
}
private async _previewEdit(edit: WorkspaceEdit) {
this._ctxEnabled.set(true);
const uxState = this._activeSession?.uxState ?? new UXState(this._panelService, this._editorGroupsService);
const view = await getBulkEditPane(this._viewsService);
if (!view) {
this._ctxEnabled.set(false);
return edit;
}
// check for active preview session and let the user decide
if (view.hasInput()) {
const choice = await this._dialogService.show(
Severity.Info,
localize('overlap', "Another refactoring is being previewed."),
[localize('cancel', "Cancel"), localize('continue', "Continue")],
{ detail: localize('detail', "Press 'Continue' to discard the previous refactoring and continue with the current refactoring.") }
);
if (choice.choice === 0) {
// this refactoring is being cancelled
return { edits: [] };
}
}
// session
let session: PreviewSession;
if (this._activeSession) {
this._activeSession.cts.dispose(true);
session = new PreviewSession(uxState);
} else {
session = new PreviewSession(uxState);
}
this._activeSession = session;
// the actual work...
try {
const newEditOrUndefined = await view.setInput(edit, session.cts.token);
if (!newEditOrUndefined) {
return { edits: [] };
}
return newEditOrUndefined;
} finally {
// restore UX state
if (this._activeSession === session) {
await this._activeSession.uxState.restore();
this._activeSession.cts.dispose();
this._ctxEnabled.set(false);
this._activeSession = undefined;
}
}
}
}
// CMD: accept
registerAction2(class ApplyAction extends Action2 {
constructor() {
super({
id: 'refactorPreview.apply',
title: { value: localize('apply', "Apply Refactoring"), original: 'Apply Refactoring' },
category: localize('cat', "Refactor Preview"),
icon: { id: 'codicon/check' },
precondition: ContextKeyExpr.and(BulkEditPreviewContribution.ctxEnabled, BulkEditPane.ctxHasCheckedChanges),
menu: [{
id: MenuId.BulkEditTitle,
group: 'navigation'
}, {
id: MenuId.BulkEditContext,
order: 1
}],
keybinding: {
weight: KeybindingWeight.EditorContrib - 10,
when: ContextKeyExpr.and(BulkEditPreviewContribution.ctxEnabled, FocusedViewContext.isEqualTo(BulkEditPane.ID)),
primary: KeyMod.Shift + KeyCode.Enter,
}
});
}
async run(accessor: ServicesAccessor): Promise<any> {
const viewsService = accessor.get(IViewsService);
const view = await getBulkEditPane(viewsService);
if (view) {
view.accept();
}
}
});
// CMD: discard
registerAction2(class DiscardAction extends Action2 {
constructor() {
super({
id: 'refactorPreview.discard',
title: { value: localize('Discard', "Discard Refactoring"), original: 'Discard Refactoring' },
category: localize('cat', "Refactor Preview"),
icon: { id: 'codicon/clear-all' },
precondition: BulkEditPreviewContribution.ctxEnabled,
menu: [{
id: MenuId.BulkEditTitle,
group: 'navigation'
}, {
id: MenuId.BulkEditContext,
order: 2
}]
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const viewsService = accessor.get(IViewsService);
const view = await getBulkEditPane(viewsService);
if (view) {
view.discard();
}
}
});
// CMD: toggle change
registerAction2(class ToggleAction extends Action2 {
constructor() {
super({
id: 'refactorPreview.toggleCheckedState',
title: { value: localize('toogleSelection', "Toggle Change"), original: 'Toggle Change' },
category: localize('cat', "Refactor Preview"),
precondition: BulkEditPreviewContribution.ctxEnabled,
keybinding: {
weight: KeybindingWeight.WorkbenchContrib,
when: WorkbenchListFocusContextKey,
primary: KeyCode.Space,
},
menu: {
id: MenuId.BulkEditContext,
group: 'navigation'
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const viewsService = accessor.get(IViewsService);
const view = await getBulkEditPane(viewsService);
if (view) {
view.toggleChecked();
}
}
});
// CMD: toggle category
registerAction2(class GroupByFile extends Action2 {
constructor() {
super({
id: 'refactorPreview.groupByFile',
title: { value: localize('groupByFile', "Group Changes By File"), original: 'Group Changes By File' },
category: localize('cat', "Refactor Preview"),
icon: { id: 'codicon/ungroup-by-ref-type' },
precondition: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile.negate(), BulkEditPreviewContribution.ctxEnabled),
menu: [{
id: MenuId.BulkEditTitle,
when: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile.negate()),
group: 'navigation',
order: 3,
}]
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const viewsService = accessor.get(IViewsService);
const view = await getBulkEditPane(viewsService);
if (view) {
view.groupByFile();
}
}
});
registerAction2(class GroupByType extends Action2 {
constructor() {
super({
id: 'refactorPreview.groupByType',
title: { value: localize('groupByType', "Group Changes By Type"), original: 'Group Changes By Type' },
category: localize('cat', "Refactor Preview"),
icon: { id: 'codicon/group-by-ref-type' },
precondition: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile, BulkEditPreviewContribution.ctxEnabled),
menu: [{
id: MenuId.BulkEditTitle,
when: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPane.ctxGroupByFile),
group: 'navigation',
order: 3
}]
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const viewsService = accessor.get(IViewsService);
const view = await getBulkEditPane(viewsService);
if (view) {
view.groupByType();
}
}
});
registerAction2(class ToggleGrouping extends Action2 {
constructor() {
super({
id: 'refactorPreview.toggleGrouping',
title: { value: localize('groupByType', "Group Changes By Type"), original: 'Group Changes By Type' },
category: localize('cat', "Refactor Preview"),
icon: { id: 'codicon/list-tree' },
toggled: BulkEditPane.ctxGroupByFile.negate(),
precondition: ContextKeyExpr.and(BulkEditPane.ctxHasCategories, BulkEditPreviewContribution.ctxEnabled),
menu: [{
id: MenuId.BulkEditContext,
order: 3
}]
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const viewsService = accessor.get(IViewsService);
const view = await getBulkEditPane(viewsService);
if (view) {
view.toggleGrouping();
}
}
});
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(
BulkEditPreviewContribution, LifecyclePhase.Ready
);
const container = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).registerViewContainer({
id: BulkEditPane.ID,
name: localize('panel', "Refactor Preview"),
hideIfEmpty: true,
ctorDescriptor: new SyncDescriptor(
ViewPaneContainer,
[BulkEditPane.ID, { mergeViewWithContainerWhenSingleView: true, donotShowContainerTitleWhenMergedWithContainer: true }]
),
storageId: BulkEditPane.ID
}, ViewContainerLocation.Panel);
Registry.as<IViewsRegistry>(ViewContainerExtensions.ViewsRegistry).registerViews([{
id: BulkEditPane.ID,
name: localize('panel', "Refactor Preview"),
when: BulkEditPreviewContribution.ctxEnabled,
ctorDescriptor: new SyncDescriptor(BulkEditPane),
}], container);
| src/vs/workbench/contrib/bulkEdit/browser/bulkEdit.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017253962869290262,
0.00016878009773790836,
0.00016531541768927127,
0.00016835614223964512,
0.000001588463987900468
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\treturn new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n",
"}\n",
"\n",
"/**\n",
" * Compiles guard functions for case matches.\n",
" * This compiles 'cases' attributes into efficient match functions.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlet flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');\n",
"\treturn new RegExp(str, flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 105
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc';
export const ISharedProcessService = createDecorator<ISharedProcessService>('sharedProcessService');
export interface ISharedProcessService {
_serviceBrand: undefined;
getChannel(channelName: string): IChannel;
registerChannel(channelName: string, channel: IServerChannel<string>): void;
whenSharedProcessReady(): Promise<void>;
toggleSharedProcessWindow(): Promise<void>;
}
| src/vs/platform/ipc/electron-browser/sharedProcessService.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.0001735181431286037,
0.00016957717889454216,
0.00016576320922467858,
0.00016945015522651374,
0.0000031672120712755714
] |
{
"id": 3,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');\n",
"\t\t});\n",
"\t}\n",
"\n",
"\treturn new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n",
"}\n",
"\n",
"/**\n",
" * Compiles guard functions for case matches.\n",
" * This compiles 'cases' attributes into efficient match functions.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlet flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');\n",
"\treturn new RegExp(str, flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "replace",
"edit_start_line_idx": 105
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { STATUS_BAR_HOST_NAME_BACKGROUND, STATUS_BAR_HOST_NAME_FOREGROUND } from 'vs/workbench/common/theme';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { Disposable } from 'vs/base/common/lifecycle';
import { MenuId, IMenuService, MenuItemAction, IMenu, MenuRegistry, registerAction2, Action2 } from 'vs/platform/actions/common/actions';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/common/statusbar';
import { ILabelService } from 'vs/platform/label/common/label';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { RemoteConnectionState, Deprecated_RemoteAuthorityContext } from 'vs/workbench/browser/contextkeys';
import { isWeb } from 'vs/base/common/platform';
import { once } from 'vs/base/common/functional';
const WINDOW_ACTIONS_COMMAND_ID = 'workbench.action.remote.showMenu';
const CLOSE_REMOTE_COMMAND_ID = 'workbench.action.remote.close';
const SHOW_CLOSE_REMOTE_COMMAND_ID = !isWeb; // web does not have a "Close Remote" command
export class RemoteWindowActiveIndicator extends Disposable implements IWorkbenchContribution {
private windowIndicatorEntry: IStatusbarEntryAccessor | undefined;
private windowCommandMenu: IMenu;
private hasWindowActions: boolean = false;
private remoteAuthority: string | undefined;
private connectionState: 'initializing' | 'connected' | 'disconnected' | undefined = undefined;
constructor(
@IStatusbarService private readonly statusbarService: IStatusbarService,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@ILabelService private readonly labelService: ILabelService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IMenuService private menuService: IMenuService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ICommandService private readonly commandService: ICommandService,
@IExtensionService extensionService: IExtensionService,
@IRemoteAgentService remoteAgentService: IRemoteAgentService,
@IRemoteAuthorityResolverService remoteAuthorityResolverService: IRemoteAuthorityResolverService,
@IHostService hostService: IHostService
) {
super();
this.windowCommandMenu = this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService);
this._register(this.windowCommandMenu);
const category = nls.localize('remote.category', "Remote");
const that = this;
registerAction2(class extends Action2 {
constructor() {
super({
id: WINDOW_ACTIONS_COMMAND_ID,
category,
title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' },
f1: true,
});
}
run = () => that.showIndicatorActions(that.windowCommandMenu);
});
this.remoteAuthority = environmentService.configuration.remoteAuthority;
Deprecated_RemoteAuthorityContext.bindTo(this.contextKeyService).set(this.remoteAuthority || '');
if (this.remoteAuthority) {
if (SHOW_CLOSE_REMOTE_COMMAND_ID) {
registerAction2(class extends Action2 {
constructor() {
super({
id: CLOSE_REMOTE_COMMAND_ID,
category,
title: { value: nls.localize('remote.close', "Close Remote Connection"), original: 'Close Remote Connection' },
f1: true
});
}
run = () => that.remoteAuthority && hostService.openWindow({ forceReuseWindow: true });
});
MenuRegistry.appendMenuItem(MenuId.MenubarFileMenu, {
group: '6_close',
command: {
id: CLOSE_REMOTE_COMMAND_ID,
title: nls.localize({ key: 'miCloseRemote', comment: ['&& denotes a mnemonic'] }, "Close Re&&mote Connection")
},
order: 3.5
});
}
// Pending entry until extensions are ready
this.renderWindowIndicator('$(sync~spin) ' + nls.localize('host.open', "Opening Remote..."), undefined, WINDOW_ACTIONS_COMMAND_ID);
this.connectionState = 'initializing';
RemoteConnectionState.bindTo(this.contextKeyService).set(this.connectionState);
const connection = remoteAgentService.getConnection();
if (connection) {
this._register(connection.onDidStateChange((e) => {
switch (e.type) {
case PersistentConnectionEventType.ConnectionLost:
case PersistentConnectionEventType.ReconnectionPermanentFailure:
case PersistentConnectionEventType.ReconnectionRunning:
case PersistentConnectionEventType.ReconnectionWait:
this.setDisconnected(true);
break;
case PersistentConnectionEventType.ConnectionGain:
this.setDisconnected(false);
break;
}
}));
}
}
extensionService.whenInstalledExtensionsRegistered().then(_ => {
if (this.remoteAuthority) {
this._register(this.labelService.onDidChangeFormatters(e => this.updateWindowIndicator()));
remoteAuthorityResolverService.resolveAuthority(this.remoteAuthority).then(() => this.setDisconnected(false), () => this.setDisconnected(true));
}
this._register(this.windowCommandMenu.onDidChange(e => this.updateWindowActions()));
this.updateWindowIndicator();
});
}
private setDisconnected(isDisconnected: boolean): void {
const newState = isDisconnected ? 'disconnected' : 'connected';
if (this.connectionState !== newState) {
this.connectionState = newState;
RemoteConnectionState.bindTo(this.contextKeyService).set(this.connectionState);
Deprecated_RemoteAuthorityContext.bindTo(this.contextKeyService).set(isDisconnected ? `disconnected/${this.remoteAuthority!}` : this.remoteAuthority!);
this.updateWindowIndicator();
}
}
private updateWindowIndicator(): void {
const windowActionCommand = (this.remoteAuthority || this.windowCommandMenu.getActions().length) ? WINDOW_ACTIONS_COMMAND_ID : undefined;
if (this.remoteAuthority) {
const hostLabel = this.labelService.getHostLabel(REMOTE_HOST_SCHEME, this.remoteAuthority) || this.remoteAuthority;
if (this.connectionState !== 'disconnected') {
this.renderWindowIndicator(`$(remote) ${hostLabel}`, nls.localize('host.tooltip', "Editing on {0}", hostLabel), windowActionCommand);
} else {
this.renderWindowIndicator(`$(alert) ${nls.localize('disconnectedFrom', "Disconnected from")} ${hostLabel}`, nls.localize('host.tooltipDisconnected', "Disconnected from {0}", hostLabel), windowActionCommand);
}
} else {
if (windowActionCommand) {
this.renderWindowIndicator(`$(remote)`, nls.localize('noHost.tooltip', "Open a remote window"), windowActionCommand);
} else if (this.windowIndicatorEntry) {
this.windowIndicatorEntry.dispose();
this.windowIndicatorEntry = undefined;
}
}
}
private updateWindowActions() {
const newHasWindowActions = this.windowCommandMenu.getActions().length > 0;
if (newHasWindowActions !== this.hasWindowActions) {
this.hasWindowActions = newHasWindowActions;
this.updateWindowIndicator();
}
}
private renderWindowIndicator(text: string, tooltip?: string, command?: string): void {
const properties: IStatusbarEntry = {
backgroundColor: themeColorFromId(STATUS_BAR_HOST_NAME_BACKGROUND),
color: themeColorFromId(STATUS_BAR_HOST_NAME_FOREGROUND),
ariaLabel: nls.localize('remote', "Remote"),
text,
tooltip,
command
};
if (this.windowIndicatorEntry) {
this.windowIndicatorEntry.update(properties);
} else {
this.windowIndicatorEntry = this.statusbarService.addEntry(properties, 'status.host', nls.localize('status.host', "Remote Host"), StatusbarAlignment.LEFT, Number.MAX_VALUE /* first entry */);
}
}
private showIndicatorActions(menu: IMenu) {
const actions = menu.getActions();
const items: (IQuickPickItem | IQuickPickSeparator)[] = [];
for (let actionGroup of actions) {
if (items.length) {
items.push({ type: 'separator' });
}
for (let action of actionGroup[1]) {
if (action instanceof MenuItemAction) {
let label = typeof action.item.title === 'string' ? action.item.title : action.item.title.value;
if (action.item.category) {
const category = typeof action.item.category === 'string' ? action.item.category : action.item.category.value;
label = nls.localize('cat.title', "{0}: {1}", category, label);
}
items.push({
type: 'item',
id: action.item.id,
label
});
}
}
}
if (SHOW_CLOSE_REMOTE_COMMAND_ID && this.remoteAuthority) {
if (items.length) {
items.push({ type: 'separator' });
}
items.push({
type: 'item',
id: CLOSE_REMOTE_COMMAND_ID,
label: nls.localize('closeRemote.title', 'Close Remote Connection')
});
}
const quickPick = this.quickInputService.createQuickPick();
quickPick.items = items;
quickPick.canSelectMany = false;
once(quickPick.onDidAccept)((_ => {
const selectedItems = quickPick.selectedItems;
if (selectedItems.length === 1) {
this.commandService.executeCommand(selectedItems[0].id!);
}
quickPick.hide();
}));
quickPick.show();
}
}
| src/vs/workbench/contrib/remote/browser/remoteIndicator.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017208617646247149,
0.00016798188153188676,
0.00016576335474383086,
0.00016791406960692257,
0.0000013628725810121978
] |
{
"id": 4,
"code_window": [
"\n",
"\t// Set standard fields: be defensive about types\n",
"\tlexer.start = (typeof json.start === 'string' ? json.start : null);\n",
"\tlexer.ignoreCase = bool(json.ignoreCase, false);\n",
"\n",
"\tlexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);\n",
"\tlexer.defaultToken = string(json.defaultToken, 'source');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexer.unicode = bool(json.unicode, false);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 402
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.9939061999320984,
0.020198704674839973,
0.00016237959789577872,
0.0002841007662937045,
0.1338096261024475
] |
{
"id": 4,
"code_window": [
"\n",
"\t// Set standard fields: be defensive about types\n",
"\tlexer.start = (typeof json.start === 'string' ? json.start : null);\n",
"\tlexer.ignoreCase = bool(json.ignoreCase, false);\n",
"\n",
"\tlexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);\n",
"\tlexer.defaultToken = string(json.defaultToken, 'source');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexer.unicode = bool(json.unicode, false);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 402
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import * as DOM from 'vs/base/browser/dom';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { ILabelService } from 'vs/platform/label/common/label';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { isMacintosh, isWindows, isLinux } from 'vs/base/common/platform';
import { IMenuService } from 'vs/platform/actions/common/actions';
import { TitlebarPart as BrowserTitleBarPart } from 'vs/workbench/browser/parts/titlebar/titlebarPart';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { IProductService } from 'vs/platform/product/common/productService';
import { IElectronService } from 'vs/platform/electron/node/electron';
import { getTitleBarStyle } from 'vs/platform/windows/common/windows';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Codicon } from 'vs/base/common/codicons';
export class TitlebarPart extends BrowserTitleBarPart {
private appIcon: HTMLElement | undefined;
private windowControls: HTMLElement | undefined;
private maxRestoreControl: HTMLElement | undefined;
private dragRegion: HTMLElement | undefined;
private resizer: HTMLElement | undefined;
constructor(
@IContextMenuService contextMenuService: IContextMenuService,
@IConfigurationService protected readonly configurationService: IConfigurationService,
@IEditorService editorService: IEditorService,
@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@ILabelService labelService: ILabelService,
@IStorageService storageService: IStorageService,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@IMenuService menuService: IMenuService,
@IContextKeyService contextKeyService: IContextKeyService,
@IHostService hostService: IHostService,
@IProductService productService: IProductService,
@IElectronService private readonly electronService: IElectronService
) {
super(contextMenuService, configurationService, editorService, environmentService, contextService, instantiationService, themeService, labelService, storageService, layoutService, menuService, contextKeyService, hostService, productService);
}
private onUpdateAppIconDragBehavior() {
const setting = this.configurationService.getValue('window.doubleClickIconToClose');
if (setting && this.appIcon) {
(this.appIcon.style as any)['-webkit-app-region'] = 'no-drag';
} else if (this.appIcon) {
(this.appIcon.style as any)['-webkit-app-region'] = 'drag';
}
}
private onDidChangeMaximized(maximized: boolean) {
if (this.maxRestoreControl) {
if (maximized) {
DOM.removeClasses(this.maxRestoreControl, Codicon.chromeMaximize.classNames);
DOM.addClasses(this.maxRestoreControl, Codicon.chromeRestore.classNames);
} else {
DOM.removeClasses(this.maxRestoreControl, Codicon.chromeRestore.classNames);
DOM.addClasses(this.maxRestoreControl, Codicon.chromeMaximize.classNames);
}
}
if (this.resizer) {
if (maximized) {
DOM.hide(this.resizer);
} else {
DOM.show(this.resizer);
}
}
this.adjustTitleMarginToCenter();
}
private onMenubarFocusChanged(focused: boolean) {
if ((isWindows || isLinux) && this.currentMenubarVisibility !== 'compact' && this.dragRegion) {
if (focused) {
DOM.hide(this.dragRegion);
} else {
DOM.show(this.dragRegion);
}
}
}
protected onMenubarVisibilityChanged(visible: boolean) {
// Hide title when toggling menu bar
if ((isWindows || isLinux) && this.currentMenubarVisibility === 'toggle' && visible) {
// Hack to fix issue #52522 with layered webkit-app-region elements appearing under cursor
if (this.dragRegion) {
DOM.hide(this.dragRegion);
setTimeout(() => DOM.show(this.dragRegion!), 50);
}
}
super.onMenubarVisibilityChanged(visible);
}
protected onConfigurationChanged(event: IConfigurationChangeEvent): void {
super.onConfigurationChanged(event);
if (event.affectsConfiguration('window.doubleClickIconToClose')) {
if (this.appIcon) {
this.onUpdateAppIconDragBehavior();
}
}
}
protected adjustTitleMarginToCenter(): void {
if (this.customMenubar && this.menubar) {
const leftMarker = (this.appIcon ? this.appIcon.clientWidth : 0) + this.menubar.clientWidth + 10;
const rightMarker = this.element.clientWidth - (this.windowControls ? this.windowControls.clientWidth : 0) - 10;
// Not enough space to center the titlebar within window,
// Center between menu and window controls
if (leftMarker > (this.element.clientWidth - this.title.clientWidth) / 2 ||
rightMarker < (this.element.clientWidth + this.title.clientWidth) / 2) {
this.title.style.position = '';
this.title.style.left = '';
this.title.style.transform = '';
return;
}
}
this.title.style.position = 'absolute';
this.title.style.left = '50%';
this.title.style.transform = 'translate(-50%, 0)';
}
protected installMenubar(): void {
super.installMenubar();
if (this.menubar) {
return;
}
if (this.customMenubar) {
this._register(this.customMenubar.onFocusStateChange(e => this.onMenubarFocusChanged(e)));
}
}
createContentArea(parent: HTMLElement): HTMLElement {
const ret = super.createContentArea(parent);
// App Icon (Native Windows/Linux)
if (!isMacintosh) {
this.appIcon = DOM.prepend(this.element, DOM.$('div.window-appicon'));
this.onUpdateAppIconDragBehavior();
this._register(DOM.addDisposableListener(this.appIcon, DOM.EventType.DBLCLICK, (e => {
this.electronService.closeWindow();
})));
}
// Draggable region that we can manipulate for #52522
this.dragRegion = DOM.prepend(this.element, DOM.$('div.titlebar-drag-region'));
// Window Controls (Native Windows/Linux)
if (!isMacintosh) {
this.windowControls = DOM.append(this.element, DOM.$('div.window-controls-container'));
// Minimize
const minimizeIcon = DOM.append(this.windowControls, DOM.$('div.window-icon.window-minimize' + Codicon.chromeMinimize.cssSelector));
this._register(DOM.addDisposableListener(minimizeIcon, DOM.EventType.CLICK, e => {
this.electronService.minimizeWindow();
}));
// Restore
this.maxRestoreControl = DOM.append(this.windowControls, DOM.$('div.window-icon.window-max-restore'));
this._register(DOM.addDisposableListener(this.maxRestoreControl, DOM.EventType.CLICK, async e => {
const maximized = await this.electronService.isMaximized();
if (maximized) {
return this.electronService.unmaximizeWindow();
}
return this.electronService.maximizeWindow();
}));
// Close
const closeIcon = DOM.append(this.windowControls, DOM.$('div.window-icon.window-close' + Codicon.chromeClose.cssSelector));
this._register(DOM.addDisposableListener(closeIcon, DOM.EventType.CLICK, e => {
this.electronService.closeWindow();
}));
// Resizer
this.resizer = DOM.append(this.element, DOM.$('div.resizer'));
this._register(this.layoutService.onMaximizeChange(maximized => this.onDidChangeMaximized(maximized)));
this.onDidChangeMaximized(this.layoutService.isWindowMaximized());
}
return ret;
}
updateLayout(dimension: DOM.Dimension): void {
this.lastLayoutDimensions = dimension;
if (getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') {
// Only prevent zooming behavior on macOS or when the menubar is not visible
if (isMacintosh || this.currentMenubarVisibility === 'hidden') {
this.title.style.zoom = `${1 / browser.getZoomFactor()}`;
if (isWindows || isLinux) {
if (this.appIcon) {
this.appIcon.style.zoom = `${1 / browser.getZoomFactor()}`;
}
if (this.windowControls) {
this.windowControls.style.zoom = `${1 / browser.getZoomFactor()}`;
}
}
} else {
this.title.style.zoom = '';
if (isWindows || isLinux) {
if (this.appIcon) {
this.appIcon.style.zoom = '';
}
if (this.windowControls) {
this.windowControls.style.zoom = '';
}
}
}
DOM.runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter());
if (this.customMenubar) {
const menubarDimension = new DOM.Dimension(0, dimension.height);
this.customMenubar.layout(menubarDimension);
}
}
}
}
| src/vs/workbench/electron-browser/parts/titlebar/titlebarPart.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00020553338981699198,
0.00017582863802090287,
0.0001706127804936841,
0.0001746069174259901,
0.000006432268492062576
] |
{
"id": 4,
"code_window": [
"\n",
"\t// Set standard fields: be defensive about types\n",
"\tlexer.start = (typeof json.start === 'string' ? json.start : null);\n",
"\tlexer.ignoreCase = bool(json.ignoreCase, false);\n",
"\n",
"\tlexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);\n",
"\tlexer.defaultToken = string(json.defaultToken, 'source');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexer.unicode = bool(json.unicode, false);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 402
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { BrandedService, IConstructorSignature1 } from 'vs/platform/instantiation/common/instantiation';
import { INotebookEditor, INotebookEditorContribution } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
export type INotebookEditorContributionCtor = IConstructorSignature1<INotebookEditor, INotebookEditorContribution>;
export interface INotebookEditorContributionDescription {
id: string;
ctor: INotebookEditorContributionCtor;
}
class EditorContributionRegistry {
public static readonly INSTANCE = new EditorContributionRegistry();
private readonly editorContributions: INotebookEditorContributionDescription[];
constructor() {
this.editorContributions = [];
}
public registerEditorContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: INotebookEditor, ...services: Services): INotebookEditorContribution }): void {
this.editorContributions.push({ id, ctor: ctor as INotebookEditorContributionCtor });
}
public getEditorContributions(): INotebookEditorContributionDescription[] {
return this.editorContributions.slice(0);
}
}
export function registerNotebookContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: INotebookEditor, ...services: Services): INotebookEditorContribution }): void {
EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor);
}
export namespace NotebookEditorExtensionsRegistry {
export function getEditorContributions(): INotebookEditorContributionDescription[] {
return EditorContributionRegistry.INSTANCE.getEditorContributions();
}
}
| src/vs/workbench/contrib/notebook/browser/notebookEditorExtensions.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017640436999499798,
0.00017349020345136523,
0.00016652887279633433,
0.00017577389371581376,
0.0000037830618566658814
] |
{
"id": 4,
"code_window": [
"\n",
"\t// Set standard fields: be defensive about types\n",
"\tlexer.start = (typeof json.start === 'string' ? json.start : null);\n",
"\tlexer.ignoreCase = bool(json.ignoreCase, false);\n",
"\n",
"\tlexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);\n",
"\tlexer.defaultToken = string(json.defaultToken, 'source');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexer.unicode = bool(json.unicode, false);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 402
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable } from 'vs/base/common/lifecycle';
import { FeedbackDropdown, IFeedback, IFeedbackDelegate } from 'vs/workbench/contrib/feedback/browser/feedback';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProductService } from 'vs/platform/product/common/productService';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IStatusbarService, StatusbarAlignment, IStatusbarEntry, IStatusbarEntryAccessor } from 'vs/workbench/services/statusbar/common/statusbar';
import { localize } from 'vs/nls';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
class TwitterFeedbackService implements IFeedbackDelegate {
private static TWITTER_URL: string = 'https://twitter.com/intent/tweet';
private static VIA_NAME: string = 'code';
private static HASHTAGS: string[] = ['HappyCoding'];
private combineHashTagsAsString(): string {
return TwitterFeedbackService.HASHTAGS.join(',');
}
submitFeedback(feedback: IFeedback, openerService: IOpenerService): void {
const queryString = `?${feedback.sentiment === 1 ? `hashtags=${this.combineHashTagsAsString()}&` : null}ref_src=twsrc%5Etfw&related=twitterapi%2Ctwitter&text=${encodeURIComponent(feedback.feedback)}&tw_p=tweetbutton&via=${TwitterFeedbackService.VIA_NAME}`;
const url = TwitterFeedbackService.TWITTER_URL + queryString;
openerService.open(URI.parse(url));
}
getCharacterLimit(sentiment: number): number {
let length: number = 0;
if (sentiment === 1) {
TwitterFeedbackService.HASHTAGS.forEach(element => {
length += element.length + 2;
});
}
if (TwitterFeedbackService.VIA_NAME) {
length += ` via @${TwitterFeedbackService.VIA_NAME}`.length;
}
return 280 - length;
}
}
export class FeedbackStatusbarConribution extends Disposable implements IWorkbenchContribution {
private dropdown: FeedbackDropdown | undefined;
private entry: IStatusbarEntryAccessor | undefined;
constructor(
@IStatusbarService statusbarService: IStatusbarService,
@IProductService productService: IProductService,
@IInstantiationService private instantiationService: IInstantiationService,
@IContextViewService private contextViewService: IContextViewService
) {
super();
if (productService.sendASmile) {
this.entry = this._register(statusbarService.addEntry(this.getStatusEntry(), 'status.feedback', localize('status.feedback', "Tweet Feedback"), StatusbarAlignment.RIGHT, -100 /* towards the end of the right hand side */));
CommandsRegistry.registerCommand('help.tweetFeedback', () => this.toggleFeedback());
MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
command: {
id: 'help.tweetFeedback',
category: localize('help', "Help"),
title: localize('status.feedback', "Tweet Feedback")
}
});
}
}
private toggleFeedback(): void {
if (!this.dropdown) {
const statusContainr = document.getElementById('status.feedback');
if (statusContainr) {
const icon = statusContainr.getElementsByClassName('codicon').item(0) as HTMLElement | null;
if (!icon) {
throw new Error('Could not find icon');
}
this.dropdown = this._register(this.instantiationService.createInstance(FeedbackDropdown, icon, {
contextViewProvider: this.contextViewService,
feedbackService: this.instantiationService.createInstance(TwitterFeedbackService),
onFeedbackVisibilityChange: visible => this.entry!.update(this.getStatusEntry(visible))
}));
}
}
if (this.dropdown) {
if (!this.dropdown.isVisible()) {
this.dropdown.show();
} else {
this.dropdown.hide();
}
}
}
private getStatusEntry(showBeak?: boolean): IStatusbarEntry {
return {
text: '$(feedback)',
ariaLabel: localize('status.feedback', "Tweet Feedback"),
tooltip: localize('status.feedback', "Tweet Feedback"),
command: 'help.tweetFeedback',
showBeak
};
}
}
| src/vs/workbench/contrib/feedback/browser/feedbackStatusbarItem.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017952796770259738,
0.00017490437312517315,
0.00017181433213409036,
0.00017511223268229514,
0.000002281747811139212
] |
{
"id": 5,
"code_window": [
"\t// For calling compileAction later on\n",
"\tlet lexerMin: monarchCommon.ILexerMin = <any>json;\n",
"\tlexerMin.languageId = languageId;\n",
"\tlexerMin.ignoreCase = lexer.ignoreCase;\n",
"\tlexerMin.noThrow = lexer.noThrow;\n",
"\tlexerMin.usesEmbedded = lexer.usesEmbedded;\n",
"\tlexerMin.stateNames = json.tokenizer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexerMin.unicode = lexer.unicode;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 412
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module exports common types and functionality shared between
* the Monarch compiler that compiles JSON to ILexer, and the Monarch
* Tokenizer (that highlights at runtime)
*/
/*
* Type definitions to be used internally to Monarch.
* Inside monarch we use fully typed definitions and compiled versions of the more abstract JSON descriptions.
*/
export const enum MonarchBracket {
None = 0,
Open = 1,
Close = -1
}
export interface ILexerMin {
languageId: string;
noThrow: boolean;
ignoreCase: boolean;
usesEmbedded: boolean;
defaultToken: string;
stateNames: { [stateName: string]: any; };
[attr: string]: any;
}
export interface ILexer extends ILexerMin {
maxStack: number;
start: string | null;
ignoreCase: boolean;
tokenPostfix: string;
tokenizer: { [stateName: string]: IRule[]; };
brackets: IBracket[];
}
export interface IBracket {
token: string;
open: string;
close: string;
}
export type FuzzyAction = IAction | string;
export function isFuzzyActionArr(what: FuzzyAction | FuzzyAction[]): what is FuzzyAction[] {
return (Array.isArray(what));
}
export function isFuzzyAction(what: FuzzyAction | FuzzyAction[]): what is FuzzyAction {
return !isFuzzyActionArr(what);
}
export function isString(what: FuzzyAction): what is string {
return (typeof what === 'string');
}
export function isIAction(what: FuzzyAction): what is IAction {
return !isString(what);
}
export interface IRule {
regex: RegExp;
action: FuzzyAction;
matchOnlyAtLineStart: boolean;
name: string;
}
export interface IAction {
// an action is either a group of actions
group?: FuzzyAction[];
// or a function that returns a fresh action
test?: (id: string, matches: string[], state: string, eos: boolean) => FuzzyAction;
// or it is a declarative action with a token value and various other attributes
token?: string;
tokenSubst?: boolean;
next?: string;
nextEmbedded?: string;
bracket?: MonarchBracket;
log?: string;
switchTo?: string;
goBack?: number;
transform?: (states: string[]) => string[];
}
export interface IBranch {
name: string;
value: FuzzyAction;
test?: (id: string, matches: string[], state: string, eos: boolean) => boolean;
}
// Small helper functions
/**
* Is a string null, undefined, or empty?
*/
export function empty(s: string): boolean {
return (s ? false : true);
}
/**
* Puts a string to lower case if 'ignoreCase' is set.
*/
export function fixCase(lexer: ILexerMin, str: string): string {
return (lexer.ignoreCase && str ? str.toLowerCase() : str);
}
/**
* Ensures there are no bad characters in a CSS token class.
*/
export function sanitize(s: string) {
return s.replace(/[&<>'"_]/g, '-'); // used on all output token CSS classes
}
// Logging
/**
* Logs a message.
*/
export function log(lexer: ILexerMin, msg: string) {
console.log(`${lexer.languageId}: ${msg}`);
}
// Throwing errors
export function createError(lexer: ILexerMin, msg: string): Error {
return new Error(`${lexer.languageId}: ${msg}`);
}
// Helper functions for rule finding and substitution
/**
* substituteMatches is used on lexer strings and can substitutes predefined patterns:
* $$ => $
* $# => id
* $n => matched entry n
* @attr => contents of lexer[attr]
*
* See documentation for more info
*/
export function substituteMatches(lexer: ILexerMin, str: string, id: string, matches: string[], state: string): string {
const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
let stateMatches: string[] | null = null;
return str.replace(re, function (full, sub?, dollar?, hash?, n?, s?, attr?, ofs?, total?) {
if (!empty(dollar)) {
return '$'; // $$
}
if (!empty(hash)) {
return fixCase(lexer, id); // default $#
}
if (!empty(n) && n < matches.length) {
return fixCase(lexer, matches[n]); // $n
}
if (!empty(attr) && lexer && typeof (lexer[attr]) === 'string') {
return lexer[attr]; //@attribute
}
if (stateMatches === null) { // split state on demand
stateMatches = state.split('.');
stateMatches.unshift(state);
}
if (!empty(s) && s < stateMatches.length) {
return fixCase(lexer, stateMatches[s]); //$Sn
}
return '';
});
}
/**
* Find the tokenizer rules for a specific state (i.e. next action)
*/
export function findRules(lexer: ILexer, inState: string): IRule[] | null {
let state: string | null = inState;
while (state && state.length > 0) {
const rules = lexer.tokenizer[state];
if (rules) {
return rules;
}
const idx = state.lastIndexOf('.');
if (idx < 0) {
state = null; // no further parent
} else {
state = state.substr(0, idx);
}
}
return null;
}
/**
* Is a certain state defined? In contrast to 'findRules' this works on a ILexerMin.
* This is used during compilation where we may know the defined states
* but not yet whether the corresponding rules are correct.
*/
export function stateExists(lexer: ILexerMin, inState: string): boolean {
let state: string | null = inState;
while (state && state.length > 0) {
const exist = lexer.stateNames[state];
if (exist) {
return true;
}
const idx = state.lastIndexOf('.');
if (idx < 0) {
state = null; // no further parent
} else {
state = state.substr(0, idx);
}
}
return false;
}
| src/vs/editor/standalone/common/monarch/monarchCommon.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.996271014213562,
0.22414828836917877,
0.00016372630489058793,
0.00040211452869698405,
0.41218042373657227
] |
{
"id": 5,
"code_window": [
"\t// For calling compileAction later on\n",
"\tlet lexerMin: monarchCommon.ILexerMin = <any>json;\n",
"\tlexerMin.languageId = languageId;\n",
"\tlexerMin.ignoreCase = lexer.ignoreCase;\n",
"\tlexerMin.noThrow = lexer.noThrow;\n",
"\tlexerMin.usesEmbedded = lexer.usesEmbedded;\n",
"\tlexerMin.stateNames = json.tokenizer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexerMin.unicode = lexer.unicode;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 412
} | {
"comments": {
"lineComment": "//",
"blockComment": [ "/*", "*/" ]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
{ "open": "{", "close": "}" },
{ "open": "[", "close": "]" },
{ "open": "(", "close": ")" },
{ "open": "'", "close": "'", "notIn": ["string", "comment"] },
{ "open": "\"", "close": "\"", "notIn": ["string"] },
{ "open": "`", "close": "`", "notIn": ["string", "comment"] },
{ "open": "/**", "close": " */", "notIn": ["string"] }
],
"surroundingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["'", "'"],
["\"", "\""],
["`", "`"],
["<", ">"]
],
"autoCloseBefore": ";:.,=}])>` \n\t",
"folding": {
"markers": {
"start": "^\\s*//\\s*#?region\\b",
"end": "^\\s*//\\s*#?endregion\\b"
}
}
}
| extensions/typescript-basics/language-configuration.json | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017668599321041256,
0.00017550209304317832,
0.00017350226698908955,
0.00017591005598660558,
0.000001198716631733987
] |
{
"id": 5,
"code_window": [
"\t// For calling compileAction later on\n",
"\tlet lexerMin: monarchCommon.ILexerMin = <any>json;\n",
"\tlexerMin.languageId = languageId;\n",
"\tlexerMin.ignoreCase = lexer.ignoreCase;\n",
"\tlexerMin.noThrow = lexer.noThrow;\n",
"\tlexerMin.usesEmbedded = lexer.usesEmbedded;\n",
"\tlexerMin.stateNames = json.tokenizer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexerMin.unicode = lexer.unicode;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 412
} | Name: @@NAME@@
Version: @@VERSION@@
Release: @@RELEASE@@.el7
Summary: Code editing. Redefined.
Group: Development/Tools
Vendor: Microsoft Corporation
Packager: Visual Studio Code Team <[email protected]>
License: @@LICENSE@@
URL: https://code.visualstudio.com/
Icon: @@NAME@@.xpm
Requires: @@DEPENDENCIES@@
AutoReq: 0
%description
Visual Studio Code is a new choice of tool that combines the simplicity of a code editor with what developers need for the core edit-build-debug cycle. See https://code.visualstudio.com/docs/setup/linux for installation instructions and FAQ.
%install
mkdir -p %{buildroot}/usr/share/@@NAME@@
mkdir -p %{buildroot}/usr/share/applications
mkdir -p %{buildroot}/usr/share/pixmaps
mkdir -p %{buildroot}/usr/share/bash-completion/completions
mkdir -p %{buildroot}/usr/share/zsh/site-functions
cp -r usr/share/@@NAME@@/* %{buildroot}/usr/share/@@NAME@@
cp -r usr/share/applications/@@NAME@@.desktop %{buildroot}/usr/share/applications
cp -r usr/share/applications/@@NAME@@-url-handler.desktop %{buildroot}/usr/share/applications
cp -r usr/share/pixmaps/@@ICON@@.png %{buildroot}/usr/share/pixmaps
cp usr/share/bash-completion/completions/@@NAME@@ %{buildroot}/usr/share/bash-completion/completions/@@NAME@@
cp usr/share/zsh/site-functions/_@@NAME@@ %{buildroot}/usr/share/zsh/site-functions/_@@NAME@@
%post
# Remove the legacy bin command if this is the stable build
if [ "@@NAME@@" = "code" ]; then
rm -f /usr/local/bin/code
fi
# Symlink bin command to /usr/bin
ln -sf /usr/share/@@NAME@@/bin/@@NAME@@ %{_bindir}/@@NAME@@
# Register yum repository
# TODO: #229: Enable once the yum repository is signed
#if [ "@@NAME@@" != "code-oss" ]; then
# if [ -d "/etc/yum.repos.d" ]; then
# REPO_FILE=/etc/yum.repos.d/@@NAME@@.repo
# rm -f $REPO_FILE
# echo -e "[@@NAME@@]\nname=@@NAME_LONG@@\nbaseurl=@@UPDATEURL@@/api/rpm/@@QUALITY@@/@@ARCHITECTURE@@/rpm" > $REPO_FILE
# fi
#fi
%postun
if [ $1 = 0 ]; then
rm -f /usr/bin/@@NAME@@
fi
%files
%defattr(-,root,root)
/usr/share/@@NAME@@/
/usr/share/applications/@@NAME@@.desktop
/usr/share/applications/@@NAME@@-url-handler.desktop
/usr/share/pixmaps/@@ICON@@.png
/usr/share/bash-completion/completions/@@NAME@@
/usr/share/zsh/site-functions/_@@NAME@@
| resources/linux/rpm/code.spec.template | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017883362306747586,
0.00017486191063653678,
0.00016599777154624462,
0.0001771078386809677,
0.000004288902800908545
] |
{
"id": 5,
"code_window": [
"\t// For calling compileAction later on\n",
"\tlet lexerMin: monarchCommon.ILexerMin = <any>json;\n",
"\tlexerMin.languageId = languageId;\n",
"\tlexerMin.ignoreCase = lexer.ignoreCase;\n",
"\tlexerMin.noThrow = lexer.noThrow;\n",
"\tlexerMin.usesEmbedded = lexer.usesEmbedded;\n",
"\tlexerMin.stateNames = json.tokenizer;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlexerMin.unicode = lexer.unicode;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchCompile.ts",
"type": "add",
"edit_start_line_idx": 412
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'vs/base/common/path';
import * as nls from 'vs/nls';
import * as Objects from 'vs/base/common/objects';
import * as Types from 'vs/base/common/types';
import * as Platform from 'vs/base/common/platform';
import * as Async from 'vs/base/common/async';
import * as resources from 'vs/base/common/resources';
import { IStringDictionary, values } from 'vs/base/common/collections';
import { LinkedMap, Touch } from 'vs/base/common/map';
import Severity from 'vs/base/common/severity';
import { Event, Emitter } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { isUNC } from 'vs/base/common/extpath';
import { IFileService } from 'vs/platform/files/common/files';
import { IMarkerService, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ProblemMatcher, ProblemMatcherRegistry /*, ProblemPattern, getResource */ } from 'vs/workbench/contrib/tasks/common/problemMatcher';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { IShellLaunchConfig, TERMINAL_VIEW_ID } from 'vs/workbench/contrib/terminal/common/terminal';
import { ITerminalService, ITerminalInstanceService, ITerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminal';
import { IOutputService } from 'vs/workbench/contrib/output/common/output';
import { StartStopProblemCollector, WatchingProblemCollector, ProblemCollectorEventKind, ProblemHandlingStrategy } from 'vs/workbench/contrib/tasks/common/problemCollectors';
import {
Task, CustomTask, ContributedTask, RevealKind, CommandOptions, ShellConfiguration, RuntimeType, PanelKind,
TaskEvent, TaskEventKind, ShellQuotingOptions, ShellQuoting, CommandString, CommandConfiguration, ExtensionTaskSource, TaskScope, RevealProblemKind, DependsOrder, TaskSourceKind, InMemoryTask
} from 'vs/workbench/contrib/tasks/common/tasks';
import {
ITaskSystem, ITaskSummary, ITaskExecuteResult, TaskExecuteKind, TaskError, TaskErrors, ITaskResolver,
TelemetryEvent, Triggers, TaskTerminateResponse, TaskSystemInfoResolver, TaskSystemInfo, ResolveSet, ResolvedVariables
} from 'vs/workbench/contrib/tasks/common/taskSystem';
import { URI } from 'vs/base/common/uri';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { Schemas } from 'vs/base/common/network';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { env as processEnv, cwd as processCwd } from 'vs/base/common/process';
import { IViewsService, IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views';
interface TerminalData {
terminal: ITerminalInstance;
lastTask: string;
group?: string;
}
interface ActiveTerminalData {
terminal: ITerminalInstance;
task: Task;
promise: Promise<ITaskSummary>;
}
class InstanceManager {
private _currentInstances: number = 0;
private _counter: number = 0;
addInstance() {
this._currentInstances++;
this._counter++;
}
removeInstance() {
this._currentInstances--;
}
get instances() {
return this._currentInstances;
}
get counter() {
return this._counter;
}
}
class VariableResolver {
constructor(public workspaceFolder: IWorkspaceFolder | undefined, public taskSystemInfo: TaskSystemInfo | undefined, private _values: Map<string, string>, private _service: IConfigurationResolverService | undefined) {
}
resolve(value: string): string {
return value.replace(/\$\{(.*?)\}/g, (match: string, variable: string) => {
// Strip out the ${} because the map contains them variables without those characters.
let result = this._values.get(match.substring(2, match.length - 1));
if ((result !== undefined) && (result !== null)) {
return result;
}
if (this._service) {
return this._service.resolve(this.workspaceFolder, match);
}
return match;
});
}
}
export class VerifiedTask {
readonly task: Task;
readonly resolver: ITaskResolver;
readonly trigger: string;
resolvedVariables?: ResolvedVariables;
systemInfo?: TaskSystemInfo;
workspaceFolder?: IWorkspaceFolder;
shellLaunchConfig?: IShellLaunchConfig;
constructor(task: Task, resolver: ITaskResolver, trigger: string) {
this.task = task;
this.resolver = resolver;
this.trigger = trigger;
}
public verify(): boolean {
let verified = false;
if (this.trigger && this.resolvedVariables && this.workspaceFolder && (this.shellLaunchConfig !== undefined)) {
verified = true;
}
return verified;
}
public getVerifiedTask(): { task: Task, resolver: ITaskResolver, trigger: string, resolvedVariables: ResolvedVariables, systemInfo: TaskSystemInfo, workspaceFolder: IWorkspaceFolder, shellLaunchConfig: IShellLaunchConfig } {
if (this.verify()) {
return { task: this.task, resolver: this.resolver, trigger: this.trigger, resolvedVariables: this.resolvedVariables!, systemInfo: this.systemInfo!, workspaceFolder: this.workspaceFolder!, shellLaunchConfig: this.shellLaunchConfig! };
} else {
throw new Error('VerifiedTask was not checked. verify must be checked before getVerifiedTask.');
}
}
}
export class TerminalTaskSystem implements ITaskSystem {
public static TelemetryEventName: string = 'taskService';
private static readonly ProcessVarName = '__process__';
private static shellQuotes: IStringDictionary<ShellQuotingOptions> = {
'cmd': {
strong: '"'
},
'powershell': {
escape: {
escapeChar: '`',
charsToEscape: ' "\'()'
},
strong: '\'',
weak: '"'
},
'bash': {
escape: {
escapeChar: '\\',
charsToEscape: ' "\''
},
strong: '\'',
weak: '"'
},
'zsh': {
escape: {
escapeChar: '\\',
charsToEscape: ' "\''
},
strong: '\'',
weak: '"'
}
};
private static osShellQuotes: IStringDictionary<ShellQuotingOptions> = {
'Linux': TerminalTaskSystem.shellQuotes['bash'],
'Mac': TerminalTaskSystem.shellQuotes['bash'],
'Windows': TerminalTaskSystem.shellQuotes['powershell']
};
private activeTasks: IStringDictionary<ActiveTerminalData>;
private instances: IStringDictionary<InstanceManager>;
private busyTasks: IStringDictionary<Task>;
private terminals: IStringDictionary<TerminalData>;
private idleTaskTerminals: LinkedMap<string, string>;
private sameTaskTerminals: IStringDictionary<string>;
private taskSystemInfoResolver: TaskSystemInfoResolver;
private lastTask: VerifiedTask | undefined;
// Should always be set in run
private currentTask!: VerifiedTask;
private isRerun: boolean = false;
private previousPanelId: string | undefined;
private previousTerminalInstance: ITerminalInstance | undefined;
private readonly _onDidStateChange: Emitter<TaskEvent>;
constructor(
private terminalService: ITerminalService,
private outputService: IOutputService,
private panelService: IPanelService,
private viewsService: IViewsService,
private markerService: IMarkerService, private modelService: IModelService,
private configurationResolverService: IConfigurationResolverService,
private telemetryService: ITelemetryService,
private contextService: IWorkspaceContextService,
private environmentService: IWorkbenchEnvironmentService,
private outputChannelId: string,
private fileService: IFileService,
private terminalInstanceService: ITerminalInstanceService,
private pathService: IPathService,
private viewDescriptorService: IViewDescriptorService,
taskSystemInfoResolver: TaskSystemInfoResolver,
) {
this.activeTasks = Object.create(null);
this.instances = Object.create(null);
this.busyTasks = Object.create(null);
this.terminals = Object.create(null);
this.idleTaskTerminals = new LinkedMap<string, string>();
this.sameTaskTerminals = Object.create(null);
this._onDidStateChange = new Emitter();
this.taskSystemInfoResolver = taskSystemInfoResolver;
}
public get onDidStateChange(): Event<TaskEvent> {
return this._onDidStateChange.event;
}
public log(value: string): void {
this.appendOutput(value + '\n');
}
protected showOutput(): void {
this.outputService.showChannel(this.outputChannelId, true);
}
public run(task: Task, resolver: ITaskResolver, trigger: string = Triggers.command): ITaskExecuteResult {
task = task.clone(); // A small amount of task state is stored in the task (instance) and tasks passed in to run may have that set already.
const recentTaskKey = task.getRecentlyUsedKey() ?? '';
let validInstance = task.runOptions && task.runOptions.instanceLimit && this.instances[recentTaskKey] && this.instances[recentTaskKey].instances < task.runOptions.instanceLimit;
let instance = this.instances[recentTaskKey] ? this.instances[recentTaskKey].instances : 0;
this.currentTask = new VerifiedTask(task, resolver, trigger);
if (instance > 0) {
task.instance = this.instances[recentTaskKey].counter;
}
let lastTaskInstance = this.getLastInstance(task);
let terminalData = lastTaskInstance ? this.activeTasks[lastTaskInstance.getMapKey()] : undefined;
if (terminalData && terminalData.promise && !validInstance) {
this.lastTask = this.currentTask;
return { kind: TaskExecuteKind.Active, task: terminalData.task, active: { same: true, background: task.configurationProperties.isBackground! }, promise: terminalData.promise };
}
try {
const executeResult = { kind: TaskExecuteKind.Started, task, started: {}, promise: this.executeTask(task, resolver, trigger) };
executeResult.promise.then(summary => {
this.lastTask = this.currentTask;
});
if (InMemoryTask.is(task) || !this.isTaskEmpty(task)) {
if (!this.instances[recentTaskKey]) {
this.instances[recentTaskKey] = new InstanceManager();
}
this.instances[recentTaskKey].addInstance();
}
return executeResult;
} catch (error) {
if (error instanceof TaskError) {
throw error;
} else if (error instanceof Error) {
this.log(error.message);
throw new TaskError(Severity.Error, error.message, TaskErrors.UnknownError);
} else {
this.log(error.toString());
throw new TaskError(Severity.Error, nls.localize('TerminalTaskSystem.unknownError', 'A unknown error has occurred while executing a task. See task output log for details.'), TaskErrors.UnknownError);
}
}
}
public rerun(): ITaskExecuteResult | undefined {
if (this.lastTask && this.lastTask.verify()) {
if ((this.lastTask.task.runOptions.reevaluateOnRerun !== undefined) && !this.lastTask.task.runOptions.reevaluateOnRerun) {
this.isRerun = true;
}
const result = this.run(this.lastTask.task, this.lastTask.resolver);
result.promise.then(summary => {
this.isRerun = false;
});
return result;
} else {
return undefined;
}
}
public isTaskVisible(task: Task): boolean {
let terminalData = this.activeTasks[task.getMapKey()];
if (!terminalData) {
return false;
}
const activeTerminalInstance = this.terminalService.getActiveInstance();
const isPanelShowingTerminal = !!this.viewsService.getActiveViewWithId(TERMINAL_VIEW_ID);
return isPanelShowingTerminal && (activeTerminalInstance?.id === terminalData.terminal.id);
}
public revealTask(task: Task): boolean {
let terminalData = this.activeTasks[task.getMapKey()];
if (!terminalData) {
return false;
}
const isTerminalInPanel: boolean = this.viewDescriptorService.getViewLocationById(TERMINAL_VIEW_ID) === ViewContainerLocation.Panel;
if (isTerminalInPanel && this.isTaskVisible(task)) {
if (this.previousPanelId) {
if (this.previousTerminalInstance) {
this.terminalService.setActiveInstance(this.previousTerminalInstance);
}
this.panelService.openPanel(this.previousPanelId);
} else {
this.panelService.hideActivePanel();
}
this.previousPanelId = undefined;
this.previousTerminalInstance = undefined;
} else {
if (isTerminalInPanel) {
this.previousPanelId = this.panelService.getActivePanel()?.getId();
if (this.previousPanelId === TERMINAL_VIEW_ID) {
this.previousTerminalInstance = this.terminalService.getActiveInstance() ?? undefined;
}
}
this.terminalService.setActiveInstance(terminalData.terminal);
if (CustomTask.is(task) || ContributedTask.is(task)) {
this.terminalService.showPanel(task.command.presentation!.focus);
}
}
return true;
}
public isActive(): Promise<boolean> {
return Promise.resolve(this.isActiveSync());
}
public isActiveSync(): boolean {
return Object.keys(this.activeTasks).length > 0;
}
public canAutoTerminate(): boolean {
return Object.keys(this.activeTasks).every(key => !this.activeTasks[key].task.configurationProperties.promptOnClose);
}
public getActiveTasks(): Task[] {
return Object.keys(this.activeTasks).map(key => this.activeTasks[key].task);
}
public getLastInstance(task: Task): Task | undefined {
let lastInstance = undefined;
const recentKey = task.getRecentlyUsedKey();
Object.keys(this.activeTasks).forEach((key) => {
if (recentKey && recentKey === this.activeTasks[key].task.getRecentlyUsedKey()) {
lastInstance = this.activeTasks[key].task;
}
});
return lastInstance;
}
public getBusyTasks(): Task[] {
return Object.keys(this.busyTasks).map(key => this.busyTasks[key]);
}
public customExecutionComplete(task: Task, result: number): Promise<void> {
let activeTerminal = this.activeTasks[task.getMapKey()];
if (!activeTerminal) {
return Promise.reject(new Error('Expected to have a terminal for an custom execution task'));
}
return new Promise<void>((resolve) => {
// activeTerminal.terminal.rendererExit(result);
resolve();
});
}
private removeInstances(task: Task) {
const recentTaskKey = task.getRecentlyUsedKey() ?? '';
if (this.instances[recentTaskKey]) {
this.instances[recentTaskKey].removeInstance();
if (this.instances[recentTaskKey].instances === 0) {
delete this.instances[recentTaskKey];
}
}
}
private removeFromActiveTasks(task: Task): void {
if (!this.activeTasks[task.getMapKey()]) {
return;
}
delete this.activeTasks[task.getMapKey()];
this.removeInstances(task);
}
public terminate(task: Task): Promise<TaskTerminateResponse> {
let activeTerminal = this.activeTasks[task.getMapKey()];
if (!activeTerminal) {
return Promise.resolve<TaskTerminateResponse>({ success: false, task: undefined });
}
return new Promise<TaskTerminateResponse>((resolve, reject) => {
let terminal = activeTerminal.terminal;
const onExit = terminal.onExit(() => {
let task = activeTerminal.task;
try {
onExit.dispose();
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Terminated, task));
} catch (error) {
// Do nothing.
}
resolve({ success: true, task: task });
});
terminal.dispose();
});
}
public terminateAll(): Promise<TaskTerminateResponse[]> {
let promises: Promise<TaskTerminateResponse>[] = [];
Object.keys(this.activeTasks).forEach((key) => {
let terminalData = this.activeTasks[key];
let terminal = terminalData.terminal;
promises.push(new Promise<TaskTerminateResponse>((resolve, reject) => {
const onExit = terminal.onExit(() => {
let task = terminalData.task;
try {
onExit.dispose();
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Terminated, task));
} catch (error) {
// Do nothing.
}
resolve({ success: true, task: terminalData.task });
});
}));
terminal.dispose();
});
this.activeTasks = Object.create(null);
return Promise.all<TaskTerminateResponse>(promises);
}
private async executeTask(task: Task, resolver: ITaskResolver, trigger: string, alreadyResolved?: Map<string, string>): Promise<ITaskSummary> {
alreadyResolved = alreadyResolved ?? new Map<string, string>();
let promises: Promise<ITaskSummary>[] = [];
if (task.configurationProperties.dependsOn) {
for (const dependency of task.configurationProperties.dependsOn) {
let dependencyTask = await resolver.resolve(dependency.uri, dependency.task!);
if (dependencyTask) {
let key = dependencyTask.getMapKey();
let promise = this.activeTasks[key] ? this.activeTasks[key].promise : undefined;
if (!promise) {
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.DependsOnStarted, task));
promise = this.executeTask(dependencyTask, resolver, trigger, alreadyResolved);
}
promises.push(promise);
if (task.configurationProperties.dependsOrder === DependsOrder.sequence) {
const promiseResult = await promise;
if (promiseResult.exitCode === 0) {
promise = Promise.resolve(promiseResult);
} else {
promise = Promise.reject(promiseResult);
break;
}
}
promises.push(promise);
} else {
this.log(nls.localize('dependencyFailed',
'Couldn\'t resolve dependent task \'{0}\' in workspace folder \'{1}\'',
Types.isString(dependency.task) ? dependency.task : JSON.stringify(dependency.task, undefined, 0),
dependency.uri.toString()
));
this.showOutput();
}
}
}
if ((ContributedTask.is(task) || CustomTask.is(task)) && (task.command)) {
return Promise.all(promises).then((summaries): Promise<ITaskSummary> | ITaskSummary => {
for (let summary of summaries) {
if (summary.exitCode !== 0) {
this.removeInstances(task);
return { exitCode: summary.exitCode };
}
}
if (this.isRerun) {
return this.reexecuteCommand(task, trigger, alreadyResolved!);
} else {
return this.executeCommand(task, trigger, alreadyResolved!);
}
});
} else {
return Promise.all(promises).then((summaries): ITaskSummary => {
for (let summary of summaries) {
if (summary.exitCode !== 0) {
return { exitCode: summary.exitCode };
}
}
return { exitCode: 0 };
});
}
}
private resolveAndFindExecutable(workspaceFolder: IWorkspaceFolder | undefined, task: CustomTask | ContributedTask, cwd: string | undefined, envPath: string | undefined): Promise<string> {
return this.findExecutable(
this.configurationResolverService.resolve(workspaceFolder, CommandString.value(task.command.name!)),
cwd ? this.configurationResolverService.resolve(workspaceFolder, cwd) : undefined,
envPath ? envPath.split(path.delimiter).map(p => this.configurationResolverService.resolve(workspaceFolder, p)) : undefined
);
}
private findUnresolvedVariables(variables: Set<string>, alreadyResolved: Map<string, string>): Set<string> {
if (alreadyResolved.size === 0) {
return variables;
}
const unresolved = new Set<string>();
for (const variable of variables) {
if (!alreadyResolved.has(variable.substring(2, variable.length - 1))) {
unresolved.add(variable);
}
}
return unresolved;
}
private mergeMaps(mergeInto: Map<string, string>, mergeFrom: Map<string, string>) {
for (const entry of mergeFrom) {
if (!mergeInto.has(entry[0])) {
mergeInto.set(entry[0], entry[1]);
}
}
}
private resolveVariablesFromSet(taskSystemInfo: TaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder | undefined, task: CustomTask | ContributedTask, variables: Set<string>, alreadyResolved: Map<string, string>): Promise<ResolvedVariables> {
let isProcess = task.command && task.command.runtime === RuntimeType.Process;
let options = task.command && task.command.options ? task.command.options : undefined;
let cwd = options ? options.cwd : undefined;
let envPath: string | undefined = undefined;
if (options && options.env) {
for (let key of Object.keys(options.env)) {
if (key.toLowerCase() === 'path') {
if (Types.isString(options.env[key])) {
envPath = options.env[key];
}
break;
}
}
}
const unresolved = this.findUnresolvedVariables(variables, alreadyResolved);
let resolvedVariables: Promise<ResolvedVariables>;
if (taskSystemInfo && workspaceFolder) {
let resolveSet: ResolveSet = {
variables: unresolved
};
if (taskSystemInfo.platform === Platform.Platform.Windows && isProcess) {
resolveSet.process = { name: CommandString.value(task.command.name!) };
if (cwd) {
resolveSet.process.cwd = cwd;
}
if (envPath) {
resolveSet.process.path = envPath;
}
}
resolvedVariables = taskSystemInfo.resolveVariables(workspaceFolder, resolveSet, TaskSourceKind.toConfigurationTarget(task._source.kind)).then(async (resolved) => {
this.mergeMaps(alreadyResolved, resolved.variables);
resolved.variables = new Map(alreadyResolved);
if (isProcess) {
let process = CommandString.value(task.command.name!);
if (taskSystemInfo.platform === Platform.Platform.Windows) {
process = await this.resolveAndFindExecutable(workspaceFolder, task, cwd, envPath);
}
resolved.variables.set(TerminalTaskSystem.ProcessVarName, process);
}
return Promise.resolve(resolved);
});
return resolvedVariables;
} else {
let variablesArray = new Array<string>();
unresolved.forEach(variable => variablesArray.push(variable));
return new Promise((resolve, reject) => {
this.configurationResolverService.resolveWithInteraction(workspaceFolder, variablesArray, 'tasks', undefined, TaskSourceKind.toConfigurationTarget(task._source.kind)).then(async (resolvedVariablesMap: Map<string, string> | undefined) => {
if (resolvedVariablesMap) {
this.mergeMaps(alreadyResolved, resolvedVariablesMap);
resolvedVariablesMap = new Map(alreadyResolved);
if (isProcess) {
let processVarValue: string;
if (Platform.isWindows) {
processVarValue = await this.resolveAndFindExecutable(workspaceFolder, task, cwd, envPath);
} else {
processVarValue = this.configurationResolverService.resolve(workspaceFolder, CommandString.value(task.command.name!));
}
resolvedVariablesMap.set(TerminalTaskSystem.ProcessVarName, processVarValue);
}
let resolvedVariablesResult: ResolvedVariables = {
variables: resolvedVariablesMap,
};
resolve(resolvedVariablesResult);
} else {
resolve(undefined);
}
}, reason => {
reject(reason);
});
});
}
}
private executeCommand(task: CustomTask | ContributedTask, trigger: string, alreadyResolved: Map<string, string>): Promise<ITaskSummary> {
const taskWorkspaceFolder = task.getWorkspaceFolder();
let workspaceFolder: IWorkspaceFolder | undefined;
if (taskWorkspaceFolder) {
workspaceFolder = this.currentTask.workspaceFolder = taskWorkspaceFolder;
} else {
const folders = this.contextService.getWorkspace().folders;
workspaceFolder = folders.length > 0 ? folders[0] : undefined;
}
const systemInfo: TaskSystemInfo | undefined = this.currentTask.systemInfo = workspaceFolder ? this.taskSystemInfoResolver(workspaceFolder) : undefined;
let variables = new Set<string>();
this.collectTaskVariables(variables, task);
const resolvedVariables = this.resolveVariablesFromSet(systemInfo, workspaceFolder, task, variables, alreadyResolved);
return resolvedVariables.then((resolvedVariables) => {
if (resolvedVariables && !this.isTaskEmpty(task)) {
this.currentTask.resolvedVariables = resolvedVariables;
return this.executeInTerminal(task, trigger, new VariableResolver(workspaceFolder, systemInfo, resolvedVariables.variables, this.configurationResolverService), workspaceFolder);
} else {
// Allows the taskExecutions array to be updated in the extension host
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
return Promise.resolve({ exitCode: 0 });
}
}, reason => {
return Promise.reject(reason);
});
}
private isTaskEmpty(task: CustomTask | ContributedTask): boolean {
const isCustomExecution = (task.command.runtime === RuntimeType.CustomExecution);
return !((task.command !== undefined) && task.command.runtime && (isCustomExecution || (task.command.name !== undefined)));
}
private reexecuteCommand(task: CustomTask | ContributedTask, trigger: string, alreadyResolved: Map<string, string>): Promise<ITaskSummary> {
const lastTask = this.lastTask;
if (!lastTask) {
return Promise.reject(new Error('No task previously run'));
}
const workspaceFolder = this.currentTask.workspaceFolder = lastTask.workspaceFolder;
let variables = new Set<string>();
this.collectTaskVariables(variables, task);
// Check that the task hasn't changed to include new variables
let hasAllVariables = true;
variables.forEach(value => {
if (value.substring(2, value.length - 1) in lastTask.getVerifiedTask().resolvedVariables) {
hasAllVariables = false;
}
});
if (!hasAllVariables) {
return this.resolveVariablesFromSet(lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().workspaceFolder, task, variables, alreadyResolved).then((resolvedVariables) => {
this.currentTask.resolvedVariables = resolvedVariables;
return this.executeInTerminal(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, resolvedVariables.variables, this.configurationResolverService), workspaceFolder!);
}, reason => {
return Promise.reject(reason);
});
} else {
this.currentTask.resolvedVariables = lastTask.getVerifiedTask().resolvedVariables;
return this.executeInTerminal(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().resolvedVariables.variables, this.configurationResolverService), workspaceFolder!);
}
}
private async executeInTerminal(task: CustomTask | ContributedTask, trigger: string, resolver: VariableResolver, workspaceFolder: IWorkspaceFolder | undefined): Promise<ITaskSummary> {
let terminal: ITerminalInstance | undefined = undefined;
let executedCommand: string | undefined = undefined;
let error: TaskError | undefined = undefined;
let promise: Promise<ITaskSummary> | undefined = undefined;
if (task.configurationProperties.isBackground) {
const problemMatchers = this.resolveMatchers(resolver, task.configurationProperties.problemMatchers);
let watchingProblemMatcher = new WatchingProblemCollector(problemMatchers, this.markerService, this.modelService, this.fileService);
if ((problemMatchers.length > 0) && !watchingProblemMatcher.isWatching()) {
this.appendOutput(nls.localize('TerminalTaskSystem.nonWatchingMatcher', 'Task {0} is a background task but uses a problem matcher without a background pattern', task._label));
this.showOutput();
}
const toDispose = new DisposableStore();
let eventCounter: number = 0;
const mapKey = task.getMapKey();
toDispose.add(watchingProblemMatcher.onDidStateChange((event) => {
if (event.kind === ProblemCollectorEventKind.BackgroundProcessingBegins) {
eventCounter++;
this.busyTasks[mapKey] = task;
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task));
} else if (event.kind === ProblemCollectorEventKind.BackgroundProcessingEnds) {
eventCounter--;
if (this.busyTasks[mapKey]) {
delete this.busyTasks[mapKey];
}
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
if (eventCounter === 0) {
if ((watchingProblemMatcher.numberOfMatches > 0) && watchingProblemMatcher.maxMarkerSeverity &&
(watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error)) {
let reveal = task.command.presentation!.reveal;
let revealProblems = task.command.presentation!.revealProblems;
if (revealProblems === RevealProblemKind.OnProblem) {
this.viewsService.openView(Constants.MARKERS_VIEW_ID, true);
} else if (reveal === RevealKind.Silent) {
this.terminalService.setActiveInstance(terminal!);
this.terminalService.showPanel(false);
}
}
}
}
}));
watchingProblemMatcher.aboutToStart();
let delayer: Async.Delayer<any> | undefined = undefined;
[terminal, executedCommand, error] = await this.createTerminal(task, resolver, workspaceFolder);
if (error) {
return Promise.reject(new Error((<TaskError>error).message));
}
if (!terminal) {
return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`));
}
let processStartedSignaled = false;
terminal.processReady.then(() => {
if (!processStartedSignaled) {
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
processStartedSignaled = true;
}
}, (_error) => {
// The process never got ready. Need to think how to handle this.
});
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Start, task, terminal.id));
let skipLine: boolean = (!!task.command.presentation && task.command.presentation.echo);
const onData = terminal.onLineData((line) => {
if (skipLine) {
skipLine = false;
return;
}
watchingProblemMatcher.processLine(line);
if (!delayer) {
delayer = new Async.Delayer(3000);
}
delayer.trigger(() => {
watchingProblemMatcher.forceDelivery();
delayer = undefined;
});
});
promise = new Promise<ITaskSummary>((resolve, reject) => {
const onExit = terminal!.onExit((exitCode) => {
onData.dispose();
onExit.dispose();
let key = task.getMapKey();
if (this.busyTasks[mapKey]) {
delete this.busyTasks[mapKey];
}
this.removeFromActiveTasks(task);
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
if (exitCode !== undefined) {
// Only keep a reference to the terminal if it is not being disposed.
switch (task.command.presentation!.panel) {
case PanelKind.Dedicated:
this.sameTaskTerminals[key] = terminal!.id.toString();
break;
case PanelKind.Shared:
this.idleTaskTerminals.set(key, terminal!.id.toString(), Touch.AsOld);
break;
}
}
let reveal = task.command.presentation!.reveal;
if ((reveal === RevealKind.Silent) && ((exitCode !== 0) || (watchingProblemMatcher.numberOfMatches > 0) && watchingProblemMatcher.maxMarkerSeverity &&
(watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) {
this.terminalService.setActiveInstance(terminal!);
this.terminalService.showPanel(false);
}
watchingProblemMatcher.done();
watchingProblemMatcher.dispose();
if (!processStartedSignaled) {
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
processStartedSignaled = true;
}
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
for (let i = 0; i < eventCounter; i++) {
let event = TaskEvent.create(TaskEventKind.Inactive, task);
this._onDidStateChange.fire(event);
}
eventCounter = 0;
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
toDispose.dispose();
resolve({ exitCode });
});
});
} else {
[terminal, executedCommand, error] = await this.createTerminal(task, resolver, workspaceFolder);
if (error) {
return Promise.reject(new Error((<TaskError>error).message));
}
if (!terminal) {
return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`));
}
let processStartedSignaled = false;
terminal.processReady.then(() => {
if (!processStartedSignaled) {
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
processStartedSignaled = true;
}
}, (_error) => {
// The process never got ready. Need to think how to handle this.
});
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Start, task, terminal.id));
const mapKey = task.getMapKey();
this.busyTasks[mapKey] = task;
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task));
let problemMatchers = this.resolveMatchers(resolver, task.configurationProperties.problemMatchers);
let startStopProblemMatcher = new StartStopProblemCollector(problemMatchers, this.markerService, this.modelService, ProblemHandlingStrategy.Clean, this.fileService);
let skipLine: boolean = (!!task.command.presentation && task.command.presentation.echo);
const onData = terminal.onLineData((line) => {
if (skipLine) {
skipLine = false;
return;
}
startStopProblemMatcher.processLine(line);
});
promise = new Promise<ITaskSummary>((resolve, reject) => {
const onExit = terminal!.onExit((exitCode) => {
onData.dispose();
onExit.dispose();
let key = task.getMapKey();
this.removeFromActiveTasks(task);
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
if (exitCode !== undefined) {
// Only keep a reference to the terminal if it is not being disposed.
switch (task.command.presentation!.panel) {
case PanelKind.Dedicated:
this.sameTaskTerminals[key] = terminal!.id.toString();
break;
case PanelKind.Shared:
this.idleTaskTerminals.set(key, terminal!.id.toString(), Touch.AsOld);
break;
}
}
let reveal = task.command.presentation!.reveal;
let revealProblems = task.command.presentation!.revealProblems;
let revealProblemPanel = terminal && (revealProblems === RevealProblemKind.OnProblem) && (startStopProblemMatcher.numberOfMatches > 0);
if (revealProblemPanel) {
this.viewsService.openView(Constants.MARKERS_VIEW_ID);
} else if (terminal && (reveal === RevealKind.Silent) && ((exitCode !== 0) || (startStopProblemMatcher.numberOfMatches > 0) && startStopProblemMatcher.maxMarkerSeverity &&
(startStopProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) {
this.terminalService.setActiveInstance(terminal);
this.terminalService.showPanel(false);
}
startStopProblemMatcher.done();
startStopProblemMatcher.dispose();
if (!processStartedSignaled && terminal) {
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal.processId!));
processStartedSignaled = true;
}
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
if (this.busyTasks[mapKey]) {
delete this.busyTasks[mapKey];
}
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
resolve({ exitCode });
});
});
}
let showProblemPanel = task.command.presentation && (task.command.presentation.revealProblems === RevealProblemKind.Always);
if (showProblemPanel) {
this.viewsService.openView(Constants.MARKERS_VIEW_ID);
} else if (task.command.presentation && (task.command.presentation.reveal === RevealKind.Always)) {
this.terminalService.setActiveInstance(terminal);
this.terminalService.showPanel(task.command.presentation.focus);
}
this.activeTasks[task.getMapKey()] = { terminal, task, promise };
this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
return promise.then((summary) => {
try {
let telemetryEvent: TelemetryEvent = {
trigger: trigger,
runner: 'terminal',
taskKind: task.getTelemetryKind(),
command: this.getSanitizedCommand(executedCommand!),
success: true,
exitCode: summary.exitCode
};
/* __GDPR__
"taskService" : {
"${include}": [
"${TelemetryEvent}"
]
}
*/
this.telemetryService.publicLog(TerminalTaskSystem.TelemetryEventName, telemetryEvent);
} catch (error) {
}
return summary;
}, (error) => {
try {
let telemetryEvent: TelemetryEvent = {
trigger: trigger,
runner: 'terminal',
taskKind: task.getTelemetryKind(),
command: this.getSanitizedCommand(executedCommand!),
success: false
};
/* __GDPR__
"taskService" : {
"${include}": [
"${TelemetryEvent}"
]
}
*/
this.telemetryService.publicLog(TerminalTaskSystem.TelemetryEventName, telemetryEvent);
} catch (error) {
}
return Promise.reject<ITaskSummary>(error);
});
}
private createTerminalName(task: CustomTask | ContributedTask): string {
const needsFolderQualification = this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
return nls.localize('TerminalTaskSystem.terminalName', 'Task - {0}', needsFolderQualification ? task.getQualifiedLabel() : task.configurationProperties.name);
}
private async createShellLaunchConfig(task: CustomTask | ContributedTask, workspaceFolder: IWorkspaceFolder | undefined, variableResolver: VariableResolver, platform: Platform.Platform, options: CommandOptions, command: CommandString, args: CommandString[], waitOnExit: boolean | string): Promise<IShellLaunchConfig | undefined> {
let shellLaunchConfig: IShellLaunchConfig;
let isShellCommand = task.command.runtime === RuntimeType.Shell;
let needsFolderQualification = this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
let terminalName = this.createTerminalName(task);
let originalCommand = task.command.name;
if (isShellCommand) {
const defaultConfig = variableResolver.taskSystemInfo ? await variableResolver.taskSystemInfo.getDefaultShellAndArgs() : await this.terminalInstanceService.getDefaultShellAndArgs(true, platform);
shellLaunchConfig = { name: terminalName, executable: defaultConfig.shell, args: defaultConfig.args, waitOnExit };
let shellSpecified: boolean = false;
let shellOptions: ShellConfiguration | undefined = task.command.options && task.command.options.shell;
if (shellOptions) {
if (shellOptions.executable) {
shellLaunchConfig.executable = this.resolveVariable(variableResolver, shellOptions.executable);
shellSpecified = true;
}
if (shellOptions.args) {
shellLaunchConfig.args = this.resolveVariables(variableResolver, shellOptions.args.slice());
} else {
shellLaunchConfig.args = [];
}
}
let shellArgs = Array.isArray(shellLaunchConfig.args!) ? <string[]>shellLaunchConfig.args!.slice(0) : [shellLaunchConfig.args!];
let toAdd: string[] = [];
let commandLine = this.buildShellCommandLine(platform, shellLaunchConfig.executable!, shellOptions, command, originalCommand, args);
let windowsShellArgs: boolean = false;
if (platform === Platform.Platform.Windows) {
windowsShellArgs = true;
let basename = path.basename(shellLaunchConfig.executable!).toLowerCase();
// If we don't have a cwd, then the terminal uses the home dir.
const userHome = await this.pathService.userHome;
if (basename === 'cmd.exe' && ((options.cwd && isUNC(options.cwd)) || (!options.cwd && isUNC(userHome.fsPath)))) {
return undefined;
}
if ((basename === 'powershell.exe') || (basename === 'pwsh.exe')) {
if (!shellSpecified) {
toAdd.push('-Command');
}
} else if ((basename === 'bash.exe') || (basename === 'zsh.exe')) {
windowsShellArgs = false;
if (!shellSpecified) {
toAdd.push('-c');
}
} else if (basename === 'wsl.exe') {
if (!shellSpecified) {
toAdd.push('-e');
}
} else {
if (!shellSpecified) {
toAdd.push('/d', '/c');
}
}
} else {
if (!shellSpecified) {
// Under Mac remove -l to not start it as a login shell.
if (platform === Platform.Platform.Mac) {
let index = shellArgs.indexOf('-l');
if (index !== -1) {
shellArgs.splice(index, 1);
}
}
toAdd.push('-c');
}
}
toAdd.forEach(element => {
if (!shellArgs.some(arg => arg.toLowerCase() === element)) {
shellArgs.push(element);
}
});
shellArgs.push(commandLine);
shellLaunchConfig.args = windowsShellArgs ? shellArgs.join(' ') : shellArgs;
if (task.command.presentation && task.command.presentation.echo) {
if (needsFolderQualification && workspaceFolder) {
shellLaunchConfig.initialText = `\x1b[1m> Executing task in folder ${workspaceFolder.name}: ${commandLine} <\x1b[0m\n`;
} else {
shellLaunchConfig.initialText = `\x1b[1m> Executing task: ${commandLine} <\x1b[0m\n`;
}
}
} else {
let commandExecutable = (task.command.runtime !== RuntimeType.CustomExecution) ? CommandString.value(command) : undefined;
let executable = !isShellCommand
? this.resolveVariable(variableResolver, '${' + TerminalTaskSystem.ProcessVarName + '}')
: commandExecutable;
// When we have a process task there is no need to quote arguments. So we go ahead and take the string value.
shellLaunchConfig = {
name: terminalName,
executable: executable,
args: args.map(a => Types.isString(a) ? a : a.value),
waitOnExit
};
if (task.command.presentation && task.command.presentation.echo) {
let getArgsToEcho = (args: string | string[] | undefined): string => {
if (!args || args.length === 0) {
return '';
}
if (Types.isString(args)) {
return args;
}
return args.join(' ');
};
if (needsFolderQualification && workspaceFolder) {
shellLaunchConfig.initialText = `\x1b[1m> Executing task in folder ${workspaceFolder.name}: ${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)} <\x1b[0m\n`;
} else {
shellLaunchConfig.initialText = `\x1b[1m> Executing task: ${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)} <\x1b[0m\n`;
}
}
}
if (options.cwd) {
let cwd = options.cwd;
if (!path.isAbsolute(cwd)) {
if (workspaceFolder && (workspaceFolder.uri.scheme === 'file')) {
cwd = path.join(workspaceFolder.uri.fsPath, cwd);
}
}
// This must be normalized to the OS
shellLaunchConfig.cwd = resources.toLocalResource(URI.from({ scheme: Schemas.file, path: cwd }), this.environmentService.configuration.remoteAuthority);
}
if (options.env) {
shellLaunchConfig.env = options.env;
}
return shellLaunchConfig;
}
private async createTerminal(task: CustomTask | ContributedTask, resolver: VariableResolver, workspaceFolder: IWorkspaceFolder | undefined): Promise<[ITerminalInstance | undefined, string | undefined, TaskError | undefined]> {
let platform = resolver.taskSystemInfo ? resolver.taskSystemInfo.platform : Platform.platform;
let options = this.resolveOptions(resolver, task.command.options);
let waitOnExit: boolean | string = false;
const presentationOptions = task.command.presentation;
if (!presentationOptions) {
throw new Error('Task presentation options should not be undefined here.');
}
if (presentationOptions.reveal !== RevealKind.Never || !task.configurationProperties.isBackground) {
if (presentationOptions.panel === PanelKind.New) {
waitOnExit = nls.localize('closeTerminal', 'Press any key to close the terminal.');
} else if (presentationOptions.showReuseMessage) {
waitOnExit = nls.localize('reuseTerminal', 'Terminal will be reused by tasks, press any key to close it.');
} else {
waitOnExit = true;
}
}
let commandExecutable: string | undefined;
let command: CommandString | undefined;
let args: CommandString[] | undefined;
let launchConfigs: IShellLaunchConfig | undefined;
if (task.command.runtime === RuntimeType.CustomExecution) {
this.currentTask.shellLaunchConfig = launchConfigs = {
isExtensionTerminal: true,
waitOnExit,
name: this.createTerminalName(task),
initialText: task.command.presentation && task.command.presentation.echo ? `\x1b[1m> Executing task: ${task._label} <\x1b[0m\n` : undefined
};
} else {
let resolvedResult: { command: CommandString, args: CommandString[] } = this.resolveCommandAndArgs(resolver, task.command);
command = resolvedResult.command;
args = resolvedResult.args;
commandExecutable = CommandString.value(command);
this.currentTask.shellLaunchConfig = launchConfigs = (this.isRerun && this.lastTask) ? this.lastTask.getVerifiedTask().shellLaunchConfig : await this.createShellLaunchConfig(task, workspaceFolder, resolver, platform, options, command, args, waitOnExit);
if (launchConfigs === undefined) {
return [undefined, undefined, new TaskError(Severity.Error, nls.localize('TerminalTaskSystem', 'Can\'t execute a shell command on an UNC drive using cmd.exe.'), TaskErrors.UnknownError)];
}
}
let prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated;
let allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared;
let group = presentationOptions.group;
let taskKey = task.getMapKey();
let terminalToReuse: TerminalData | undefined;
if (prefersSameTerminal) {
let terminalId = this.sameTaskTerminals[taskKey];
if (terminalId) {
terminalToReuse = this.terminals[terminalId];
delete this.sameTaskTerminals[taskKey];
}
} else if (allowsSharedTerminal) {
// Always allow to reuse the terminal previously used by the same task.
let terminalId = this.idleTaskTerminals.remove(taskKey);
if (!terminalId) {
// There is no idle terminal which was used by the same task.
// Search for any idle terminal used previously by a task of the same group
// (or, if the task has no group, a terminal used by a task without group).
for (const taskId of this.idleTaskTerminals.keys()) {
const idleTerminalId = this.idleTaskTerminals.get(taskId)!;
if (idleTerminalId && this.terminals[idleTerminalId] && this.terminals[idleTerminalId].group === group) {
terminalId = this.idleTaskTerminals.remove(taskId);
break;
}
}
}
if (terminalId) {
terminalToReuse = this.terminals[terminalId];
}
}
if (terminalToReuse) {
if (!launchConfigs) {
throw new Error('Task shell launch configuration should not be undefined here.');
}
terminalToReuse.terminal.scrollToBottom();
terminalToReuse.terminal.reuseTerminal(launchConfigs);
if (task.command.presentation && task.command.presentation.clear) {
terminalToReuse.terminal.clear();
}
this.terminals[terminalToReuse.terminal.id.toString()].lastTask = taskKey;
return [terminalToReuse.terminal, commandExecutable, undefined];
}
let result: ITerminalInstance | null = null;
if (group) {
// Try to find an existing terminal to split.
// Even if an existing terminal is found, the split can fail if the terminal width is too small.
for (const terminal of values(this.terminals)) {
if (terminal.group === group) {
const originalInstance = terminal.terminal;
await originalInstance.waitForTitle();
result = this.terminalService.splitInstance(originalInstance, launchConfigs);
if (result) {
break;
}
}
}
}
if (!result) {
// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.
result = this.terminalService.createTerminal(launchConfigs);
}
const terminalKey = result.id.toString();
result.onDisposed((terminal) => {
let terminalData = this.terminals[terminalKey];
if (terminalData) {
delete this.terminals[terminalKey];
delete this.sameTaskTerminals[terminalData.lastTask];
this.idleTaskTerminals.delete(terminalData.lastTask);
// Delete the task now as a work around for cases when the onExit isn't fired.
// This can happen if the terminal wasn't shutdown with an "immediate" flag and is expected.
// For correct terminal re-use, the task needs to be deleted immediately.
// Note that this shouldn't be a problem anymore since user initiated terminal kills are now immediate.
const mapKey = task.getMapKey();
this.removeFromActiveTasks(task);
if (this.busyTasks[mapKey]) {
delete this.busyTasks[mapKey];
}
}
});
this.terminals[terminalKey] = { terminal: result, lastTask: taskKey, group };
return [result, commandExecutable, undefined];
}
private buildShellCommandLine(platform: Platform.Platform, shellExecutable: string, shellOptions: ShellConfiguration | undefined, command: CommandString, originalCommand: CommandString | undefined, args: CommandString[]): string {
let basename = path.parse(shellExecutable).name.toLowerCase();
let shellQuoteOptions = this.getQuotingOptions(basename, shellOptions, platform);
function needsQuotes(value: string): boolean {
if (value.length >= 2) {
let first = value[0] === shellQuoteOptions.strong ? shellQuoteOptions.strong : value[0] === shellQuoteOptions.weak ? shellQuoteOptions.weak : undefined;
if (first === value[value.length - 1]) {
return false;
}
}
let quote: string | undefined;
for (let i = 0; i < value.length; i++) {
// We found the end quote.
let ch = value[i];
if (ch === quote) {
quote = undefined;
} else if (quote !== undefined) {
// skip the character. We are quoted.
continue;
} else if (ch === shellQuoteOptions.escape) {
// Skip the next character
i++;
} else if (ch === shellQuoteOptions.strong || ch === shellQuoteOptions.weak) {
quote = ch;
} else if (ch === ' ') {
return true;
}
}
return false;
}
function quote(value: string, kind: ShellQuoting): [string, boolean] {
if (kind === ShellQuoting.Strong && shellQuoteOptions.strong) {
return [shellQuoteOptions.strong + value + shellQuoteOptions.strong, true];
} else if (kind === ShellQuoting.Weak && shellQuoteOptions.weak) {
return [shellQuoteOptions.weak + value + shellQuoteOptions.weak, true];
} else if (kind === ShellQuoting.Escape && shellQuoteOptions.escape) {
if (Types.isString(shellQuoteOptions.escape)) {
return [value.replace(/ /g, shellQuoteOptions.escape + ' '), true];
} else {
let buffer: string[] = [];
for (let ch of shellQuoteOptions.escape.charsToEscape) {
buffer.push(`\\${ch}`);
}
let regexp: RegExp = new RegExp('[' + buffer.join(',') + ']', 'g');
let escapeChar = shellQuoteOptions.escape.escapeChar;
return [value.replace(regexp, (match) => escapeChar + match), true];
}
}
return [value, false];
}
function quoteIfNecessary(value: CommandString): [string, boolean] {
if (Types.isString(value)) {
if (needsQuotes(value)) {
return quote(value, ShellQuoting.Strong);
} else {
return [value, false];
}
} else {
return quote(value.value, value.quoting);
}
}
// If we have no args and the command is a string then use the command to stay backwards compatible with the old command line
// model. To allow variable resolving with spaces we do continue if the resolved value is different than the original one
// and the resolved one needs quoting.
if ((!args || args.length === 0) && Types.isString(command) && (command === originalCommand as string || needsQuotes(originalCommand as string))) {
return command;
}
let result: string[] = [];
let commandQuoted = false;
let argQuoted = false;
let value: string;
let quoted: boolean;
[value, quoted] = quoteIfNecessary(command);
result.push(value);
commandQuoted = quoted;
for (let arg of args) {
[value, quoted] = quoteIfNecessary(arg);
result.push(value);
argQuoted = argQuoted || quoted;
}
let commandLine = result.join(' ');
// There are special rules quoted command line in cmd.exe
if (platform === Platform.Platform.Windows) {
if (basename === 'cmd' && commandQuoted && argQuoted) {
commandLine = '"' + commandLine + '"';
} else if (basename === 'powershell' && commandQuoted) {
commandLine = '& ' + commandLine;
}
}
if (basename === 'cmd' && platform === Platform.Platform.Windows && commandQuoted && argQuoted) {
commandLine = '"' + commandLine + '"';
}
return commandLine;
}
private getQuotingOptions(shellBasename: string, shellOptions: ShellConfiguration | undefined, platform: Platform.Platform): ShellQuotingOptions {
if (shellOptions && shellOptions.quoting) {
return shellOptions.quoting;
}
return TerminalTaskSystem.shellQuotes[shellBasename] || TerminalTaskSystem.osShellQuotes[Platform.PlatformToString(platform)];
}
private collectTaskVariables(variables: Set<string>, task: CustomTask | ContributedTask): void {
if (task.command && task.command.name) {
this.collectCommandVariables(variables, task.command, task);
}
this.collectMatcherVariables(variables, task.configurationProperties.problemMatchers);
}
private collectCommandVariables(variables: Set<string>, command: CommandConfiguration, task: CustomTask | ContributedTask): void {
// The custom execution should have everything it needs already as it provided
// the callback.
if (command.runtime === RuntimeType.CustomExecution) {
return;
}
if (command.name === undefined) {
throw new Error('Command name should never be undefined here.');
}
this.collectVariables(variables, command.name);
if (command.args) {
command.args.forEach(arg => this.collectVariables(variables, arg));
}
// Try to get a scope.
const scope = (<ExtensionTaskSource>task._source).scope;
if (scope !== TaskScope.Global) {
variables.add('${workspaceFolder}');
}
if (command.options) {
let options = command.options;
if (options.cwd) {
this.collectVariables(variables, options.cwd);
}
const optionsEnv = options.env;
if (optionsEnv) {
Object.keys(optionsEnv).forEach((key) => {
let value: any = optionsEnv[key];
if (Types.isString(value)) {
this.collectVariables(variables, value);
}
});
}
if (options.shell) {
if (options.shell.executable) {
this.collectVariables(variables, options.shell.executable);
}
if (options.shell.args) {
options.shell.args.forEach(arg => this.collectVariables(variables, arg));
}
}
}
}
private collectMatcherVariables(variables: Set<string>, values: Array<string | ProblemMatcher> | undefined): void {
if (values === undefined || values === null || values.length === 0) {
return;
}
values.forEach((value) => {
let matcher: ProblemMatcher;
if (Types.isString(value)) {
if (value[0] === '$') {
matcher = ProblemMatcherRegistry.get(value.substring(1));
} else {
matcher = ProblemMatcherRegistry.get(value);
}
} else {
matcher = value;
}
if (matcher && matcher.filePrefix) {
this.collectVariables(variables, matcher.filePrefix);
}
});
}
private collectVariables(variables: Set<string>, value: string | CommandString): void {
let string: string = Types.isString(value) ? value : value.value;
let r = /\$\{(.*?)\}/g;
let matches: RegExpExecArray | null;
do {
matches = r.exec(string);
if (matches) {
variables.add(matches[0]);
}
} while (matches);
}
private resolveCommandAndArgs(resolver: VariableResolver, commandConfig: CommandConfiguration): { command: CommandString, args: CommandString[] } {
// First we need to use the command args:
let args: CommandString[] = commandConfig.args ? commandConfig.args.slice() : [];
args = this.resolveVariables(resolver, args);
let command: CommandString = this.resolveVariable(resolver, commandConfig.name);
return { command, args };
}
private resolveVariables(resolver: VariableResolver, value: string[]): string[];
private resolveVariables(resolver: VariableResolver, value: CommandString[]): CommandString[];
private resolveVariables(resolver: VariableResolver, value: CommandString[]): CommandString[] {
return value.map(s => this.resolveVariable(resolver, s));
}
private resolveMatchers(resolver: VariableResolver, values: Array<string | ProblemMatcher> | undefined): ProblemMatcher[] {
if (values === undefined || values === null || values.length === 0) {
return [];
}
let result: ProblemMatcher[] = [];
values.forEach((value) => {
let matcher: ProblemMatcher;
if (Types.isString(value)) {
if (value[0] === '$') {
matcher = ProblemMatcherRegistry.get(value.substring(1));
} else {
matcher = ProblemMatcherRegistry.get(value);
}
} else {
matcher = value;
}
if (!matcher) {
this.appendOutput(nls.localize('unknownProblemMatcher', 'Problem matcher {0} can\'t be resolved. The matcher will be ignored'));
return;
}
let taskSystemInfo: TaskSystemInfo | undefined = resolver.taskSystemInfo;
let hasFilePrefix = matcher.filePrefix !== undefined;
let hasUriProvider = taskSystemInfo !== undefined && taskSystemInfo.uriProvider !== undefined;
if (!hasFilePrefix && !hasUriProvider) {
result.push(matcher);
} else {
let copy = Objects.deepClone(matcher);
if (hasUriProvider && (taskSystemInfo !== undefined)) {
copy.uriProvider = taskSystemInfo.uriProvider;
}
if (hasFilePrefix) {
copy.filePrefix = this.resolveVariable(resolver, copy.filePrefix);
}
result.push(copy);
}
});
return result;
}
private resolveVariable(resolver: VariableResolver, value: string | undefined): string;
private resolveVariable(resolver: VariableResolver, value: CommandString | undefined): CommandString;
private resolveVariable(resolver: VariableResolver, value: CommandString | undefined): CommandString {
// TODO@Dirk Task.getWorkspaceFolder should return a WorkspaceFolder that is defined in workspace.ts
if (Types.isString(value)) {
return resolver.resolve(value);
} else if (value !== undefined) {
return {
value: resolver.resolve(value.value),
quoting: value.quoting
};
} else { // This should never happen
throw new Error('Should never try to resolve undefined.');
}
}
private resolveOptions(resolver: VariableResolver, options: CommandOptions | undefined): CommandOptions {
if (options === undefined || options === null) {
let cwd: string | undefined;
try {
cwd = this.resolveVariable(resolver, '${workspaceFolder}');
} catch (e) {
// No workspace
}
return { cwd };
}
let result: CommandOptions = Types.isString(options.cwd)
? { cwd: this.resolveVariable(resolver, options.cwd) }
: { cwd: this.resolveVariable(resolver, '${workspaceFolder}') };
if (options.env) {
result.env = Object.create(null);
Object.keys(options.env).forEach((key) => {
let value: any = options.env![key];
if (Types.isString(value)) {
result.env![key] = this.resolveVariable(resolver, value);
} else {
result.env![key] = value.toString();
}
});
}
return result;
}
private static WellKnowCommands: IStringDictionary<boolean> = {
'ant': true,
'cmake': true,
'eslint': true,
'gradle': true,
'grunt': true,
'gulp': true,
'jake': true,
'jenkins': true,
'jshint': true,
'make': true,
'maven': true,
'msbuild': true,
'msc': true,
'nmake': true,
'npm': true,
'rake': true,
'tsc': true,
'xbuild': true
};
public getSanitizedCommand(cmd: string): string {
let result = cmd.toLowerCase();
let index = result.lastIndexOf(path.sep);
if (index !== -1) {
result = result.substring(index + 1);
}
if (TerminalTaskSystem.WellKnowCommands[result]) {
return result;
}
return 'other';
}
private appendOutput(output: string): void {
const outputChannel = this.outputService.getChannel(this.outputChannelId);
if (outputChannel) {
outputChannel.append(output);
}
}
private async fileExists(path: string): Promise<boolean> {
const uri: URI = resources.toLocalResource(URI.from({ scheme: Schemas.file, path: path }), this.environmentService.configuration.remoteAuthority);
if (await this.fileService.exists(uri)) {
return !((await this.fileService.resolve(uri)).isDirectory);
}
return false;
}
private async findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string> {
// If we have an absolute path then we take it.
if (path.isAbsolute(command)) {
return command;
}
if (cwd === undefined) {
cwd = processCwd();
}
const dir = path.dirname(command);
if (dir !== '.') {
// We have a directory and the directory is relative (see above). Make the path absolute
// to the current working directory.
return path.join(cwd, command);
}
if (paths === undefined && Types.isString(processEnv.PATH)) {
paths = processEnv.PATH.split(path.delimiter);
}
// No PATH environment. Make path absolute to the cwd.
if (paths === undefined || paths.length === 0) {
return path.join(cwd, command);
}
// We have a simple file name. We get the path variable from the env
// and try to find the executable on the path.
for (let pathEntry of paths) {
// The path entry is absolute.
let fullPath: string;
if (path.isAbsolute(pathEntry)) {
fullPath = path.join(pathEntry, command);
} else {
fullPath = path.join(cwd, pathEntry, command);
}
if (await this.fileExists(fullPath)) {
return fullPath;
}
let withExtension = fullPath + '.com';
if (await this.fileExists(withExtension)) {
return withExtension;
}
withExtension = fullPath + '.exe';
if (await this.fileExists(withExtension)) {
return withExtension;
}
}
return path.join(cwd, command);
}
}
| src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00019529279961716384,
0.00017536069208290428,
0.00016517045150976628,
0.00017570436466485262,
0.0000029971929507155437
] |
{
"id": 6,
"code_window": [
"\n",
"\t\t\tlet regex = rule.regex;\n",
"\t\t\tlet regexSource = rule.regex.source;\n",
"\t\t\tif (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), regex.ignoreCase ? 'i' : '');\n",
"\t\t\t}\n",
"\n",
"\t\t\tlet result = line.search(regex);\n",
"\t\t\tif (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tlet flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchLexer.ts",
"type": "replace",
"edit_start_line_idx": 499
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.014793843030929565,
0.000734328234102577,
0.00015956313291098922,
0.00017201955779455602,
0.0021432312205433846
] |
{
"id": 6,
"code_window": [
"\n",
"\t\t\tlet regex = rule.regex;\n",
"\t\t\tlet regexSource = rule.regex.source;\n",
"\t\t\tif (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), regex.ignoreCase ? 'i' : '');\n",
"\t\t\t}\n",
"\n",
"\t\t\tlet result = line.search(regex);\n",
"\t\t\tif (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tlet flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchLexer.ts",
"type": "replace",
"edit_start_line_idx": 499
} | {
"name": "Solarized (dark)",
"tokenColors": [
{
"settings": {
"foreground": "#93A1A1"
}
},
{
"scope": ["meta.embedded", "source.groovy.embedded"],
"settings": {
"foreground": "#93A1A1"
}
},
{
"name": "Comment",
"scope": "comment",
"settings": {
"fontStyle": "italic",
"foreground": "#657B83"
}
},
{
"name": "String",
"scope": "string",
"settings": {
"foreground": "#2AA198"
}
},
{
"name": "Regexp",
"scope": "string.regexp",
"settings": {
"foreground": "#D30102"
}
},
{
"name": "Number",
"scope": "constant.numeric",
"settings": {
"foreground": "#D33682"
}
},
{
"name": "Variable",
"scope": [
"variable.language",
"variable.other"
],
"settings": {
"foreground": "#268BD2"
}
},
{
"name": "Keyword",
"scope": "keyword",
"settings": {
"foreground": "#859900"
}
},
{
"name": "Storage",
"scope": "storage",
"settings": {
"fontStyle": "bold",
"foreground": "#93A1A1"
}
},
{
"name": "Class name",
"scope": [
"entity.name.class",
"entity.name.type",
"entity.name.namespace",
"entity.name.scope-resolution"
],
"settings": {
"fontStyle": "",
"foreground": "#CB4B16"
}
},
{
"name": "Function name",
"scope": "entity.name.function",
"settings": {
"foreground": "#268BD2"
}
},
{
"name": "Variable start",
"scope": "punctuation.definition.variable",
"settings": {
"foreground": "#859900"
}
},
{
"name": "Embedded code markers",
"scope": [
"punctuation.section.embedded.begin",
"punctuation.section.embedded.end"
],
"settings": {
"foreground": "#D30102"
}
},
{
"name": "Built-in constant",
"scope": [
"constant.language",
"meta.preprocessor"
],
"settings": {
"foreground": "#B58900"
}
},
{
"name": "Support.construct",
"scope": [
"support.function.construct",
"keyword.other.new"
],
"settings": {
"foreground": "#CB4B16"
}
},
{
"name": "User-defined constant",
"scope": [
"constant.character",
"constant.other"
],
"settings": {
"foreground": "#CB4B16"
}
},
{
"name": "Inherited class",
"scope": "entity.other.inherited-class",
"settings": {
"foreground": "#6C71C4"
}
},
{
"name": "Function argument",
"scope": "variable.parameter",
"settings": {}
},
{
"name": "Tag name",
"scope": "entity.name.tag",
"settings": {
"foreground": "#268BD2"
}
},
{
"name": "Tag start/end",
"scope": "punctuation.definition.tag",
"settings": {
"foreground": "#657B83"
}
},
{
"name": "Tag attribute",
"scope": "entity.other.attribute-name",
"settings": {
"foreground": "#93A1A1"
}
},
{
"name": "Library function",
"scope": "support.function",
"settings": {
"foreground": "#268BD2"
}
},
{
"name": "Continuation",
"scope": "punctuation.separator.continuation",
"settings": {
"foreground": "#D30102"
}
},
{
"name": "Library constant",
"scope": "support.constant",
"settings": {}
},
{
"name": "Library class/type",
"scope": [
"support.type",
"support.class"
],
"settings": {
"foreground": "#859900"
}
},
{
"name": "Library Exception",
"scope": "support.type.exception",
"settings": {
"foreground": "#CB4B16"
}
},
{
"name": "Library variable",
"scope": "support.other.variable",
"settings": {}
},
{
"name": "Invalid",
"scope": "invalid",
"settings": {}
},
{
"name": "diff: header",
"scope": [
"meta.diff",
"meta.diff.header"
],
"settings": {
"fontStyle": "italic",
"foreground": "#E0EDDD"
}
},
{
"name": "diff: deleted",
"scope": "markup.deleted",
"settings": {
"fontStyle": "",
"foreground": "#dc322f"
}
},
{
"name": "diff: changed",
"scope": "markup.changed",
"settings": {
"fontStyle": "",
"foreground": "#cb4b16"
}
},
{
"name": "diff: inserted",
"scope": "markup.inserted",
"settings": {
"foreground": "#219186"
}
},
{
"name": "Markup Quote",
"scope": "markup.quote",
"settings": {
"foreground": "#859900"
}
},
{
"name": "Markup Lists",
"scope": "markup.list",
"settings": {
"foreground": "#B58900"
}
},
{
"name": "Markup Styling",
"scope": [
"markup.bold",
"markup.italic"
],
"settings": {
"foreground": "#D33682"
}
},
{
"name": "Markup Inline",
"scope": "markup.inline.raw",
"settings": {
"fontStyle": "",
"foreground": "#2AA198"
}
},
{
"name": "Markup Headings",
"scope": "markup.heading",
"settings": {
"foreground": "#268BD2"
}
},
{
"name": "Markup Setext Header",
"scope": "markup.heading.setext",
"settings": {
"fontStyle": "",
"foreground": "#268BD2"
}
}
],
"colors": {
// Base
// "foreground": "",
"focusBorder": "#2AA19899",
// "contrastActiveBorder": "",
// "contrastBorder": "",
// "widget.shadow": "",
"selection.background": "#2AA19899",
"input.background": "#003847",
"input.foreground": "#93A1A1",
"input.placeholderForeground": "#93A1A1AA",
// "input.border": "",
"inputOption.activeBorder": "#2AA19899",
"inputValidation.infoBorder": "#363b5f",
"inputValidation.infoBackground": "#052730",
"inputValidation.warningBackground": "#5d5938",
"inputValidation.warningBorder": "#9d8a5e",
"inputValidation.errorBackground": "#571b26",
"inputValidation.errorBorder": "#a92049",
"errorForeground": "#ffeaea",
"badge.background": "#047aa6",
"progressBar.background": "#047aa6",
"dropdown.background": "#00212B",
"dropdown.border": "#2AA19899",
// "dropdown.foreground": "",
"button.background": "#2AA19899",
// "button.foreground": "",
"list.activeSelectionBackground": "#005A6F",
// "list.activeSelectionForeground": "",
"list.focusBackground": "#005A6F",
"list.hoverBackground": "#004454AA",
"list.inactiveSelectionBackground": "#00445488",
"list.dropBackground": "#00445488",
"list.highlightForeground": "#1ebcc5",
// "scrollbar.shadow": "",
// "scrollbarSlider.activeBackground": "",
// "scrollbarSlider.background": "",
// "scrollbarSlider.hoverBackground": "",
// Editor
"editor.background": "#002B36",
// "editor.foreground": "#6688cc",
"editorWidget.background": "#00212B",
"editorCursor.foreground": "#D30102",
"editorWhitespace.foreground": "#93A1A180",
"editor.lineHighlightBackground": "#073642",
"editorLineNumber.activeForeground": "#949494",
"editor.selectionBackground": "#274642",
"minimap.selectionHighlight": "#274642",
"editorIndentGuide.background": "#93A1A180",
"editorIndentGuide.activeBackground": "#C3E1E180",
"editorHoverWidget.background": "#004052",
// "editorHoverWidget.border": "",
// "editorLineNumber.foreground": "",
// "editorMarkerNavigation.background": "",
"editorMarkerNavigationError.background": "#AB395B",
"editorMarkerNavigationWarning.background": "#5B7E7A",
// "editorLink.activeForeground": "",
// "editor.findMatchBackground": "",
// "editor.findMatchHighlightBackground": "",
// "editor.findRangeHighlightBackground": "",
// "editor.hoverHighlightBackground": "",
// "editor.inactiveSelectionBackground": "",
// "editor.lineHighlightBorder": "",
// "editor.rangeHighlightBackground": "",
"editor.selectionHighlightBackground": "#005A6FAA",
"editor.wordHighlightBackground": "#004454AA",
"editor.wordHighlightStrongBackground": "#005A6FAA",
// Editor: Suggest
// "editorSuggestWidget.background": "",
// "editorSuggestWidget.border": "",
// "editorSuggestWidget.foreground": "",
// "editorSuggestWidget.highlightForeground": "",
// "editorSuggestWidget.selectedBackground": "",
// Editor: Peek View
"peekViewResult.background": "#00212B",
// "peekViewResult.lineForeground": "",
// "peekViewResult.selectionBackground": "",
// "peekViewResult.selectionForeground": "",
"peekViewEditor.background": "#10192c",
"peekViewTitle.background": "#00212B",
"peekView.border": "#2b2b4a",
"peekViewEditor.matchHighlightBackground": "#7744AA40",
// "peekViewResult.fileForeground": "",
// "peekViewResult.matchHighlightBackground": "",
// "peekViewTitleLabel.foreground": "",
// "peekViewTitleDescription.foreground": "",
// Editor: Diff
// "diffEditor.insertedTextBackground": "",
// "diffEditor.insertedTextBorder": "",
// "diffEditor.removedTextBackground": "",
// "diffEditor.removedTextBorder": "",
// Workbench: Title
"titleBar.activeBackground": "#002C39",
// "titleBar.inactiveBackground": "",
// "titleBar.activeForeground": "",
// "titleBar.inactiveForeground": "",
// Workbench: Editors
// "editorGroupHeader.noTabsBackground": "",
"editorGroup.border": "#00212B",
"editorGroup.dropBackground": "#2AA19844",
"editorGroupHeader.tabsBackground": "#004052",
// Workbench: Tabs
"tab.activeForeground": "#d6dbdb",
"tab.activeBackground": "#002B37",
"tab.inactiveForeground": "#93A1A1",
"tab.inactiveBackground": "#004052",
"tab.border": "#003847",
// Workbench: Activity Bar
"activityBar.background": "#003847",
// "activityBarBadge.background": "",
// "activityBar.dropBackground": "",
// "activityBar.foreground": "",
// "activityBarBadge.foreground": "",
// Workbench: Panel
// "panel.background": "",
"panel.border": "#2b2b4a",
// "panelTitle.activeBorder": "",
// "panelTitle.activeForeground": "",
// "panelTitle.inactiveForeground": "",
// Workbench: Side Bar
"sideBar.background": "#00212B",
"sideBarTitle.foreground": "#93A1A1",
// "sideBarSectionHeader.background": "",
// Workbench: Status Bar
"statusBar.foreground": "#93A1A1",
"statusBar.background": "#00212B",
"statusBar.debuggingBackground": "#00212B",
"statusBar.noFolderBackground": "#00212B",
"statusBarItem.remoteBackground": "#2AA19899",
"statusBarItem.prominentBackground": "#003847",
"statusBarItem.prominentHoverBackground": "#003847",
// "statusBarItem.activeBackground": "",
// "statusBarItem.hoverBackground": "",
// Workbench: Debug
"debugToolBar.background": "#00212B",
"debugExceptionWidget.background": "#00212B",
"debugExceptionWidget.border": "#AB395B",
// Workbench: Quick Open
"pickerGroup.foreground": "#2AA19899",
"pickerGroup.border": "#2AA19899",
// Workbench: Terminal
// Colors sourced from the official palette http://ethanschoonover.com/solarized
"terminal.ansiBlack": "#073642",
"terminal.ansiRed": "#dc322f",
"terminal.ansiGreen": "#859900",
"terminal.ansiYellow": "#b58900",
"terminal.ansiBlue": "#268bd2",
"terminal.ansiMagenta": "#d33682",
"terminal.ansiCyan": "#2aa198",
"terminal.ansiWhite": "#eee8d5",
"terminal.ansiBrightBlack": "#586e75",
"terminal.ansiBrightRed": "#cb4b16",
"terminal.ansiBrightGreen": "#586e75",
"terminal.ansiBrightYellow": "#657b83",
"terminal.ansiBrightBlue": "#839496",
"terminal.ansiBrightMagenta": "#6c71c4",
"terminal.ansiBrightCyan": "#93a1a1",
"terminal.ansiBrightWhite": "#fdf6e3"
},
"semanticHighlighting": true
}
| extensions/theme-solarized-dark/themes/solarized-dark-color-theme.json | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017536123050376773,
0.00017308499081991613,
0.0001713630772428587,
0.0001731362281134352,
9.742474276208668e-7
] |
{
"id": 6,
"code_window": [
"\n",
"\t\t\tlet regex = rule.regex;\n",
"\t\t\tlet regexSource = rule.regex.source;\n",
"\t\t\tif (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), regex.ignoreCase ? 'i' : '');\n",
"\t\t\t}\n",
"\n",
"\t\t\tlet result = line.search(regex);\n",
"\t\t\tif (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tlet flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchLexer.ts",
"type": "replace",
"edit_start_line_idx": 499
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Command } from 'vs/editor/common/modes';
import { UriComponents, URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { RawContextKey, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey';
import { localize } from 'vs/nls';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IDisposable, Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { values, keys, getOrSet } from 'vs/base/common/map';
import { Registry } from 'vs/platform/registry/common/platform';
import { IKeybindings } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IAction, IActionViewItem } from 'vs/base/common/actions';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { flatten, mergeSort } from 'vs/base/common/arrays';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { SetMap } from 'vs/base/common/collections';
import { IProgressIndicator } from 'vs/platform/progress/common/progress';
import Severity from 'vs/base/common/severity';
import { IPaneComposite } from 'vs/workbench/common/panecomposite';
import { IAccessibilityInformation } from 'vs/platform/accessibility/common/accessibility';
export const TEST_VIEW_CONTAINER_ID = 'workbench.view.extension.test';
export namespace Extensions {
export const ViewContainersRegistry = 'workbench.registry.view.containers';
export const ViewsRegistry = 'workbench.registry.view';
}
export enum ViewContainerLocation {
Sidebar,
Panel
}
export interface IViewContainerDescriptor {
readonly id: string;
readonly name: string;
readonly ctorDescriptor: SyncDescriptor<IViewPaneContainer>;
readonly storageId?: string;
readonly icon?: string | URI;
readonly alwaysUseContainerInfo?: boolean;
readonly focusCommand?: { id: string, keybindings?: IKeybindings };
readonly viewOrderDelegate?: ViewOrderDelegate;
readonly hideIfEmpty?: boolean;
readonly extensionId?: ExtensionIdentifier;
readonly rejectAddedViews?: boolean;
order?: number;
}
export interface IViewContainersRegistry {
/**
* An event that is triggered when a view container is registered.
*/
readonly onDidRegister: Event<{ viewContainer: ViewContainer, viewContainerLocation: ViewContainerLocation }>;
/**
* An event that is triggered when a view container is deregistered.
*/
readonly onDidDeregister: Event<{ viewContainer: ViewContainer, viewContainerLocation: ViewContainerLocation }>;
/**
* All registered view containers
*/
readonly all: ViewContainer[];
/**
* Registers a view container to given location.
* No op if a view container is already registered.
*
* @param viewContainerDescriptor descriptor of view container
* @param location location of the view container
*
* @returns the registered ViewContainer.
*/
registerViewContainer(viewContainerDescriptor: IViewContainerDescriptor, location: ViewContainerLocation, isDefault?: boolean): ViewContainer;
/**
* Deregisters the given view container
* No op if the view container is not registered
*/
deregisterViewContainer(viewContainer: ViewContainer): void;
/**
* Returns the view container with given id.
*
* @returns the view container with given id.
*/
get(id: string): ViewContainer | undefined;
/**
* Returns all view containers in the given location
*/
getViewContainers(location: ViewContainerLocation): ViewContainer[];
/**
* Returns the view container location
*/
getViewContainerLocation(container: ViewContainer): ViewContainerLocation;
/**
* Return the default view container from the given location
*/
getDefaultViewContainer(location: ViewContainerLocation): ViewContainer | undefined;
}
interface ViewOrderDelegate {
getOrder(group?: string): number | undefined;
}
export interface ViewContainer extends IViewContainerDescriptor { }
class ViewContainersRegistryImpl extends Disposable implements IViewContainersRegistry {
private readonly _onDidRegister = this._register(new Emitter<{ viewContainer: ViewContainer, viewContainerLocation: ViewContainerLocation }>());
readonly onDidRegister: Event<{ viewContainer: ViewContainer, viewContainerLocation: ViewContainerLocation }> = this._onDidRegister.event;
private readonly _onDidDeregister = this._register(new Emitter<{ viewContainer: ViewContainer, viewContainerLocation: ViewContainerLocation }>());
readonly onDidDeregister: Event<{ viewContainer: ViewContainer, viewContainerLocation: ViewContainerLocation }> = this._onDidDeregister.event;
private readonly viewContainers: Map<ViewContainerLocation, ViewContainer[]> = new Map<ViewContainerLocation, ViewContainer[]>();
private readonly defaultViewContainers: ViewContainer[] = [];
get all(): ViewContainer[] {
return flatten(values(this.viewContainers));
}
registerViewContainer(viewContainerDescriptor: IViewContainerDescriptor, viewContainerLocation: ViewContainerLocation, isDefault?: boolean): ViewContainer {
const existing = this.get(viewContainerDescriptor.id);
if (existing) {
return existing;
}
const viewContainer: ViewContainer = viewContainerDescriptor;
const viewContainers = getOrSet(this.viewContainers, viewContainerLocation, []);
viewContainers.push(viewContainer);
if (isDefault) {
this.defaultViewContainers.push(viewContainer);
}
this._onDidRegister.fire({ viewContainer, viewContainerLocation });
return viewContainer;
}
deregisterViewContainer(viewContainer: ViewContainer): void {
for (const viewContainerLocation of keys(this.viewContainers)) {
const viewContainers = this.viewContainers.get(viewContainerLocation)!;
const index = viewContainers?.indexOf(viewContainer);
if (index !== -1) {
viewContainers?.splice(index, 1);
if (viewContainers.length === 0) {
this.viewContainers.delete(viewContainerLocation);
}
this._onDidDeregister.fire({ viewContainer, viewContainerLocation });
return;
}
}
}
get(id: string): ViewContainer | undefined {
return this.all.filter(viewContainer => viewContainer.id === id)[0];
}
getViewContainers(location: ViewContainerLocation): ViewContainer[] {
return [...(this.viewContainers.get(location) || [])];
}
getViewContainerLocation(container: ViewContainer): ViewContainerLocation {
return keys(this.viewContainers).filter(location => this.getViewContainers(location).filter(viewContainer => viewContainer.id === container.id).length > 0)[0];
}
getDefaultViewContainer(location: ViewContainerLocation): ViewContainer | undefined {
return this.defaultViewContainers.find(viewContainer => this.getViewContainerLocation(viewContainer) === location);
}
}
Registry.add(Extensions.ViewContainersRegistry, new ViewContainersRegistryImpl());
export interface IViewDescriptor {
readonly id: string;
readonly name: string;
readonly ctorDescriptor: SyncDescriptor<IView>;
readonly when?: ContextKeyExpression;
readonly order?: number;
readonly weight?: number;
readonly collapsed?: boolean;
readonly canToggleVisibility?: boolean;
readonly canMoveView?: boolean;
readonly containerIcon?: string | URI;
readonly containerTitle?: string;
// Applies only to newly created views
readonly hideByDefault?: boolean;
readonly workspace?: boolean;
readonly focusCommand?: { id: string, keybindings?: IKeybindings };
// For contributed remote explorer views
readonly group?: string;
readonly remoteAuthority?: string | string[];
}
export interface IViewDescriptorRef {
viewDescriptor: IViewDescriptor;
index: number;
}
export interface IAddedViewDescriptorRef extends IViewDescriptorRef {
collapsed: boolean;
size?: number;
}
export interface IViewContainerModel {
readonly title: string;
readonly icon: string | URI | undefined;
readonly onDidChangeContainerInfo: Event<{ title?: boolean, icon?: boolean }>;
readonly allViewDescriptors: ReadonlyArray<IViewDescriptor>;
readonly onDidChangeAllViewDescriptors: Event<{ added: ReadonlyArray<IViewDescriptor>, removed: ReadonlyArray<IViewDescriptor> }>;
readonly activeViewDescriptors: ReadonlyArray<IViewDescriptor>;
readonly onDidChangeActiveViewDescriptors: Event<{ added: ReadonlyArray<IViewDescriptor>, removed: ReadonlyArray<IViewDescriptor> }>;
readonly visibleViewDescriptors: ReadonlyArray<IViewDescriptor>;
readonly onDidAddVisibleViewDescriptors: Event<IAddedViewDescriptorRef[]>;
readonly onDidRemoveVisibleViewDescriptors: Event<IViewDescriptorRef[]>
readonly onDidMoveVisibleViewDescriptors: Event<{ from: IViewDescriptorRef; to: IViewDescriptorRef; }>
isVisible(id: string): boolean;
setVisible(id: string, visible: boolean, size?: number): void;
isCollapsed(id: string): boolean;
setCollapsed(id: string, collapsed: boolean): void;
getSize(id: string): number | undefined;
setSize(id: string, size: number): void
move(from: string, to: string): void;
}
export enum ViewContentPriority {
Normal = 0,
Low = 1,
Lowest = 2
}
export interface IViewContentDescriptor {
readonly content: string;
readonly when?: ContextKeyExpression | 'default';
readonly priority?: ViewContentPriority;
/**
* ordered preconditions for each button in the content
*/
readonly preconditions?: (ContextKeyExpression | undefined)[];
}
export interface IViewsRegistry {
readonly onViewsRegistered: Event<{ views: IViewDescriptor[], viewContainer: ViewContainer }[]>;
readonly onViewsDeregistered: Event<{ views: IViewDescriptor[], viewContainer: ViewContainer }>;
readonly onDidChangeContainer: Event<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }>;
registerViews(views: IViewDescriptor[], viewContainer: ViewContainer): void;
registerViews2(views: { views: IViewDescriptor[], viewContainer: ViewContainer }[]): void;
deregisterViews(views: IViewDescriptor[], viewContainer: ViewContainer): void;
moveViews(views: IViewDescriptor[], viewContainer: ViewContainer): void;
getViews(viewContainer: ViewContainer): IViewDescriptor[];
getView(id: string): IViewDescriptor | null;
getViewContainer(id: string): ViewContainer | null;
readonly onDidChangeViewWelcomeContent: Event<string>;
registerViewWelcomeContent(id: string, viewContent: IViewContentDescriptor): IDisposable;
getViewWelcomeContent(id: string): IViewContentDescriptor[];
}
function compareViewContentDescriptors(a: IViewContentDescriptor, b: IViewContentDescriptor): number {
const aPriority = a.priority ?? ViewContentPriority.Normal;
const bPriority = b.priority ?? ViewContentPriority.Normal;
if (aPriority !== bPriority) {
return aPriority - bPriority;
}
// No priroity, keep views sorted in the order they got registered
return 0;
}
class ViewsRegistry extends Disposable implements IViewsRegistry {
private readonly _onViewsRegistered = this._register(new Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }[]>());
readonly onViewsRegistered = this._onViewsRegistered.event;
private readonly _onViewsDeregistered: Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }> = this._register(new Emitter<{ views: IViewDescriptor[], viewContainer: ViewContainer }>());
readonly onViewsDeregistered: Event<{ views: IViewDescriptor[], viewContainer: ViewContainer }> = this._onViewsDeregistered.event;
private readonly _onDidChangeContainer: Emitter<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }> = this._register(new Emitter<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }>());
readonly onDidChangeContainer: Event<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }> = this._onDidChangeContainer.event;
private readonly _onDidChangeViewWelcomeContent: Emitter<string> = this._register(new Emitter<string>());
readonly onDidChangeViewWelcomeContent: Event<string> = this._onDidChangeViewWelcomeContent.event;
private _viewContainers: ViewContainer[] = [];
private _views: Map<ViewContainer, IViewDescriptor[]> = new Map<ViewContainer, IViewDescriptor[]>();
private _viewWelcomeContents = new SetMap<string, IViewContentDescriptor>();
registerViews(views: IViewDescriptor[], viewContainer: ViewContainer): void {
this.registerViews2([{ views, viewContainer }]);
}
registerViews2(views: { views: IViewDescriptor[], viewContainer: ViewContainer }[]): void {
views.forEach(({ views, viewContainer }) => this.addViews(views, viewContainer));
this._onViewsRegistered.fire(views);
}
deregisterViews(viewDescriptors: IViewDescriptor[], viewContainer: ViewContainer): void {
const views = this.removeViews(viewDescriptors, viewContainer);
if (views.length) {
this._onViewsDeregistered.fire({ views, viewContainer });
}
}
moveViews(viewsToMove: IViewDescriptor[], viewContainer: ViewContainer): void {
keys(this._views).forEach(container => {
if (container !== viewContainer) {
const views = this.removeViews(viewsToMove, container);
if (views.length) {
this.addViews(views, viewContainer);
this._onDidChangeContainer.fire({ views, from: container, to: viewContainer });
}
}
});
}
getViews(loc: ViewContainer): IViewDescriptor[] {
return this._views.get(loc) || [];
}
getView(id: string): IViewDescriptor | null {
for (const viewContainer of this._viewContainers) {
const viewDescriptor = (this._views.get(viewContainer) || []).filter(v => v.id === id)[0];
if (viewDescriptor) {
return viewDescriptor;
}
}
return null;
}
getViewContainer(viewId: string): ViewContainer | null {
for (const viewContainer of this._viewContainers) {
const viewDescriptor = (this._views.get(viewContainer) || []).filter(v => v.id === viewId)[0];
if (viewDescriptor) {
return viewContainer;
}
}
return null;
}
registerViewWelcomeContent(id: string, viewContent: IViewContentDescriptor): IDisposable {
this._viewWelcomeContents.add(id, viewContent);
this._onDidChangeViewWelcomeContent.fire(id);
return toDisposable(() => {
this._viewWelcomeContents.delete(id, viewContent);
this._onDidChangeViewWelcomeContent.fire(id);
});
}
getViewWelcomeContent(id: string): IViewContentDescriptor[] {
const result: IViewContentDescriptor[] = [];
this._viewWelcomeContents.forEach(id, descriptor => result.push(descriptor));
mergeSort(result, compareViewContentDescriptors);
return result;
}
private addViews(viewDescriptors: IViewDescriptor[], viewContainer: ViewContainer): void {
let views = this._views.get(viewContainer);
if (!views) {
views = [];
this._views.set(viewContainer, views);
this._viewContainers.push(viewContainer);
}
for (const viewDescriptor of viewDescriptors) {
if (this.getView(viewDescriptor.id) !== null) {
throw new Error(localize('duplicateId', "A view with id '{0}' is already registered", viewDescriptor.id));
}
views.push(viewDescriptor);
}
}
private removeViews(viewDescriptors: IViewDescriptor[], viewContainer: ViewContainer): IViewDescriptor[] {
const views = this._views.get(viewContainer);
if (!views) {
return [];
}
const viewsToDeregister: IViewDescriptor[] = [];
const remaningViews: IViewDescriptor[] = [];
for (const view of views) {
if (viewDescriptors.indexOf(view) === -1) {
remaningViews.push(view);
} else {
viewsToDeregister.push(view);
}
}
if (viewsToDeregister.length) {
if (remaningViews.length) {
this._views.set(viewContainer, remaningViews);
} else {
this._views.delete(viewContainer);
this._viewContainers.splice(this._viewContainers.indexOf(viewContainer), 1);
}
}
return viewsToDeregister;
}
}
Registry.add(Extensions.ViewsRegistry, new ViewsRegistry());
export interface IView {
readonly id: string;
isVisible(): boolean;
isBodyVisible(): boolean;
setExpanded(expanded: boolean): boolean;
getProgressIndicator(): IProgressIndicator | undefined;
}
export const IViewsService = createDecorator<IViewsService>('viewsService');
export interface IViewsService {
_serviceBrand: undefined;
// View Container APIs
readonly onDidChangeViewContainerVisibility: Event<{ id: string, visible: boolean, location: ViewContainerLocation }>;
isViewContainerVisible(id: string): boolean;
openViewContainer(id: string, focus?: boolean): Promise<IPaneComposite | null>;
closeViewContainer(id: string): void;
getVisibleViewContainer(location: ViewContainerLocation): ViewContainer | null;
// View APIs
readonly onDidChangeViewVisibility: Event<{ id: string, visible: boolean }>;
isViewVisible(id: string): boolean;
openView<T extends IView>(id: string, focus?: boolean): Promise<T | null>;
closeView(id: string): void;
getActiveViewWithId<T extends IView>(id: string): T | null;
getViewProgressIndicator(id: string): IProgressIndicator | undefined;
}
/**
* View Contexts
*/
export const FocusedViewContext = new RawContextKey<string>('focusedView', '');
export function getVisbileViewContextKey(viewId: string): string { return `${viewId}.visible`; }
export const IViewDescriptorService = createDecorator<IViewDescriptorService>('viewDescriptorService');
export interface IViewDescriptorService {
_serviceBrand: undefined;
// ViewContainers
readonly viewContainers: ReadonlyArray<ViewContainer>;
readonly onDidChangeViewContainers: Event<{ added: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation }>, removed: ReadonlyArray<{ container: ViewContainer, location: ViewContainerLocation }> }>;
getDefaultViewContainer(location: ViewContainerLocation): ViewContainer | undefined;
getViewContainerById(id: string): ViewContainer | null;
getDefaultViewContainerLocation(viewContainer: ViewContainer): ViewContainerLocation | null;
getViewContainerLocation(viewContainer: ViewContainer): ViewContainerLocation | null;
getViewContainersByLocation(location: ViewContainerLocation): ViewContainer[];
getViewContainerModel(viewContainer: ViewContainer): IViewContainerModel;
readonly onDidChangeContainerLocation: Event<{ viewContainer: ViewContainer, from: ViewContainerLocation, to: ViewContainerLocation }>;
moveViewContainerToLocation(viewContainer: ViewContainer, location: ViewContainerLocation, order?: number): void;
// Views
getViewDescriptorById(id: string): IViewDescriptor | null;
getViewContainerByViewId(id: string): ViewContainer | null;
getDefaultContainerById(id: string): ViewContainer | null;
getViewLocationById(id: string): ViewContainerLocation | null;
readonly onDidChangeContainer: Event<{ views: IViewDescriptor[], from: ViewContainer, to: ViewContainer }>;
moveViewsToContainer(views: IViewDescriptor[], viewContainer: ViewContainer): void;
readonly onDidChangeLocation: Event<{ views: IViewDescriptor[], from: ViewContainerLocation, to: ViewContainerLocation }>;
moveViewToLocation(view: IViewDescriptor, location: ViewContainerLocation): void;
}
// Custom views
export interface ITreeView extends IDisposable {
dataProvider: ITreeViewDataProvider | undefined;
showCollapseAllAction: boolean;
canSelectMany: boolean;
message?: string;
title: string;
readonly visible: boolean;
readonly onDidExpandItem: Event<ITreeItem>;
readonly onDidCollapseItem: Event<ITreeItem>;
readonly onDidChangeSelection: Event<ITreeItem[]>;
readonly onDidChangeVisibility: Event<boolean>;
readonly onDidChangeActions: Event<void>;
readonly onDidChangeTitle: Event<string>;
readonly onDidChangeWelcomeState: Event<void>;
refresh(treeItems?: ITreeItem[]): Promise<void>;
setVisibility(visible: boolean): void;
focus(): void;
layout(height: number, width: number): void;
getOptimalWidth(): number;
reveal(item: ITreeItem): Promise<void>;
expand(itemOrItems: ITreeItem | ITreeItem[]): Promise<void>;
setSelection(items: ITreeItem[]): void;
setFocus(item: ITreeItem): void;
}
export interface IRevealOptions {
select?: boolean;
focus?: boolean;
expand?: boolean | number;
}
export interface ITreeViewDescriptor extends IViewDescriptor {
treeView: ITreeView;
}
export type TreeViewItemHandleArg = {
$treeViewId: string,
$treeItemHandle: string
};
export enum TreeItemCollapsibleState {
None = 0,
Collapsed = 1,
Expanded = 2
}
export interface ITreeItemLabel {
label: string;
highlights?: [number, number][];
}
export interface ITreeItem {
handle: string;
parentHandle?: string;
collapsibleState: TreeItemCollapsibleState;
label?: ITreeItemLabel;
description?: string | boolean;
icon?: UriComponents;
iconDark?: UriComponents;
themeIcon?: ThemeIcon;
resourceUri?: UriComponents;
tooltip?: string;
contextValue?: string;
command?: Command;
children?: ITreeItem[];
accessibilityInformation?: IAccessibilityInformation;
}
export interface ITreeViewDataProvider {
readonly isTreeEmpty?: boolean;
onDidChangeEmpty?: Event<void>;
getChildren(element?: ITreeItem): Promise<ITreeItem[]>;
}
export interface IEditableData {
validationMessage: (value: string) => { content: string, severity: Severity } | null;
placeholder?: string | null;
startingValue?: string | null;
onFinish: (value: string, success: boolean) => Promise<void>;
}
export interface IViewPaneContainer {
onDidAddViews: Event<IView[]>;
onDidRemoveViews: Event<IView[]>;
onDidChangeViewVisibility: Event<IView>;
readonly views: IView[];
setVisible(visible: boolean): void;
isVisible(): boolean;
focus(): void;
getActions(): IAction[];
getSecondaryActions(): IAction[];
getActionViewItem(action: IAction): IActionViewItem | undefined;
getView(viewId: string): IView | undefined;
saveState(): void;
}
| src/vs/workbench/common/views.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.0001774073316482827,
0.000172995452885516,
0.00015763574629090726,
0.00017337873578071594,
0.000002749458417383721
] |
{
"id": 6,
"code_window": [
"\n",
"\t\t\tlet regex = rule.regex;\n",
"\t\t\tlet regexSource = rule.regex.source;\n",
"\t\t\tif (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), regex.ignoreCase ? 'i' : '');\n",
"\t\t\t}\n",
"\n",
"\t\t\tlet result = line.search(regex);\n",
"\t\t\tif (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tlet flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');\n",
"\t\t\t\tregex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchLexer.ts",
"type": "replace",
"edit_start_line_idx": 499
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event, Emitter } from 'vs/base/common/event';
import { Registry } from 'vs/platform/registry/common/platform';
import { URI } from 'vs/base/common/uri';
export const Extensions = {
OutputChannels: 'workbench.contributions.outputChannels'
};
export interface IOutputChannelDescriptor {
id: string;
label: string;
log: boolean;
file?: URI;
}
export interface IFileOutputChannelDescriptor extends IOutputChannelDescriptor {
file: URI;
}
export interface IOutputChannelRegistry {
readonly onDidRegisterChannel: Event<string>;
readonly onDidRemoveChannel: Event<string>;
/**
* Make an output channel known to the output world.
*/
registerChannel(descriptor: IOutputChannelDescriptor): void;
/**
* Returns the list of channels known to the output world.
*/
getChannels(): IOutputChannelDescriptor[];
/**
* Returns the channel with the passed id.
*/
getChannel(id: string): IOutputChannelDescriptor | undefined;
/**
* Remove the output channel with the passed id.
*/
removeChannel(id: string): void;
}
class OutputChannelRegistry implements IOutputChannelRegistry {
private channels = new Map<string, IOutputChannelDescriptor>();
private readonly _onDidRegisterChannel = new Emitter<string>();
readonly onDidRegisterChannel: Event<string> = this._onDidRegisterChannel.event;
private readonly _onDidRemoveChannel = new Emitter<string>();
readonly onDidRemoveChannel: Event<string> = this._onDidRemoveChannel.event;
public registerChannel(descriptor: IOutputChannelDescriptor): void {
if (!this.channels.has(descriptor.id)) {
this.channels.set(descriptor.id, descriptor);
this._onDidRegisterChannel.fire(descriptor.id);
}
}
public getChannels(): IOutputChannelDescriptor[] {
const result: IOutputChannelDescriptor[] = [];
this.channels.forEach(value => result.push(value));
return result;
}
public getChannel(id: string): IOutputChannelDescriptor | undefined {
return this.channels.get(id);
}
public removeChannel(id: string): void {
this.channels.delete(id);
this._onDidRemoveChannel.fire(id);
}
}
Registry.add(Extensions.OutputChannels, new OutputChannelRegistry());
| src/vs/workbench/services/output/common/output.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017547397874295712,
0.00017176539404317737,
0.00016348168719559908,
0.00017340105841867626,
0.0000034091171983163804
] |
{
"id": 7,
"code_window": [
"\t/**\n",
"\t * is the language case insensitive?\n",
"\t */\n",
"\tignoreCase?: boolean;\n",
"\t/**\n",
"\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t */\n",
"\tdefaultToken?: string;\n",
"\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t */\n",
"\tunicode?: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchTypes.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module only exports 'compile' which compiles a JSON language definition
* into a typed and checked ILexer definition.
*/
import * as monarchCommon from 'vs/editor/standalone/common/monarch/monarchCommon';
import { IMonarchLanguage, IMonarchLanguageBracket } from 'vs/editor/standalone/common/monarch/monarchTypes';
/*
* Type helpers
*
* Note: this is just for sanity checks on the JSON description which is
* helpful for the programmer. No checks are done anymore once the lexer is
* already 'compiled and checked'.
*
*/
function isArrayOf(elemType: (x: any) => boolean, obj: any): boolean {
if (!obj) {
return false;
}
if (!(Array.isArray(obj))) {
return false;
}
for (const el of obj) {
if (!(elemType(el))) {
return false;
}
}
return true;
}
function bool(prop: any, defValue: boolean): boolean {
if (typeof prop === 'boolean') {
return prop;
}
return defValue;
}
function string(prop: any, defValue: string): string {
if (typeof (prop) === 'string') {
return prop;
}
return defValue;
}
function arrayToHash(array: string[]): { [name: string]: true } {
const result: any = {};
for (const e of array) {
result[e] = true;
}
return result;
}
function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
// Lexer helpers
/**
* Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set.
* Also replaces @\w+ or sequences with the content of the specified attribute
*/
function compileRegExp(lexer: monarchCommon.ILexerMin, str: string): RegExp {
let n = 0;
while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions
n++;
str = str.replace(/@(\w+)/g, function (s, attr?) {
let sub = '';
if (typeof (lexer[attr]) === 'string') {
sub = lexer[attr];
} else if (lexer[attr] && lexer[attr] instanceof RegExp) {
sub = lexer[attr].source;
} else {
if (lexer[attr] === undefined) {
throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
} else {
throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
}
}
return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')');
});
}
return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));
}
/**
* Compiles guard functions for case matches.
* This compiles 'cases' attributes into efficient match functions.
*
*/
function selectScrutinee(id: string, matches: string[], state: string, num: number): string | null {
if (num < 0) {
return id;
}
if (num < matches.length) {
return matches[num];
}
if (num >= 100) {
num = num - 100;
let parts = state.split('.');
parts.unshift(state);
if (num < parts.length) {
return parts[num];
}
}
return null;
}
function createGuard(lexer: monarchCommon.ILexerMin, ruleName: string, tkey: string, val: monarchCommon.FuzzyAction): monarchCommon.IBranch {
// get the scrutinee and pattern
let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
let oppat = tkey;
let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
if (matches) {
if (matches[3]) { // if digits
scrut = parseInt(matches[3]);
if (matches[2]) {
scrut = scrut + 100; // if [sS] present
}
}
oppat = matches[4];
}
// get operator
let op = '~';
let pat = oppat;
if (!oppat || oppat.length === 0) {
op = '!=';
pat = '';
}
else if (/^\w*$/.test(pat)) { // just a word
op = '==';
}
else {
matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
if (matches) {
op = matches[1];
pat = matches[2];
}
}
// set the tester function
let tester: (s: string, id: string, matches: string[], state: string, eos: boolean) => boolean;
// special case a regexp that matches just words
if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
let inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
}
else if (op === '@' || op === '!@') {
let words = lexer[pat];
if (!words) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
}
if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
}
let inWords = createKeywordMatcher(words, lexer.ignoreCase);
tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
}
else if (op === '~' || op === '!~') {
if (pat.indexOf('$') < 0) {
// precompile regular expression
let re = compileRegExp(lexer, '^' + pat + '$');
tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
}
else {
tester = function (s, id, matches, state) {
let re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$');
return re.test(s);
};
}
}
else { // if (op==='==' || op==='!=') {
if (pat.indexOf('$') < 0) {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
}
else {
let patx = monarchCommon.fixCase(lexer, pat);
tester = function (s, id, matches, state, eos) {
let patexp = monarchCommon.substituteMatches(lexer, patx, id, matches, state);
return (op === '==' ? s === patexp : s !== patexp);
};
}
}
// return the branch object
if (scrut === -1) {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
return tester(id, id, matches, state, eos);
}
};
}
else {
return {
name: tkey, value: val, test: function (id, matches, state, eos) {
let scrutinee = selectScrutinee(id, matches, state, scrut);
return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
}
};
}
}
/**
* Compiles an action: i.e. optimize regular expressions and case matches
* and do many sanity checks.
*
* This is called only during compilation but if the lexer definition
* contains user functions as actions (which is usually not allowed), then this
* may be called during lexing. It is important therefore to compile common cases efficiently
*/
function compileAction(lexer: monarchCommon.ILexerMin, ruleName: string, action: any): monarchCommon.FuzzyAction {
if (!action) {
return { token: '' };
}
else if (typeof (action) === 'string') {
return action; // { token: action };
}
else if (action.token || action.token === '') {
if (typeof (action.token) !== 'string') {
throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
}
else {
// only copy specific typed fields (only happens once during compile Lexer)
let newAction: monarchCommon.IAction = { token: action.token };
if (action.token.indexOf('$') >= 0) {
newAction.tokenSubst = true;
}
if (typeof (action.bracket) === 'string') {
if (action.bracket === '@open') {
newAction.bracket = monarchCommon.MonarchBracket.Open;
} else if (action.bracket === '@close') {
newAction.bracket = monarchCommon.MonarchBracket.Close;
} else {
throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
}
}
if (action.next) {
if (typeof (action.next) !== 'string') {
throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
}
else {
let next: string = action.next;
if (!/^(@pop|@push|@popall)$/.test(next)) {
if (next[0] === '@') {
next = next.substr(1); // peel off starting @ sign
}
if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) {
throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
}
}
}
newAction.next = next;
}
}
if (typeof (action.goBack) === 'number') {
newAction.goBack = action.goBack;
}
if (typeof (action.switchTo) === 'string') {
newAction.switchTo = action.switchTo;
}
if (typeof (action.log) === 'string') {
newAction.log = action.log;
}
if (typeof (action.nextEmbedded) === 'string') {
newAction.nextEmbedded = action.nextEmbedded;
lexer.usesEmbedded = true;
}
return newAction;
}
}
else if (Array.isArray(action)) {
let results: monarchCommon.FuzzyAction[] = [];
for (let i = 0, len = action.length; i < len; i++) {
results[i] = compileAction(lexer, ruleName, action[i]);
}
return { group: results };
}
else if (action.cases) {
// build an array of test cases
let cases: monarchCommon.IBranch[] = [];
// for each case, push a test function and result value
for (let tkey in action.cases) {
if (action.cases.hasOwnProperty(tkey)) {
const val = compileAction(lexer, ruleName, action.cases[tkey]);
// what kind of case
if (tkey === '@default' || tkey === '@' || tkey === '') {
cases.push({ test: undefined, value: val, name: tkey });
}
else if (tkey === '@eos') {
cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
}
else {
cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
}
}
}
// create a matching function
const def = lexer.defaultToken;
return {
test: function (id, matches, state, eos) {
for (const _case of cases) {
const didmatch = (!_case.test || _case.test(id, matches, state, eos));
if (didmatch) {
return _case.value;
}
}
return def;
}
};
}
else {
throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
}
}
/**
* Helper class for creating matching rules
*/
class Rule implements monarchCommon.IRule {
public regex: RegExp = new RegExp('');
public action: monarchCommon.FuzzyAction = { token: '' };
public matchOnlyAtLineStart: boolean = false;
public name: string = '';
constructor(name: string) {
this.name = name;
}
public setRegex(lexer: monarchCommon.ILexerMin, re: string | RegExp): void {
let sregex: string;
if (typeof (re) === 'string') {
sregex = re;
}
else if (re instanceof RegExp) {
sregex = (<RegExp>re).source;
}
else {
throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
}
this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
this.name = this.name + ': ' + sregex;
this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
}
public setAction(lexer: monarchCommon.ILexerMin, act: monarchCommon.IAction) {
this.action = compileAction(lexer, this.name, act);
}
}
/**
* Compiles a json description function into json where all regular expressions,
* case matches etc, are compiled and all include rules are expanded.
* We also compile the bracket definitions, supply defaults, and do many sanity checks.
* If the 'jsonStrict' parameter is 'false', we allow at certain locations
* regular expression objects and functions that get called during lexing.
* (Currently we have no samples that need this so perhaps we should always have
* jsonStrict to true).
*/
export function compile(languageId: string, json: IMonarchLanguage): monarchCommon.ILexer {
if (!json || typeof (json) !== 'object') {
throw new Error('Monarch: expecting a language definition object');
}
// Create our lexer
let lexer: monarchCommon.ILexer = <monarchCommon.ILexer>{};
lexer.languageId = languageId;
lexer.noThrow = false; // raise exceptions during compilation
lexer.maxStack = 100;
// Set standard fields: be defensive about types
lexer.start = (typeof json.start === 'string' ? json.start : null);
lexer.ignoreCase = bool(json.ignoreCase, false);
lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
lexer.defaultToken = string(json.defaultToken, 'source');
lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
// For calling compileAction later on
let lexerMin: monarchCommon.ILexerMin = <any>json;
lexerMin.languageId = languageId;
lexerMin.ignoreCase = lexer.ignoreCase;
lexerMin.noThrow = lexer.noThrow;
lexerMin.usesEmbedded = lexer.usesEmbedded;
lexerMin.stateNames = json.tokenizer;
lexerMin.defaultToken = lexer.defaultToken;
// Compile an array of rules into newrules where RegExp objects are created.
function addRules(state: string, newrules: monarchCommon.IRule[], rules: any[]) {
for (const rule of rules) {
let include = rule.include;
if (include) {
if (typeof (include) !== 'string') {
throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
}
if (include[0] === '@') {
include = include.substr(1); // peel off starting @
}
if (!json.tokenizer[include]) {
throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
}
addRules(state + '.' + include, newrules, json.tokenizer[include]);
}
else {
const newrule = new Rule(state);
// Set up new rule attributes
if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
newrule.setRegex(lexerMin, rule[0]);
if (rule.length >= 3) {
if (typeof (rule[1]) === 'string') {
newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
}
else if (typeof (rule[1]) === 'object') {
const rule1 = rule[1];
rule1.next = rule[2];
newrule.setAction(lexerMin, rule1);
}
else {
throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
}
}
else {
newrule.setAction(lexerMin, rule[1]);
}
}
else {
if (!rule.regex) {
throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
}
if (rule.name) {
if (typeof rule.name === 'string') {
newrule.name = rule.name;
}
}
if (rule.matchOnlyAtStart) {
newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
}
newrule.setRegex(lexerMin, rule.regex);
newrule.setAction(lexerMin, rule.action);
}
newrules.push(newrule);
}
}
}
// compile the tokenizer rules
if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
}
lexer.tokenizer = <any>[];
for (let key in json.tokenizer) {
if (json.tokenizer.hasOwnProperty(key)) {
if (!lexer.start) {
lexer.start = key;
}
const rules = json.tokenizer[key];
lexer.tokenizer[key] = new Array();
addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
}
}
lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
// Set simple brackets
if (json.brackets) {
if (!(Array.isArray(<any>json.brackets))) {
throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array');
}
}
else {
json.brackets = [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }];
}
let brackets: IMonarchLanguageBracket[] = [];
for (let el of json.brackets) {
let desc: any = el;
if (desc && Array.isArray(desc) && desc.length === 3) {
desc = { token: desc[2], open: desc[0], close: desc[1] };
}
if (desc.open === desc.close) {
throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
'\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
}
if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
brackets.push({
token: desc.token + lexer.tokenPostfix,
open: monarchCommon.fixCase(lexer, desc.open),
close: monarchCommon.fixCase(lexer, desc.close)
});
}
else {
throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
}
}
lexer.brackets = brackets;
// Disable throw so the syntax highlighter goes, no matter what
lexer.noThrow = true;
return lexer;
}
| src/vs/editor/standalone/common/monarch/monarchCompile.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.9984534978866577,
0.07319062948226929,
0.00016250273620244116,
0.0001730406074784696,
0.2571280300617218
] |
{
"id": 7,
"code_window": [
"\t/**\n",
"\t * is the language case insensitive?\n",
"\t */\n",
"\tignoreCase?: boolean;\n",
"\t/**\n",
"\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t */\n",
"\tdefaultToken?: string;\n",
"\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t */\n",
"\tunicode?: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchTypes.ts",
"type": "add",
"edit_start_line_idx": 23
} | cgmanifest.json
| extensions/theme-kimbie-dark/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017855828627943993,
0.00017855828627943993,
0.00017855828627943993,
0.00017855828627943993,
0
] |
{
"id": 7,
"code_window": [
"\t/**\n",
"\t * is the language case insensitive?\n",
"\t */\n",
"\tignoreCase?: boolean;\n",
"\t/**\n",
"\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t */\n",
"\tdefaultToken?: string;\n",
"\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t */\n",
"\tunicode?: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchTypes.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/platform/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IActivityBarService } from 'vs/workbench/services/activityBar/browser/activityBarService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { language } from 'vs/base/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
import { configurationTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { ITextFileService, ITextFileSaveEvent, ITextFileLoadEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { guessMimeTypes } from 'vs/base/common/mime';
import { hash } from 'vs/base/common/hash';
type TelemetryData = {
mimeType: string;
ext: string;
path: number;
reason?: number;
whitelistedjson?: string;
};
type FileTelemetryDataFragment = {
mimeType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
ext: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
path: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
reason?: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
whitelistedjson?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
export class TelemetryContribution extends Disposable implements IWorkbenchContribution {
private static WHITELIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
private static WHITELIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IActivityBarService activityBarService: IActivityBarService,
@ILifecycleService lifecycleService: ILifecycleService,
@IEditorService editorService: IEditorService,
@IKeybindingService keybindingsService: IKeybindingService,
@IWorkbenchThemeService themeService: IWorkbenchThemeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IConfigurationService configurationService: IConfigurationService,
@IViewletService viewletService: IViewletService,
@ITextFileService textFileService: ITextFileService
) {
super();
const { filesToOpenOrCreate, filesToDiff } = environmentService.configuration;
const activeViewlet = viewletService.getActiveViewlet();
type WindowSizeFragment = {
innerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
innerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerHeight: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
outerWidth: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadClassification = {
userAgent: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
emptyWorkbench: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
windowSize: WindowSizeFragment;
'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
'workbench.filesToDiff': { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
customKeybindingsCount: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
theme: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
language: { classification: 'SystemMetaData', purpose: 'BusinessInsight' };
pinnedViewlets: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredViewlet?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
restoredEditors: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
startupKind: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
};
type WorkspaceLoadEvent = {
userAgent: string;
windowSize: { innerHeight: number, innerWidth: number, outerHeight: number, outerWidth: number };
emptyWorkbench: boolean;
'workbench.filesToOpenOrCreate': number;
'workbench.filesToDiff': number;
customKeybindingsCount: number;
theme: string;
language: string;
pinnedViewlets: string[];
restoredViewlet?: string;
restoredEditors: number;
startupKind: StartupKind;
};
telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', {
userAgent: navigator.userAgent,
windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth },
emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY,
'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0,
customKeybindingsCount: keybindingsService.customKeybindingsCount(),
theme: themeService.getColorTheme().id,
language,
pinnedViewlets: activityBarService.getPinnedViewContainerIds(),
restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined,
restoredEditors: editorService.visibleEditors.length,
startupKind: lifecycleService.startupKind
});
// Error Telemetry
this._register(new ErrorTelemetry(telemetryService));
// Configuration Telemetry
this._register(configurationTelemetry(telemetryService, configurationService));
// Files Telemetry
this._register(textFileService.files.onDidLoad(e => this.onTextFileModelLoaded(e)));
this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e)));
// Lifecycle
this._register(lifecycleService.onShutdown(() => this.dispose()));
}
private onTextFileModelLoaded(e: ITextFileLoadEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsReadClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
} else {
type FileGetClassification = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason));
}
}
private onTextFileModelSaved(e: ITextFileSaveEvent): void {
const settingsType = this.getTypeIfSettings(e.model.resource);
if (settingsType) {
type SettingsWrittenClassification = {
settingsType: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
} else {
type FilePutClassfication = {} & FileTelemetryDataFragment;
this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason));
}
}
private getTypeIfSettings(resource: URI): string {
if (extname(resource) !== '.json') {
return '';
}
// Check for global settings file
if (isEqual(resource, this.environmentService.settingsResource)) {
return 'global-settings';
}
// Check for keybindings file
if (isEqual(resource, this.environmentService.keybindingsResource)) {
return 'keybindings';
}
// Check for snippets
if (isEqualOrParent(resource, this.environmentService.snippetsHome)) {
return 'snippets';
}
// Check for workspace settings file
const folders = this.contextService.getWorkspace().folders;
for (const folder of folders) {
if (isEqualOrParent(resource, folder.toResource('.vscode'))) {
const filename = basename(resource);
if (TelemetryContribution.WHITELIST_WORKSPACE_JSON.indexOf(filename) > -1) {
return `.vscode/${filename}`;
}
}
}
return '';
}
private getTelemetryData(resource: URI, reason?: number): TelemetryData {
const ext = extname(resource);
const fileName = basename(resource);
const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
const telemetryData = {
mimeType: guessMimeTypes(resource).join(', '),
ext,
path: hash(path),
reason,
whitelistedjson: undefined as string | undefined
};
if (ext === '.json' && TelemetryContribution.WHITELIST_JSON.indexOf(fileName) > -1) {
telemetryData['whitelistedjson'] = fileName;
}
return telemetryData;
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);
| src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.0001775266428012401,
0.00017148384358733892,
0.00016556923219468445,
0.0001711956865619868,
0.0000030554833756468724
] |
{
"id": 7,
"code_window": [
"\t/**\n",
"\t * is the language case insensitive?\n",
"\t */\n",
"\tignoreCase?: boolean;\n",
"\t/**\n",
"\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t */\n",
"\tdefaultToken?: string;\n",
"\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t */\n",
"\tunicode?: boolean;\n"
],
"file_path": "src/vs/editor/standalone/common/monarch/monarchTypes.ts",
"type": "add",
"edit_start_line_idx": 23
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const path = require('path');
const testRunner = require('vscode/lib/testrunner');
const suite = 'Integration Notebook Tests';
const options: any = {
ui: 'tdd',
useColors: (!process.env.BUILD_ARTIFACTSTAGINGDIRECTORY && process.platform !== 'win32'),
timeout: 60000
};
if (process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
options.reporter = 'mocha-multi-reporters';
options.reporterOptions = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
testsuitesTitle: `${suite} ${process.platform}`,
mochaFile: path.join(process.env.BUILD_ARTIFACTSTAGINGDIRECTORY, `test-results/${process.platform}-${suite.toLowerCase().replace(/[^\w]/g, '-')}-results.xml`)
}
};
}
testRunner.configure(options);
export = testRunner;
| extensions/vscode-notebook-tests/src/index.ts | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017942632257472724,
0.00017456036584917456,
0.00016633923223707825,
0.00017623795429244637,
0.000004922379957861267
] |
{
"id": 8,
"code_window": [
"\t\t};\n",
"\t\t/**\n",
"\t\t * is the language case insensitive?\n",
"\t\t */\n",
"\t\tignoreCase?: boolean;\n",
"\t\t/**\n",
"\t\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t\t */\n",
"\t\tdefaultToken?: string;\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t/**\n",
"\t\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t\t */\n",
"\t\tunicode?: boolean;\n"
],
"file_path": "src/vs/monaco.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
* This module exports common types and functionality shared between
* the Monarch compiler that compiles JSON to ILexer, and the Monarch
* Tokenizer (that highlights at runtime)
*/
/*
* Type definitions to be used internally to Monarch.
* Inside monarch we use fully typed definitions and compiled versions of the more abstract JSON descriptions.
*/
export const enum MonarchBracket {
None = 0,
Open = 1,
Close = -1
}
export interface ILexerMin {
languageId: string;
noThrow: boolean;
ignoreCase: boolean;
usesEmbedded: boolean;
defaultToken: string;
stateNames: { [stateName: string]: any; };
[attr: string]: any;
}
export interface ILexer extends ILexerMin {
maxStack: number;
start: string | null;
ignoreCase: boolean;
tokenPostfix: string;
tokenizer: { [stateName: string]: IRule[]; };
brackets: IBracket[];
}
export interface IBracket {
token: string;
open: string;
close: string;
}
export type FuzzyAction = IAction | string;
export function isFuzzyActionArr(what: FuzzyAction | FuzzyAction[]): what is FuzzyAction[] {
return (Array.isArray(what));
}
export function isFuzzyAction(what: FuzzyAction | FuzzyAction[]): what is FuzzyAction {
return !isFuzzyActionArr(what);
}
export function isString(what: FuzzyAction): what is string {
return (typeof what === 'string');
}
export function isIAction(what: FuzzyAction): what is IAction {
return !isString(what);
}
export interface IRule {
regex: RegExp;
action: FuzzyAction;
matchOnlyAtLineStart: boolean;
name: string;
}
export interface IAction {
// an action is either a group of actions
group?: FuzzyAction[];
// or a function that returns a fresh action
test?: (id: string, matches: string[], state: string, eos: boolean) => FuzzyAction;
// or it is a declarative action with a token value and various other attributes
token?: string;
tokenSubst?: boolean;
next?: string;
nextEmbedded?: string;
bracket?: MonarchBracket;
log?: string;
switchTo?: string;
goBack?: number;
transform?: (states: string[]) => string[];
}
export interface IBranch {
name: string;
value: FuzzyAction;
test?: (id: string, matches: string[], state: string, eos: boolean) => boolean;
}
// Small helper functions
/**
* Is a string null, undefined, or empty?
*/
export function empty(s: string): boolean {
return (s ? false : true);
}
/**
* Puts a string to lower case if 'ignoreCase' is set.
*/
export function fixCase(lexer: ILexerMin, str: string): string {
return (lexer.ignoreCase && str ? str.toLowerCase() : str);
}
/**
* Ensures there are no bad characters in a CSS token class.
*/
export function sanitize(s: string) {
return s.replace(/[&<>'"_]/g, '-'); // used on all output token CSS classes
}
// Logging
/**
* Logs a message.
*/
export function log(lexer: ILexerMin, msg: string) {
console.log(`${lexer.languageId}: ${msg}`);
}
// Throwing errors
export function createError(lexer: ILexerMin, msg: string): Error {
return new Error(`${lexer.languageId}: ${msg}`);
}
// Helper functions for rule finding and substitution
/**
* substituteMatches is used on lexer strings and can substitutes predefined patterns:
* $$ => $
* $# => id
* $n => matched entry n
* @attr => contents of lexer[attr]
*
* See documentation for more info
*/
export function substituteMatches(lexer: ILexerMin, str: string, id: string, matches: string[], state: string): string {
const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
let stateMatches: string[] | null = null;
return str.replace(re, function (full, sub?, dollar?, hash?, n?, s?, attr?, ofs?, total?) {
if (!empty(dollar)) {
return '$'; // $$
}
if (!empty(hash)) {
return fixCase(lexer, id); // default $#
}
if (!empty(n) && n < matches.length) {
return fixCase(lexer, matches[n]); // $n
}
if (!empty(attr) && lexer && typeof (lexer[attr]) === 'string') {
return lexer[attr]; //@attribute
}
if (stateMatches === null) { // split state on demand
stateMatches = state.split('.');
stateMatches.unshift(state);
}
if (!empty(s) && s < stateMatches.length) {
return fixCase(lexer, stateMatches[s]); //$Sn
}
return '';
});
}
/**
* Find the tokenizer rules for a specific state (i.e. next action)
*/
export function findRules(lexer: ILexer, inState: string): IRule[] | null {
let state: string | null = inState;
while (state && state.length > 0) {
const rules = lexer.tokenizer[state];
if (rules) {
return rules;
}
const idx = state.lastIndexOf('.');
if (idx < 0) {
state = null; // no further parent
} else {
state = state.substr(0, idx);
}
}
return null;
}
/**
* Is a certain state defined? In contrast to 'findRules' this works on a ILexerMin.
* This is used during compilation where we may know the defined states
* but not yet whether the corresponding rules are correct.
*/
export function stateExists(lexer: ILexerMin, inState: string): boolean {
let state: string | null = inState;
while (state && state.length > 0) {
const exist = lexer.stateNames[state];
if (exist) {
return true;
}
const idx = state.lastIndexOf('.');
if (idx < 0) {
state = null; // no further parent
} else {
state = state.substr(0, idx);
}
}
return false;
}
| src/vs/editor/standalone/common/monarch/monarchCommon.ts | 1 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.08090674132108688,
0.0043985131196677685,
0.00016310877981595695,
0.0001745399204082787,
0.016735654324293137
] |
{
"id": 8,
"code_window": [
"\t\t};\n",
"\t\t/**\n",
"\t\t * is the language case insensitive?\n",
"\t\t */\n",
"\t\tignoreCase?: boolean;\n",
"\t\t/**\n",
"\t\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t\t */\n",
"\t\tdefaultToken?: string;\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t/**\n",
"\t\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t\t */\n",
"\t\tunicode?: boolean;\n"
],
"file_path": "src/vs/monaco.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* Editor Label */
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label {
white-space: nowrap;
flex: 1;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-label a,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label a {
text-decoration: none;
font-size: 13px;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .monaco-icon-label::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .monaco-icon-label::before,
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-label a,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label a,
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-label h2,
.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab .tab-label span {
cursor: pointer;
}
/* Title Actions */
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-actions .action-label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-label {
display: flex;
height: 35px;
min-width: 28px;
align-items: center;
justify-content: center;
background-size: 16px;
background-position: center center;
background-repeat: no-repeat;
}
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .title-actions .action-label,
.monaco-workbench.hc-black .part.editor > .content .editor-group-container > .title .editor-actions .action-label:not(.codicon) {
line-height: initial;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-label .label,
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-actions .action-label .label {
display: none;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-label.codicon {
color: inherit;
}
.monaco-workbench .part.editor > .content .editor-group-container > .title .title-actions .action-label.disabled,
.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions .action-label.disabled {
opacity: 0.4;
}
/* Drag Cursor */
.monaco-workbench .part.editor > .content .editor-group-container > .title {
cursor: grab;
}
/* Drag and Drop Feedback */
.monaco-editor-group-drag-image {
display: inline-block;
padding: 1px 7px;
border-radius: 10px;
font-size: 12px;
position: absolute;
}
| src/vs/workbench/browser/parts/editor/media/titlecontrol.css | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.0001750119699863717,
0.00017197546549141407,
0.00016526262334082276,
0.00017259237938560545,
0.000002806045358738629
] |
{
"id": 8,
"code_window": [
"\t\t};\n",
"\t\t/**\n",
"\t\t * is the language case insensitive?\n",
"\t\t */\n",
"\t\tignoreCase?: boolean;\n",
"\t\t/**\n",
"\t\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t\t */\n",
"\t\tdefaultToken?: string;\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t/**\n",
"\t\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t\t */\n",
"\t\tunicode?: boolean;\n"
],
"file_path": "src/vs/monaco.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* marker zone */
.monaco-editor .peekview-widget .head .peekview-title .severity-icon {
display: inline-block;
vertical-align: text-top;
margin-right: 4px;
}
.monaco-editor .marker-widget {
text-overflow: ellipsis;
white-space: nowrap;
}
.monaco-editor .marker-widget > .stale {
opacity: 0.6;
font-style: italic;
}
.monaco-editor .marker-widget .title {
display: inline-block;
padding-right: 5px;
}
.monaco-editor .marker-widget .descriptioncontainer {
position: absolute;
white-space: pre;
user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
padding: 8px 12px 0 20px;
}
.monaco-editor .marker-widget .descriptioncontainer .message {
display: flex;
flex-direction: column;
}
.monaco-editor .marker-widget .descriptioncontainer .message .details {
padding-left: 6px;
}
.monaco-editor .marker-widget .descriptioncontainer .message .source,
.monaco-editor .marker-widget .descriptioncontainer .message span.code {
opacity: 0.6;
}
.monaco-editor .marker-widget .descriptioncontainer .message a.code-link {
opacity: 0.6;
color: inherit;
}
.monaco-editor .marker-widget .descriptioncontainer .message a.code-link:before {
content: '(';
}
.monaco-editor .marker-widget .descriptioncontainer .message a.code-link:after {
content: ')';
}
.monaco-editor .marker-widget .descriptioncontainer .message a.code-link > span {
text-decoration: underline;
/** Hack to force underline to show **/
border-bottom: 1px solid transparent;
text-underline-position: under;
}
.monaco-editor .marker-widget .descriptioncontainer .filename {
cursor: pointer;
}
| src/vs/editor/contrib/gotoError/media/gotoErrorWidget.css | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00018132264085579664,
0.00017526416922919452,
0.0001728343777358532,
0.00017488037701696157,
0.000002470458866810077
] |
{
"id": 8,
"code_window": [
"\t\t};\n",
"\t\t/**\n",
"\t\t * is the language case insensitive?\n",
"\t\t */\n",
"\t\tignoreCase?: boolean;\n",
"\t\t/**\n",
"\t\t * if no match in the tokenizer assign this token class (default 'source')\n",
"\t\t */\n",
"\t\tdefaultToken?: string;\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t/**\n",
"\t\t * is the language unicode-aware? (i.e., /\\u{1D306}/)\n",
"\t\t */\n",
"\t\tunicode?: boolean;\n"
],
"file_path": "src/vs/monaco.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "Colorsublime-Themes",
"repositoryUrl": "https://github.com/Colorsublime/Colorsublime-Themes",
"commitHash": "c10fdd8b144486b7a4f3cb4e2251c66df222a825"
}
},
"version": "0.1.0"
}
],
"version": 1
}
| extensions/theme-tomorrow-night-blue/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/4b00bed17724df21c5a03ac929358bff22ff4a0d | [
0.00017403828678652644,
0.0001736197737045586,
0.000173201275174506,
0.0001736197737045586,
4.185058060102165e-7
] |
{
"id": 0,
"code_window": [
"| `cachingOptimizeSerializationMemoryUsage` | If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses. |\n",
"| `pluginsInstrumentationStatusSource` | Include a status source label for plugin request metrics and logs |\n",
"| `costManagementUi` | Toggles the display of the cost management ui plugin |\n",
"\n",
"## Development feature toggles\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `managedPluginsInstall` | Install managed plugins directly from plugins catalog |\n"
],
"file_path": "docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md",
"type": "add",
"edit_start_line_idx": 155
} | Name,Stage,Owner,requiresDevMode,RequiresLicense,RequiresRestart,FrontendOnly
trimDefaults,preview,@grafana/grafana-as-code,false,false,false,false
disableEnvelopeEncryption,GA,@grafana/grafana-as-code,false,false,false,false
live-service-web-worker,experimental,@grafana/grafana-app-platform-squad,false,false,false,true
queryOverLive,experimental,@grafana/grafana-app-platform-squad,false,false,false,true
panelTitleSearch,preview,@grafana/grafana-app-platform-squad,false,false,false,false
publicDashboards,GA,@grafana/sharing-squad,false,false,false,false
publicDashboardsEmailSharing,preview,@grafana/sharing-squad,false,true,false,false
lokiExperimentalStreaming,experimental,@grafana/observability-logs,false,false,false,false
featureHighlights,GA,@grafana/grafana-as-code,false,false,false,false
migrationLocking,preview,@grafana/backend-platform,false,false,false,false
storage,experimental,@grafana/grafana-app-platform-squad,false,false,false,false
correlations,preview,@grafana/explore-squad,false,false,false,false
exploreContentOutline,GA,@grafana/explore-squad,false,false,false,true
datasourceQueryMultiStatus,experimental,@grafana/plugins-platform-backend,false,false,false,false
traceToMetrics,experimental,@grafana/observability-traces-and-profiling,false,false,false,true
newDBLibrary,preview,@grafana/backend-platform,false,false,false,false
autoMigrateOldPanels,preview,@grafana/dataviz-squad,false,false,false,true
disableAngular,preview,@grafana/dataviz-squad,false,false,false,true
canvasPanelNesting,experimental,@grafana/dataviz-squad,false,false,false,true
scenes,experimental,@grafana/dashboards-squad,false,false,false,true
disableSecretsCompatibility,experimental,@grafana/hosted-grafana-team,false,false,true,false
logRequestsInstrumentedAsUnknown,experimental,@grafana/hosted-grafana-team,false,false,false,false
dataConnectionsConsole,GA,@grafana/plugins-platform-backend,false,false,false,false
topnav,deprecated,@grafana/grafana-frontend-platform,false,false,false,false
dockedMegaMenu,experimental,@grafana/grafana-frontend-platform,false,false,false,true
grpcServer,preview,@grafana/grafana-app-platform-squad,false,false,false,false
entityStore,experimental,@grafana/grafana-app-platform-squad,true,false,false,false
cloudWatchCrossAccountQuerying,GA,@grafana/aws-datasources,false,false,false,false
redshiftAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,false
athenaAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,true
cloudwatchNewRegionsHandler,experimental,@grafana/aws-datasources,false,false,false,false
showDashboardValidationWarnings,experimental,@grafana/dashboards-squad,false,false,false,false
mysqlAnsiQuotes,experimental,@grafana/backend-platform,false,false,false,false
accessControlOnCall,preview,@grafana/grafana-authnz-team,false,false,false,false
nestedFolders,preview,@grafana/backend-platform,false,false,false,false
nestedFolderPicker,GA,@grafana/grafana-frontend-platform,false,false,false,true
accessTokenExpirationCheck,GA,@grafana/grafana-authnz-team,false,false,false,false
emptyDashboardPage,GA,@grafana/dashboards-squad,false,false,false,true
disablePrometheusExemplarSampling,GA,@grafana/observability-metrics,false,false,false,false
alertingBacktesting,experimental,@grafana/alerting-squad,false,false,false,false
editPanelCSVDragAndDrop,experimental,@grafana/grafana-bi-squad,false,false,false,true
alertingNoNormalState,preview,@grafana/alerting-squad,false,false,false,false
logsContextDatasourceUi,GA,@grafana/observability-logs,false,false,false,true
lokiQuerySplitting,experimental,@grafana/observability-logs,false,false,false,true
lokiQuerySplittingConfig,experimental,@grafana/observability-logs,false,false,false,true
individualCookiePreferences,experimental,@grafana/backend-platform,false,false,false,false
gcomOnlyExternalOrgRoleSync,GA,@grafana/grafana-authnz-team,false,false,false,false
prometheusMetricEncyclopedia,GA,@grafana/observability-metrics,false,false,false,true
influxdbBackendMigration,GA,@grafana/observability-metrics,false,false,false,true
clientTokenRotation,experimental,@grafana/grafana-authnz-team,false,false,false,false
prometheusDataplane,GA,@grafana/observability-metrics,false,false,false,false
lokiMetricDataplane,GA,@grafana/observability-logs,false,false,false,false
lokiLogsDataplane,experimental,@grafana/observability-logs,false,false,false,false
dataplaneFrontendFallback,GA,@grafana/observability-metrics,false,false,false,true
disableSSEDataplane,experimental,@grafana/observability-metrics,false,false,false,false
alertStateHistoryLokiSecondary,experimental,@grafana/alerting-squad,false,false,false,false
alertingNotificationsPoliciesMatchingInstances,GA,@grafana/alerting-squad,false,false,false,true
alertStateHistoryLokiPrimary,experimental,@grafana/alerting-squad,false,false,false,false
alertStateHistoryLokiOnly,experimental,@grafana/alerting-squad,false,false,false,false
unifiedRequestLog,experimental,@grafana/backend-platform,false,false,false,false
renderAuthJWT,preview,@grafana/grafana-as-code,false,false,false,false
externalServiceAuth,experimental,@grafana/grafana-authnz-team,true,false,false,false
refactorVariablesTimeRange,preview,@grafana/dashboards-squad,false,false,false,false
useCachingService,GA,@grafana/grafana-operator-experience-squad,false,false,true,false
enableElasticsearchBackendQuerying,GA,@grafana/observability-logs,false,false,false,false
advancedDataSourcePicker,GA,@grafana/dashboards-squad,false,false,false,true
faroDatasourceSelector,preview,@grafana/app-o11y,false,false,false,true
enableDatagridEditing,preview,@grafana/grafana-bi-squad,false,false,false,true
dataSourcePageHeader,preview,@grafana/enterprise-datasources,false,false,false,true
extraThemes,experimental,@grafana/grafana-frontend-platform,false,false,false,true
lokiPredefinedOperations,experimental,@grafana/observability-logs,false,false,false,true
pluginsFrontendSandbox,experimental,@grafana/plugins-platform-backend,false,false,false,true
dashboardEmbed,experimental,@grafana/grafana-as-code,false,false,false,true
frontendSandboxMonitorOnly,experimental,@grafana/plugins-platform-backend,false,false,false,true
sqlDatasourceDatabaseSelection,preview,@grafana/grafana-bi-squad,false,false,false,true
lokiFormatQuery,experimental,@grafana/observability-logs,false,false,false,true
cloudWatchLogsMonacoEditor,GA,@grafana/aws-datasources,false,false,false,true
exploreScrollableLogsContainer,experimental,@grafana/observability-logs,false,false,false,true
recordedQueriesMulti,GA,@grafana/observability-metrics,false,false,false,false
pluginsDynamicAngularDetectionPatterns,experimental,@grafana/plugins-platform-backend,false,false,false,false
vizAndWidgetSplit,experimental,@grafana/dashboards-squad,false,false,false,true
prometheusIncrementalQueryInstrumentation,experimental,@grafana/observability-metrics,false,false,false,true
logsExploreTableVisualisation,experimental,@grafana/observability-logs,false,false,false,true
awsDatasourcesTempCredentials,experimental,@grafana/aws-datasources,false,false,false,false
transformationsRedesign,GA,@grafana/observability-metrics,false,false,false,true
toggleLabelsInLogsUI,GA,@grafana/observability-logs,false,false,false,true
mlExpressions,experimental,@grafana/alerting-squad,false,false,false,false
traceQLStreaming,experimental,@grafana/observability-traces-and-profiling,false,false,false,true
metricsSummary,experimental,@grafana/observability-traces-and-profiling,false,false,false,true
grafanaAPIServer,experimental,@grafana/grafana-app-platform-squad,false,false,false,false
grafanaAPIServerWithExperimentalAPIs,experimental,@grafana/grafana-app-platform-squad,false,false,false,false
featureToggleAdminPage,experimental,@grafana/grafana-operator-experience-squad,false,false,true,false
awsAsyncQueryCaching,preview,@grafana/aws-datasources,false,false,false,false
splitScopes,preview,@grafana/grafana-authnz-team,false,false,true,false
azureMonitorDataplane,GA,@grafana/partner-datasources,false,false,false,false
permissionsFilterRemoveSubquery,experimental,@grafana/backend-platform,false,false,false,false
prometheusConfigOverhaulAuth,GA,@grafana/observability-metrics,false,false,false,false
configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false
influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false
alertingNoDataErrorExecution,privatePreview,@grafana/alerting-squad,false,false,true,false
angularDeprecationUI,experimental,@grafana/plugins-platform-backend,false,false,false,true
dashgpt,experimental,@grafana/dashboards-squad,false,false,false,true
reportingRetries,preview,@grafana/sharing-squad,false,false,true,false
newBrowseDashboards,GA,@grafana/grafana-frontend-platform,false,false,false,true
sseGroupByDatasource,experimental,@grafana/observability-metrics,false,false,false,false
requestInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false
libraryPanelRBAC,experimental,@grafana/dashboards-squad,false,false,true,false
lokiRunQueriesInParallel,privatePreview,@grafana/observability-logs,false,false,false,false
wargamesTesting,experimental,@grafana/hosted-grafana-team,false,false,false,false
alertingInsights,GA,@grafana/alerting-squad,false,false,false,true
externalCorePlugins,experimental,@grafana/plugins-platform-backend,false,false,false,false
pluginsAPIMetrics,experimental,@grafana/plugins-platform-backend,false,false,false,true
httpSLOLevels,experimental,@grafana/hosted-grafana-team,false,false,true,false
idForwarding,experimental,@grafana/grafana-authnz-team,true,false,false,false
cloudWatchWildCardDimensionValues,GA,@grafana/aws-datasources,false,false,false,false
externalServiceAccounts,experimental,@grafana/grafana-authnz-team,true,false,false,false
panelMonitoring,experimental,@grafana/dataviz-squad,false,false,false,true
enableNativeHTTPHistogram,experimental,@grafana/hosted-grafana-team,false,false,false,false
formatString,experimental,@grafana/grafana-bi-squad,false,false,false,true
transformationsVariableSupport,experimental,@grafana/grafana-bi-squad,false,false,false,true
kubernetesPlaylists,experimental,@grafana/grafana-app-platform-squad,false,false,false,true
navAdminSubsections,experimental,@grafana/grafana-frontend-platform,false,false,false,false
recoveryThreshold,experimental,@grafana/alerting-squad,false,false,true,false
teamHttpHeaders,experimental,@grafana/grafana-authnz-team,false,false,false,false
awsDatasourcesNewFormStyling,experimental,@grafana/aws-datasources,false,false,false,true
cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false
panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false
pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false
costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false
| pkg/services/featuremgmt/toggles_gen.csv | 1 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0015746916178613901,
0.0015746915014460683,
0.0015746916178613901,
0.0015746916178613901,
1.1641532182693481e-10
] |
{
"id": 0,
"code_window": [
"| `cachingOptimizeSerializationMemoryUsage` | If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses. |\n",
"| `pluginsInstrumentationStatusSource` | Include a status source label for plugin request metrics and logs |\n",
"| `costManagementUi` | Toggles the display of the cost management ui plugin |\n",
"\n",
"## Development feature toggles\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `managedPluginsInstall` | Install managed plugins directly from plugins catalog |\n"
],
"file_path": "docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md",
"type": "add",
"edit_start_line_idx": 155
} | // This migration ensures that permissions attributed to a managed role are also granted
// to parent roles.
// Example setup:
// editor read, query datasources:uid:2
// editor read, query datasources:uid:1
// admin read, query, write datasources:uid:1
// we'd need to create admin read, query, write datasources:uid:2
package accesscontrol
import (
"strings"
"time"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
const ManagedPermissionsMigrationID = "managed permissions migration"
func AddManagedPermissionsMigration(mg *migrator.Migrator, migrationID string) {
mg.AddMigration(migrationID, &managedPermissionMigrator{})
}
type managedPermissionMigrator struct {
migrator.MigrationBase
}
func (sp *managedPermissionMigrator) SQL(dialect migrator.Dialect) string {
return CodeMigrationSQL
}
func (sp *managedPermissionMigrator) Exec(sess *xorm.Session, mg *migrator.Migrator) error {
logger := log.New("managed permissions migrator")
type Permission struct {
RoleName string `xorm:"role_name"`
RoleID int64 `xorm:"role_id"`
OrgID int64 `xorm:"org_id"`
Action string
Scope string
}
// get all permissions associated with a managed builtin role
managedPermissions := []Permission{}
if errFindPermissions := sess.SQL(`SELECT r.name as role_name, r.id as role_id, r.org_id as org_id,p.action, p.scope
FROM permission AS p
INNER JOIN role AS r ON p.role_id = r.id
WHERE r.name LIKE ?`, "managed:builtins%").
Find(&managedPermissions); errFindPermissions != nil {
logger.Error("could not get the managed permissions", "error", errFindPermissions)
return errFindPermissions
}
permissionMap := make(map[int64]map[string]map[Permission]bool) // map[org_id][role_name][Permission] = toInsert
// for each managed permission make a map of which permissions need to be added to inheritors
for _, p := range managedPermissions {
// this ensures we can use p as a key in the map between different permissions
// ensuring we're only comparing on the action and scope
roleName := p.RoleName
p.RoleName = ""
p.RoleID = 0
// Add the permission to the map of permissions as "false" - already exists
if _, ok := permissionMap[p.OrgID]; !ok {
permissionMap[p.OrgID] = map[string]map[Permission]bool{roleName: {p: false}}
} else {
if _, ok := permissionMap[p.OrgID][roleName]; !ok {
permissionMap[p.OrgID][roleName] = map[Permission]bool{p: false}
} else {
permissionMap[p.OrgID][roleName][p] = false
}
}
// Add parent roles + permissions to the map as "true" -- need to be inserted
basicRoleName := ParseRoleFromName(roleName)
for _, parent := range org.RoleType(basicRoleName).Parents() {
parentManagedRoleName := "managed:builtins:" + strings.ToLower(string(parent)) + ":permissions"
if _, ok := permissionMap[p.OrgID][parentManagedRoleName]; !ok {
permissionMap[p.OrgID][parentManagedRoleName] = map[Permission]bool{p: true}
} else {
if _, ok := permissionMap[p.OrgID][parentManagedRoleName][p]; !ok {
permissionMap[p.OrgID][parentManagedRoleName][p] = true
}
}
}
}
now := time.Now()
// Create missing permissions
for orgID, orgMap := range permissionMap {
for managedRole, permissions := range orgMap {
// ensure managed role exists, create and add to map if it doesn't
foundRole := &accesscontrol.Role{Name: managedRole, OrgID: orgID}
ok, err := sess.Get(foundRole)
if err != nil {
return err
}
if !ok {
uid, err := GenerateManagedRoleUID(orgID, managedRole)
if err != nil {
return err
}
createdRole := accesscontrol.Role{Name: managedRole, OrgID: orgID, UID: uid, Created: now, Updated: now}
if _, err := sess.Insert(&createdRole); err != nil {
logger.Error("Unable to create managed role", "error", err)
return err
}
connection := accesscontrol.BuiltinRole{
RoleID: createdRole.ID,
OrgID: orgID,
Role: ParseRoleFromName(createdRole.Name),
Created: now,
Updated: now,
}
if _, err := sess.Insert(&connection); err != nil {
logger.Error("Unable to create managed role connection", "error", err)
return err
}
foundRole = &createdRole
}
// assign permissions if they don't exist to the role
roleID := foundRole.ID
if roleID == 0 {
logger.Warn("Unable to create managed permission, got role ID 0", "orgID", orgID, "managedRole", managedRole)
continue
}
for p, toInsert := range permissions {
if toInsert {
perm := accesscontrol.Permission{RoleID: roleID, Action: p.Action, Scope: p.Scope, Created: now, Updated: now}
if _, err := sess.Insert(&perm); err != nil {
logger.Error("Unable to create managed permission", "error", err)
return err
}
}
}
}
}
return nil
}
// Converts from managed:builtins:<role>:permissions to <Role>
// Example: managed:builtins:editor:permissions -> Editor
func ParseRoleFromName(roleName string) string {
return cases.Title(language.AmericanEnglish).
String(strings.TrimSuffix(strings.TrimPrefix(roleName, "managed:builtins:"), ":permissions"))
}
| pkg/services/sqlstore/migrations/accesscontrol/managed_permission_migrator.go | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0015746916178613901,
0.0015746916178613901,
0.0015746916178613901,
0.0015746916178613901,
0
] |
{
"id": 0,
"code_window": [
"| `cachingOptimizeSerializationMemoryUsage` | If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses. |\n",
"| `pluginsInstrumentationStatusSource` | Include a status source label for plugin request metrics and logs |\n",
"| `costManagementUi` | Toggles the display of the cost management ui plugin |\n",
"\n",
"## Development feature toggles\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `managedPluginsInstall` | Install managed plugins directly from plugins catalog |\n"
],
"file_path": "docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md",
"type": "add",
"edit_start_line_idx": 155
} | // Code generated - EDITING IS FUTILE. DO NOT EDIT.
//
// Generated by:
// kinds/gen.go
// Using jennies:
// TSResourceJenny
// LatestMajorsOrXJenny
//
// Run 'make gen-cue' from repository root to regenerate.
export interface Role {
/**
* Role description
*/
description?: string;
/**
* Optional display
*/
displayName?: string;
/**
* Name of the team.
*/
groupName?: string;
/**
* Do not show this role
*/
hidden: (boolean | false);
/**
* The role identifier `managed:builtins:editor:permissions`
*/
name: string;
}
| packages/grafana-schema/src/raw/role/x/role_types.gen.ts | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0015746902208775282,
0.0015746902208775282,
0.0015746902208775282,
0.0015746902208775282,
0
] |
{
"id": 0,
"code_window": [
"| `cachingOptimizeSerializationMemoryUsage` | If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses. |\n",
"| `pluginsInstrumentationStatusSource` | Include a status source label for plugin request metrics and logs |\n",
"| `costManagementUi` | Toggles the display of the cost management ui plugin |\n",
"\n",
"## Development feature toggles\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"| `managedPluginsInstall` | Install managed plugins directly from plugins catalog |\n"
],
"file_path": "docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md",
"type": "add",
"edit_start_line_idx": 155
} | import React from 'react';
import { NavModelItem, PageLayoutType } from '@grafana/data';
export interface PageInfoItem {
label: string;
value: React.ReactNode;
}
export interface PluginPageProps {
/** Can be used to place actions inline with the heading */
info?: PageInfoItem[];
/** Can be used to place actions inline with the heading */
actions?: React.ReactNode;
/** Can be used to customize rendering of title */
renderTitle?: (title: string) => React.ReactNode;
/** Shown under main heading */
subTitle?: React.ReactNode;
pageNav?: NavModelItem;
children: React.ReactNode;
layout?: PageLayoutType;
}
export type PluginPageType = React.ComponentType<PluginPageProps>;
export let PluginPage: PluginPageType = ({ children }) => {
return <div>{children}</div>;
};
/**
* Used to bootstrap the PluginPage during application start
* is exposed via runtime.
*
* @internal
*/
export function setPluginPage(component: PluginPageType) {
PluginPage = component;
}
| packages/grafana-runtime/src/components/PluginPage.tsx | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0015746902208775282,
0.0015746902208775282,
0.0015746902208775282,
0.0015746902208775282,
0
] |
{
"id": 1,
"code_window": [
" cachingOptimizeSerializationMemoryUsage?: boolean;\n",
" panelTitleSearchInV1?: boolean;\n",
" pluginsInstrumentationStatusSource?: boolean;\n",
" costManagementUi?: boolean;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" managedPluginsInstall?: boolean;\n"
],
"file_path": "packages/grafana-data/src/types/featureToggles.gen.ts",
"type": "add",
"edit_start_line_idx": 149
} | // NOTE: This file was auto generated. DO NOT EDIT DIRECTLY!
// To change feature flags, edit:
// pkg/services/featuremgmt/registry.go
// Then run tests in:
// pkg/services/featuremgmt/toggles_gen_test.go
package featuremgmt
const (
// FlagTrimDefaults
// Use cue schema to remove values that will be applied automatically
FlagTrimDefaults = "trimDefaults"
// FlagDisableEnvelopeEncryption
// Disable envelope encryption (emergency only)
FlagDisableEnvelopeEncryption = "disableEnvelopeEncryption"
// FlagLiveServiceWebWorker
// This will use a webworker thread to processes events rather than the main thread
FlagLiveServiceWebWorker = "live-service-web-worker"
// FlagQueryOverLive
// Use Grafana Live WebSocket to execute backend queries
FlagQueryOverLive = "queryOverLive"
// FlagPanelTitleSearch
// Search for dashboards using panel title
FlagPanelTitleSearch = "panelTitleSearch"
// FlagPublicDashboards
// Enables public access to dashboards
FlagPublicDashboards = "publicDashboards"
// FlagPublicDashboardsEmailSharing
// Enables public dashboard sharing to be restricted to only allowed emails
FlagPublicDashboardsEmailSharing = "publicDashboardsEmailSharing"
// FlagLokiExperimentalStreaming
// Support new streaming approach for loki (prototype, needs special loki build)
FlagLokiExperimentalStreaming = "lokiExperimentalStreaming"
// FlagFeatureHighlights
// Highlight Grafana Enterprise features
FlagFeatureHighlights = "featureHighlights"
// FlagMigrationLocking
// Lock database during migrations
FlagMigrationLocking = "migrationLocking"
// FlagStorage
// Configurable storage for dashboards, datasources, and resources
FlagStorage = "storage"
// FlagCorrelations
// Correlations page
FlagCorrelations = "correlations"
// FlagExploreContentOutline
// Content outline sidebar
FlagExploreContentOutline = "exploreContentOutline"
// FlagDatasourceQueryMultiStatus
// Introduce HTTP 207 Multi Status for api/ds/query
FlagDatasourceQueryMultiStatus = "datasourceQueryMultiStatus"
// FlagTraceToMetrics
// Enable trace to metrics links
FlagTraceToMetrics = "traceToMetrics"
// FlagNewDBLibrary
// Use jmoiron/sqlx rather than xorm for a few backend services
FlagNewDBLibrary = "newDBLibrary"
// FlagAutoMigrateOldPanels
// Migrate old angular panels to supported versions (graph, table-old, worldmap, etc)
FlagAutoMigrateOldPanels = "autoMigrateOldPanels"
// FlagDisableAngular
// Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime.
FlagDisableAngular = "disableAngular"
// FlagCanvasPanelNesting
// Allow elements nesting
FlagCanvasPanelNesting = "canvasPanelNesting"
// FlagScenes
// Experimental framework to build interactive dashboards
FlagScenes = "scenes"
// FlagDisableSecretsCompatibility
// Disable duplicated secret storage in legacy tables
FlagDisableSecretsCompatibility = "disableSecretsCompatibility"
// FlagLogRequestsInstrumentedAsUnknown
// Logs the path for requests that are instrumented as unknown
FlagLogRequestsInstrumentedAsUnknown = "logRequestsInstrumentedAsUnknown"
// FlagDataConnectionsConsole
// Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins.
FlagDataConnectionsConsole = "dataConnectionsConsole"
// FlagTopnav
// Enables topnav support in external plugins. The new Grafana navigation cannot be disabled.
FlagTopnav = "topnav"
// FlagDockedMegaMenu
// Enable support for a persistent (docked) navigation menu
FlagDockedMegaMenu = "dockedMegaMenu"
// FlagGrpcServer
// Run the GRPC server
FlagGrpcServer = "grpcServer"
// FlagEntityStore
// SQL-based entity store (requires storage flag also)
FlagEntityStore = "entityStore"
// FlagCloudWatchCrossAccountQuerying
// Enables cross-account querying in CloudWatch datasources
FlagCloudWatchCrossAccountQuerying = "cloudWatchCrossAccountQuerying"
// FlagRedshiftAsyncQueryDataSupport
// Enable async query data support for Redshift
FlagRedshiftAsyncQueryDataSupport = "redshiftAsyncQueryDataSupport"
// FlagAthenaAsyncQueryDataSupport
// Enable async query data support for Athena
FlagAthenaAsyncQueryDataSupport = "athenaAsyncQueryDataSupport"
// FlagCloudwatchNewRegionsHandler
// Refactor of /regions endpoint, no user-facing changes
FlagCloudwatchNewRegionsHandler = "cloudwatchNewRegionsHandler"
// FlagShowDashboardValidationWarnings
// Show warnings when dashboards do not validate against the schema
FlagShowDashboardValidationWarnings = "showDashboardValidationWarnings"
// FlagMysqlAnsiQuotes
// Use double quotes to escape keyword in a MySQL query
FlagMysqlAnsiQuotes = "mysqlAnsiQuotes"
// FlagAccessControlOnCall
// Access control primitives for OnCall
FlagAccessControlOnCall = "accessControlOnCall"
// FlagNestedFolders
// Enable folder nesting
FlagNestedFolders = "nestedFolders"
// FlagNestedFolderPicker
// Enables the new folder picker to work with nested folders. Requires the nestedFolders feature toggle
FlagNestedFolderPicker = "nestedFolderPicker"
// FlagAccessTokenExpirationCheck
// Enable OAuth access_token expiration check and token refresh using the refresh_token
FlagAccessTokenExpirationCheck = "accessTokenExpirationCheck"
// FlagEmptyDashboardPage
// Enable the redesigned user interface of a dashboard page that includes no panels
FlagEmptyDashboardPage = "emptyDashboardPage"
// FlagDisablePrometheusExemplarSampling
// Disable Prometheus exemplar sampling
FlagDisablePrometheusExemplarSampling = "disablePrometheusExemplarSampling"
// FlagAlertingBacktesting
// Rule backtesting API for alerting
FlagAlertingBacktesting = "alertingBacktesting"
// FlagEditPanelCSVDragAndDrop
// Enables drag and drop for CSV and Excel files
FlagEditPanelCSVDragAndDrop = "editPanelCSVDragAndDrop"
// FlagAlertingNoNormalState
// Stop maintaining state of alerts that are not firing
FlagAlertingNoNormalState = "alertingNoNormalState"
// FlagLogsContextDatasourceUi
// Allow datasource to provide custom UI for context view
FlagLogsContextDatasourceUi = "logsContextDatasourceUi"
// FlagLokiQuerySplitting
// Split large interval queries into subqueries with smaller time intervals
FlagLokiQuerySplitting = "lokiQuerySplitting"
// FlagLokiQuerySplittingConfig
// Give users the option to configure split durations for Loki queries
FlagLokiQuerySplittingConfig = "lokiQuerySplittingConfig"
// FlagIndividualCookiePreferences
// Support overriding cookie preferences per user
FlagIndividualCookiePreferences = "individualCookiePreferences"
// FlagGcomOnlyExternalOrgRoleSync
// Prohibits a user from changing organization roles synced with Grafana Cloud auth provider
FlagGcomOnlyExternalOrgRoleSync = "gcomOnlyExternalOrgRoleSync"
// FlagPrometheusMetricEncyclopedia
// Adds the metrics explorer component to the Prometheus query builder as an option in metric select
FlagPrometheusMetricEncyclopedia = "prometheusMetricEncyclopedia"
// FlagInfluxdbBackendMigration
// Query InfluxDB InfluxQL without the proxy
FlagInfluxdbBackendMigration = "influxdbBackendMigration"
// FlagClientTokenRotation
// Replaces the current in-request token rotation so that the client initiates the rotation
FlagClientTokenRotation = "clientTokenRotation"
// FlagPrometheusDataplane
// Changes responses to from Prometheus to be compliant with the dataplane specification. In particular, when this feature toggle is active, the numeric `Field.Name` is set from 'Value' to the value of the `__name__` label.
FlagPrometheusDataplane = "prometheusDataplane"
// FlagLokiMetricDataplane
// Changes metric responses from Loki to be compliant with the dataplane specification.
FlagLokiMetricDataplane = "lokiMetricDataplane"
// FlagLokiLogsDataplane
// Changes logs responses from Loki to be compliant with the dataplane specification.
FlagLokiLogsDataplane = "lokiLogsDataplane"
// FlagDataplaneFrontendFallback
// Support dataplane contract field name change for transformations and field name matchers where the name is different
FlagDataplaneFrontendFallback = "dataplaneFrontendFallback"
// FlagDisableSSEDataplane
// Disables dataplane specific processing in server side expressions.
FlagDisableSSEDataplane = "disableSSEDataplane"
// FlagAlertStateHistoryLokiSecondary
// Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations.
FlagAlertStateHistoryLokiSecondary = "alertStateHistoryLokiSecondary"
// FlagAlertingNotificationsPoliciesMatchingInstances
// Enables the preview of matching instances for notification policies
FlagAlertingNotificationsPoliciesMatchingInstances = "alertingNotificationsPoliciesMatchingInstances"
// FlagAlertStateHistoryLokiPrimary
// Enable a remote Loki instance as the primary source for state history reads.
FlagAlertStateHistoryLokiPrimary = "alertStateHistoryLokiPrimary"
// FlagAlertStateHistoryLokiOnly
// Disable Grafana alerts from emitting annotations when a remote Loki instance is available.
FlagAlertStateHistoryLokiOnly = "alertStateHistoryLokiOnly"
// FlagUnifiedRequestLog
// Writes error logs to the request logger
FlagUnifiedRequestLog = "unifiedRequestLog"
// FlagRenderAuthJWT
// Uses JWT-based auth for rendering instead of relying on remote cache
FlagRenderAuthJWT = "renderAuthJWT"
// FlagExternalServiceAuth
// Starts an OAuth2 authentication provider for external services
FlagExternalServiceAuth = "externalServiceAuth"
// FlagRefactorVariablesTimeRange
// Refactor time range variables flow to reduce number of API calls made when query variables are chained
FlagRefactorVariablesTimeRange = "refactorVariablesTimeRange"
// FlagUseCachingService
// When active, the new query and resource caching implementation using a wire service inject replaces the previous middleware implementation.
FlagUseCachingService = "useCachingService"
// FlagEnableElasticsearchBackendQuerying
// Enable the processing of queries and responses in the Elasticsearch data source through backend
FlagEnableElasticsearchBackendQuerying = "enableElasticsearchBackendQuerying"
// FlagAdvancedDataSourcePicker
// Enable a new data source picker with contextual information, recently used order and advanced mode
FlagAdvancedDataSourcePicker = "advancedDataSourcePicker"
// FlagFaroDatasourceSelector
// Enable the data source selector within the Frontend Apps section of the Frontend Observability
FlagFaroDatasourceSelector = "faroDatasourceSelector"
// FlagEnableDatagridEditing
// Enables the edit functionality in the datagrid panel
FlagEnableDatagridEditing = "enableDatagridEditing"
// FlagDataSourcePageHeader
// Apply new pageHeader UI in data source edit page
FlagDataSourcePageHeader = "dataSourcePageHeader"
// FlagExtraThemes
// Enables extra themes
FlagExtraThemes = "extraThemes"
// FlagLokiPredefinedOperations
// Adds predefined query operations to Loki query editor
FlagLokiPredefinedOperations = "lokiPredefinedOperations"
// FlagPluginsFrontendSandbox
// Enables the plugins frontend sandbox
FlagPluginsFrontendSandbox = "pluginsFrontendSandbox"
// FlagDashboardEmbed
// Allow embedding dashboard for external use in Code editors
FlagDashboardEmbed = "dashboardEmbed"
// FlagFrontendSandboxMonitorOnly
// Enables monitor only in the plugin frontend sandbox (if enabled)
FlagFrontendSandboxMonitorOnly = "frontendSandboxMonitorOnly"
// FlagSqlDatasourceDatabaseSelection
// Enables previous SQL data source dataset dropdown behavior
FlagSqlDatasourceDatabaseSelection = "sqlDatasourceDatabaseSelection"
// FlagLokiFormatQuery
// Enables the ability to format Loki queries
FlagLokiFormatQuery = "lokiFormatQuery"
// FlagCloudWatchLogsMonacoEditor
// Enables the Monaco editor for CloudWatch Logs queries
FlagCloudWatchLogsMonacoEditor = "cloudWatchLogsMonacoEditor"
// FlagExploreScrollableLogsContainer
// Improves the scrolling behavior of logs in Explore
FlagExploreScrollableLogsContainer = "exploreScrollableLogsContainer"
// FlagRecordedQueriesMulti
// Enables writing multiple items from a single query within Recorded Queries
FlagRecordedQueriesMulti = "recordedQueriesMulti"
// FlagPluginsDynamicAngularDetectionPatterns
// Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones
FlagPluginsDynamicAngularDetectionPatterns = "pluginsDynamicAngularDetectionPatterns"
// FlagVizAndWidgetSplit
// Split panels between visualizations and widgets
FlagVizAndWidgetSplit = "vizAndWidgetSplit"
// FlagPrometheusIncrementalQueryInstrumentation
// Adds RudderStack events to incremental queries
FlagPrometheusIncrementalQueryInstrumentation = "prometheusIncrementalQueryInstrumentation"
// FlagLogsExploreTableVisualisation
// A table visualisation for logs in Explore
FlagLogsExploreTableVisualisation = "logsExploreTableVisualisation"
// FlagAwsDatasourcesTempCredentials
// Support temporary security credentials in AWS plugins for Grafana Cloud customers
FlagAwsDatasourcesTempCredentials = "awsDatasourcesTempCredentials"
// FlagTransformationsRedesign
// Enables the transformations redesign
FlagTransformationsRedesign = "transformationsRedesign"
// FlagToggleLabelsInLogsUI
// Enable toggleable filters in log details view
FlagToggleLabelsInLogsUI = "toggleLabelsInLogsUI"
// FlagMlExpressions
// Enable support for Machine Learning in server-side expressions
FlagMlExpressions = "mlExpressions"
// FlagTraceQLStreaming
// Enables response streaming of TraceQL queries of the Tempo data source
FlagTraceQLStreaming = "traceQLStreaming"
// FlagMetricsSummary
// Enables metrics summary queries in the Tempo data source
FlagMetricsSummary = "metricsSummary"
// FlagGrafanaAPIServer
// Enable Kubernetes API Server for Grafana resources
FlagGrafanaAPIServer = "grafanaAPIServer"
// FlagGrafanaAPIServerWithExperimentalAPIs
// Register experimental APIs with the k8s API server
FlagGrafanaAPIServerWithExperimentalAPIs = "grafanaAPIServerWithExperimentalAPIs"
// FlagFeatureToggleAdminPage
// Enable admin page for managing feature toggles from the Grafana front-end
FlagFeatureToggleAdminPage = "featureToggleAdminPage"
// FlagAwsAsyncQueryCaching
// Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled
FlagAwsAsyncQueryCaching = "awsAsyncQueryCaching"
// FlagSplitScopes
// Support faster dashboard and folder search by splitting permission scopes into parts
FlagSplitScopes = "splitScopes"
// FlagAzureMonitorDataplane
// Adds dataplane compliant frame metadata in the Azure Monitor datasource
FlagAzureMonitorDataplane = "azureMonitorDataplane"
// FlagPermissionsFilterRemoveSubquery
// Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder
FlagPermissionsFilterRemoveSubquery = "permissionsFilterRemoveSubquery"
// FlagPrometheusConfigOverhaulAuth
// Update the Prometheus configuration page with the new auth component
FlagPrometheusConfigOverhaulAuth = "prometheusConfigOverhaulAuth"
// FlagConfigurableSchedulerTick
// Enable changing the scheduler base interval via configuration option unified_alerting.scheduler_tick_interval
FlagConfigurableSchedulerTick = "configurableSchedulerTick"
// FlagInfluxdbSqlSupport
// Enable InfluxDB SQL query language support with new querying UI
FlagInfluxdbSqlSupport = "influxdbSqlSupport"
// FlagAlertingNoDataErrorExecution
// Changes how Alerting state manager handles execution of NoData/Error
FlagAlertingNoDataErrorExecution = "alertingNoDataErrorExecution"
// FlagAngularDeprecationUI
// Display new Angular deprecation-related UI features
FlagAngularDeprecationUI = "angularDeprecationUI"
// FlagDashgpt
// Enable AI powered features in dashboards
FlagDashgpt = "dashgpt"
// FlagReportingRetries
// Enables rendering retries for the reporting feature
FlagReportingRetries = "reportingRetries"
// FlagNewBrowseDashboards
// New browse/manage dashboards UI
FlagNewBrowseDashboards = "newBrowseDashboards"
// FlagSseGroupByDatasource
// Send query to the same datasource in a single request when using server side expressions
FlagSseGroupByDatasource = "sseGroupByDatasource"
// FlagRequestInstrumentationStatusSource
// Include a status source label for request metrics and logs
FlagRequestInstrumentationStatusSource = "requestInstrumentationStatusSource"
// FlagLibraryPanelRBAC
// Enables RBAC support for library panels
FlagLibraryPanelRBAC = "libraryPanelRBAC"
// FlagLokiRunQueriesInParallel
// Enables running Loki queries in parallel
FlagLokiRunQueriesInParallel = "lokiRunQueriesInParallel"
// FlagWargamesTesting
// Placeholder feature flag for internal testing
FlagWargamesTesting = "wargamesTesting"
// FlagAlertingInsights
// Show the new alerting insights landing page
FlagAlertingInsights = "alertingInsights"
// FlagExternalCorePlugins
// Allow core plugins to be loaded as external
FlagExternalCorePlugins = "externalCorePlugins"
// FlagPluginsAPIMetrics
// Sends metrics of public grafana packages usage by plugins
FlagPluginsAPIMetrics = "pluginsAPIMetrics"
// FlagHttpSLOLevels
// Adds SLO level to http request metrics
FlagHttpSLOLevels = "httpSLOLevels"
// FlagIdForwarding
// Generate signed id token for identity that can be forwarded to plugins and external services
FlagIdForwarding = "idForwarding"
// FlagCloudWatchWildCardDimensionValues
// Fetches dimension values from CloudWatch to correctly label wildcard dimensions
FlagCloudWatchWildCardDimensionValues = "cloudWatchWildCardDimensionValues"
// FlagExternalServiceAccounts
// Automatic service account and token setup for plugins
FlagExternalServiceAccounts = "externalServiceAccounts"
// FlagPanelMonitoring
// Enables panel monitoring through logs and measurements
FlagPanelMonitoring = "panelMonitoring"
// FlagEnableNativeHTTPHistogram
// Enables native HTTP Histograms
FlagEnableNativeHTTPHistogram = "enableNativeHTTPHistogram"
// FlagFormatString
// Enable format string transformer
FlagFormatString = "formatString"
// FlagTransformationsVariableSupport
// Allows using variables in transformations
FlagTransformationsVariableSupport = "transformationsVariableSupport"
// FlagKubernetesPlaylists
// Use the kubernetes API in the frontend for playlists
FlagKubernetesPlaylists = "kubernetesPlaylists"
// FlagNavAdminSubsections
// Splits the administration section of the nav tree into subsections
FlagNavAdminSubsections = "navAdminSubsections"
// FlagRecoveryThreshold
// Enables feature recovery threshold (aka hysteresis) for threshold server-side expression
FlagRecoveryThreshold = "recoveryThreshold"
// FlagTeamHttpHeaders
// Enables datasources to apply team headers to the client requests
FlagTeamHttpHeaders = "teamHttpHeaders"
// FlagAwsDatasourcesNewFormStyling
// Applies new form styling for configuration and query editors in AWS plugins
FlagAwsDatasourcesNewFormStyling = "awsDatasourcesNewFormStyling"
// FlagCachingOptimizeSerializationMemoryUsage
// If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses.
FlagCachingOptimizeSerializationMemoryUsage = "cachingOptimizeSerializationMemoryUsage"
// FlagPanelTitleSearchInV1
// Enable searching for dashboards using panel title in search v1
FlagPanelTitleSearchInV1 = "panelTitleSearchInV1"
// FlagPluginsInstrumentationStatusSource
// Include a status source label for plugin request metrics and logs
FlagPluginsInstrumentationStatusSource = "pluginsInstrumentationStatusSource"
// FlagCostManagementUi
// Toggles the display of the cost management ui plugin
FlagCostManagementUi = "costManagementUi"
)
| pkg/services/featuremgmt/toggles_gen.go | 1 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.9986440539360046,
0.05132526904344559,
0.00016503145161550492,
0.00017121116979978979,
0.2109398990869522
] |
{
"id": 1,
"code_window": [
" cachingOptimizeSerializationMemoryUsage?: boolean;\n",
" panelTitleSearchInV1?: boolean;\n",
" pluginsInstrumentationStatusSource?: boolean;\n",
" costManagementUi?: boolean;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" managedPluginsInstall?: boolean;\n"
],
"file_path": "packages/grafana-data/src/types/featureToggles.gen.ts",
"type": "add",
"edit_start_line_idx": 149
} | <svg width="122" height="48" viewBox="0 0 122 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_1764_106222)">
<path d="M0 1.04083V13H54V0H2.25658C1.6581 0 0 0 0 0C0 0 0 0.764787 0 1.04083Z" fill="#CCCCDC" fill-opacity="0.04"/>
<path d="M54 18H0V31H54V18Z" fill="#CCCCDC" fill-opacity="0.12"/>
<path d="M4.28977 28.6364C3.95739 28.6364 3.64773 28.5824 3.4375 28.4972L3.74432 27.4886C4.15341 27.6222 4.45455 27.6165 4.58807 27.2898L4.64205 27.1591L3.09091 22.6364H4.54545L5.34943 25.75H5.39489L6.21023 22.6364H7.6733L6.02841 27.4176C5.78693 28.1307 5.28977 28.6364 4.28977 28.6364ZM9.0554 28.6364C8.72301 28.6364 8.41335 28.5824 8.20312 28.4972L8.50994 27.4886C8.91903 27.6222 9.22017 27.6165 9.35369 27.2898L9.40767 27.1591L7.85653 22.6364H9.31108L10.1151 25.75H10.1605L10.9759 22.6364H12.4389L10.794 27.4176C10.5526 28.1307 10.0554 28.6364 9.0554 28.6364ZM13.821 28.6364C13.4886 28.6364 13.179 28.5824 12.9688 28.4972L13.2756 27.4886C13.6847 27.6222 13.9858 27.6165 14.1193 27.2898L14.1733 27.1591L12.6222 22.6364H14.0767L14.8807 25.75H14.9261L15.7415 22.6364H17.2045L15.5597 27.4176C15.3182 28.1307 14.821 28.6364 13.821 28.6364ZM18.5866 28.6364C18.2543 28.6364 17.9446 28.5824 17.7344 28.4972L18.0412 27.4886C18.4503 27.6222 18.7514 27.6165 18.8849 27.2898L18.9389 27.1591L17.3878 22.6364H18.8423L19.6463 25.75H19.6918L20.5071 22.6364H21.9702L20.3253 27.4176C20.0838 28.1307 19.5866 28.6364 18.5866 28.6364ZM25.2955 24.1108V25.1818H22.6023V24.1108H25.2955ZM26.2763 27V22.6364H27.5973V23.4375H27.6456C27.8274 22.9062 28.282 22.5795 28.8786 22.5795C29.4837 22.5795 29.9524 22.9148 30.0689 23.4375H30.1143C30.2763 22.9176 30.7848 22.5795 31.4297 22.5795C32.2536 22.5795 32.8217 23.1392 32.8217 24.0625V27H31.4325V24.3807C31.4325 23.946 31.1825 23.7102 30.8303 23.7102C30.4467 23.7102 30.2166 23.9773 30.2166 24.3949V27H28.8814V24.3665C28.8814 23.9631 28.6428 23.7102 28.282 23.7102C27.9183 23.7102 27.6655 23.9858 27.6655 24.4176V27H26.2763ZM33.6825 27V22.6364H35.0036V23.4375H35.0518C35.2337 22.9062 35.6882 22.5795 36.2848 22.5795C36.8899 22.5795 37.3587 22.9148 37.4751 23.4375H37.5206C37.6825 22.9176 38.1911 22.5795 38.8359 22.5795C39.6598 22.5795 40.228 23.1392 40.228 24.0625V27H38.8388V24.3807C38.8388 23.946 38.5888 23.7102 38.2365 23.7102C37.853 23.7102 37.6229 23.9773 37.6229 24.3949V27H36.2876V24.3665C36.2876 23.9631 36.049 23.7102 35.6882 23.7102C35.3246 23.7102 35.0717 23.9858 35.0717 24.4176V27H33.6825ZM43.8814 24.1108V25.1818H41.1882V24.1108H43.8814ZM46.456 27.0625C45.4929 27.0625 44.7116 26.3068 44.7116 24.821C44.7116 23.2812 45.5384 22.5795 46.4503 22.5795C47.1378 22.5795 47.5185 22.983 47.6832 23.3835H47.7116V21.1818H49.1009V27H47.7259V26.2926H47.6832C47.5071 26.696 47.1151 27.0625 46.456 27.0625ZM46.9389 25.9801C47.4446 25.9801 47.7429 25.5256 47.7429 24.8182C47.7429 24.1051 47.4474 23.6648 46.9389 23.6648C46.4219 23.6648 46.1378 24.1165 46.1378 24.8182C46.1378 25.5227 46.4247 25.9801 46.9389 25.9801Z" fill="#CCCCDC" fill-opacity="0.4"/>
<path d="M54 35H0V48H54V35Z" fill="#CCCCDC" fill-opacity="0.12"/>
<path d="M5.28977 45.6364C4.95739 45.6364 4.64773 45.5824 4.4375 45.4972L4.74432 44.4886C5.15341 44.6222 5.45455 44.6165 5.58807 44.2898L5.64205 44.1591L4.09091 39.6364H5.54545L6.34943 42.75H6.39489L7.21023 39.6364H8.6733L7.02841 44.4176C6.78693 45.1307 6.28977 45.6364 5.28977 45.6364ZM10.0554 45.6364C9.72301 45.6364 9.41335 45.5824 9.20312 45.4972L9.50994 44.4886C9.91903 44.6222 10.2202 44.6165 10.3537 44.2898L10.4077 44.1591L8.85653 39.6364H10.3111L11.1151 42.75H11.1605L11.9759 39.6364H13.4389L11.794 44.4176C11.5526 45.1307 11.0554 45.6364 10.0554 45.6364ZM14.821 45.6364C14.4886 45.6364 14.179 45.5824 13.9688 45.4972L14.2756 44.4886C14.6847 44.6222 14.9858 44.6165 15.1193 44.2898L15.1733 44.1591L13.6222 39.6364H15.0767L15.8807 42.75H15.9261L16.7415 39.6364H18.2045L16.5597 44.4176C16.3182 45.1307 15.821 45.6364 14.821 45.6364ZM19.5866 45.6364C19.2543 45.6364 18.9446 45.5824 18.7344 45.4972L19.0412 44.4886C19.4503 44.6222 19.7514 44.6165 19.8849 44.2898L19.9389 44.1591L18.3878 39.6364H19.8423L20.6463 42.75H20.6918L21.5071 39.6364H22.9702L21.3253 44.4176C21.0838 45.1307 20.5866 45.6364 19.5866 45.6364ZM26.2955 41.1108V42.1818H23.6023V41.1108H26.2955ZM27.2763 44V39.6364H28.5973V40.4375H28.6456C28.8274 39.9062 29.282 39.5795 29.8786 39.5795C30.4837 39.5795 30.9524 39.9148 31.0689 40.4375H31.1143C31.2763 39.9176 31.7848 39.5795 32.4297 39.5795C33.2536 39.5795 33.8217 40.1392 33.8217 41.0625V44H32.4325V41.3807C32.4325 40.946 32.1825 40.7102 31.8303 40.7102C31.4467 40.7102 31.2166 40.9773 31.2166 41.3949V44H29.8814V41.3665C29.8814 40.9631 29.6428 40.7102 29.282 40.7102C28.9183 40.7102 28.6655 40.9858 28.6655 41.4176V44H27.2763ZM34.6825 44V39.6364H36.0036V40.4375H36.0518C36.2337 39.9062 36.6882 39.5795 37.2848 39.5795C37.8899 39.5795 38.3587 39.9148 38.4751 40.4375H38.5206C38.6825 39.9176 39.1911 39.5795 39.8359 39.5795C40.6598 39.5795 41.228 40.1392 41.228 41.0625V44H39.8388V41.3807C39.8388 40.946 39.5888 40.7102 39.2365 40.7102C38.853 40.7102 38.6229 40.9773 38.6229 41.3949V44H37.2876V41.3665C37.2876 40.9631 37.049 40.7102 36.6882 40.7102C36.3246 40.7102 36.0717 40.9858 36.0717 41.4176V44H34.6825ZM44.8814 41.1108V42.1818H42.1882V41.1108H44.8814ZM47.456 44.0625C46.4929 44.0625 45.7116 43.3068 45.7116 41.821C45.7116 40.2812 46.5384 39.5795 47.4503 39.5795C48.1378 39.5795 48.5185 39.983 48.6832 40.3835H48.7116V38.1818H50.1009V44H48.7259V43.2926H48.6832C48.5071 43.696 48.1151 44.0625 47.456 44.0625ZM47.9389 42.9801C48.4446 42.9801 48.7429 42.5256 48.7429 41.8182C48.7429 41.1051 48.4474 40.6648 47.9389 40.6648C47.4219 40.6648 47.1378 41.1165 47.1378 41.8182C47.1378 42.5227 47.4247 42.9801 47.9389 42.9801Z" fill="#CCCCDC" fill-opacity="0.4"/>
<path d="M27 3C26.3078 3 25.6311 3.20527 25.0555 3.58986C24.4799 3.97444 24.0313 4.52107 23.7664 5.16061C23.5015 5.80015 23.4322 6.50388 23.5673 7.18282C23.7023 7.86175 24.0356 8.48539 24.5251 8.97487C25.0146 9.46436 25.6383 9.7977 26.3172 9.93275C26.9961 10.0678 27.6999 9.99848 28.3394 9.73358C28.9789 9.46867 29.5256 9.02007 29.9101 8.44449C30.2947 7.86892 30.5 7.19223 30.5 6.5C30.5 6.04037 30.4095 5.58525 30.2336 5.16061C30.0577 4.73597 29.7999 4.35013 29.4749 4.02513C29.1499 3.70012 28.764 3.44231 28.3394 3.26642C27.9148 3.09053 27.4596 3 27 3ZM27 9.3C26.4462 9.3 25.9049 9.13578 25.4444 8.82811C24.9839 8.52045 24.6251 8.08315 24.4131 7.57151C24.2012 7.05988 24.1458 6.49689 24.2538 5.95375C24.3618 5.4106 24.6285 4.91169 25.0201 4.5201C25.4117 4.12851 25.9106 3.86184 26.4537 3.7538C26.9969 3.64576 27.5599 3.70121 28.0715 3.91314C28.5831 4.12506 29.0204 4.48395 29.3281 4.9444C29.6358 5.40486 29.8 5.94621 29.8 6.5C29.8 7.24261 29.505 7.9548 28.9799 8.4799C28.4548 9.005 27.7426 9.3 27 9.3ZM27 4.4C26.9072 4.4 26.8182 4.43687 26.7525 4.50251C26.6869 4.56815 26.65 4.65717 26.65 4.75V6.15H25.95C25.8572 6.15 25.7682 6.18687 25.7025 6.25251C25.6369 6.31815 25.6 6.40717 25.6 6.5C25.6 6.59283 25.6369 6.68185 25.7025 6.74749C25.7682 6.81312 25.8572 6.85 25.95 6.85H27C27.0928 6.85 27.1819 6.81312 27.2475 6.74749C27.3131 6.68185 27.35 6.59283 27.35 6.5V4.75C27.35 4.65717 27.3131 4.56815 27.2475 4.50251C27.1819 4.43687 27.0928 4.4 27 4.4Z" fill="#CCCCDC" fill-opacity="0.4"/>
</g>
<path d="M67.9067 30C68.6011 30 73.9327 26 73.9327 24C73.9327 22 68.7357 18 67.9067 18C67.0777 18 66.4023 18.5 66.4023 19.4756C66.4023 20.4512 69.9067 22.9206 69.9067 22.9206C69.9067 22.9206 62.2539 22.25 62 22.9206C61.7461 23.5911 61.7461 24.4089 62 25.0794C62.2539 25.75 69.9067 25.0794 69.9067 25.0794C69.9067 25.0794 66.4023 27.75 66.4023 28.5301C66.4023 29.3103 67.2123 30 67.9067 30Z" fill="#CCCCDC" fill-opacity="0.4"/>
<path d="M82 1.04083V13H122V0H83.6715H82V1.04083Z" fill="#CCCCDC" fill-opacity="0.04"/>
<path d="M122 18H82V31H122V18Z" fill="#CCCCDC" fill-opacity="0.12"/>
<path d="M88.4403 27.5V23.1364H89.7614V23.9375H89.8097C89.9915 23.4062 90.446 23.0795 91.0426 23.0795C91.6477 23.0795 92.1165 23.4148 92.233 23.9375H92.2784C92.4403 23.4176 92.9489 23.0795 93.5938 23.0795C94.4176 23.0795 94.9858 23.6392 94.9858 24.5625V27.5H93.5966V24.8807C93.5966 24.446 93.3466 24.2102 92.9943 24.2102C92.6108 24.2102 92.3807 24.4773 92.3807 24.8949V27.5H91.0455V24.8665C91.0455 24.4631 90.8068 24.2102 90.446 24.2102C90.0824 24.2102 89.8295 24.4858 89.8295 24.9176V27.5H88.4403ZM95.8466 27.5V23.1364H97.1676V23.9375H97.2159C97.3977 23.4062 97.8523 23.0795 98.4489 23.0795C99.054 23.0795 99.5227 23.4148 99.6392 23.9375H99.6847C99.8466 23.4176 100.355 23.0795 101 23.0795C101.824 23.0795 102.392 23.6392 102.392 24.5625V27.5H101.003V24.8807C101.003 24.446 100.753 24.2102 100.401 24.2102C100.017 24.2102 99.7869 24.4773 99.7869 24.8949V27.5H98.4517V24.8665C98.4517 24.4631 98.2131 24.2102 97.8523 24.2102C97.4886 24.2102 97.2358 24.4858 97.2358 24.9176V27.5H95.8466ZM106.045 24.6108V25.6818H103.352V24.6108H106.045ZM108.62 27.5625C107.657 27.5625 106.876 26.8068 106.876 25.321C106.876 23.7812 107.702 23.0795 108.614 23.0795C109.302 23.0795 109.683 23.483 109.847 23.8835H109.876V21.6818H111.265V27.5H109.89V26.7926H109.847C109.671 27.196 109.279 27.5625 108.62 27.5625ZM109.103 26.4801C109.609 26.4801 109.907 26.0256 109.907 25.3182C109.907 24.6051 109.612 24.1648 109.103 24.1648C108.586 24.1648 108.302 24.6165 108.302 25.3182C108.302 26.0227 108.589 26.4801 109.103 26.4801ZM113.737 27.5625C112.774 27.5625 111.993 26.8068 111.993 25.321C111.993 23.7812 112.82 23.0795 113.732 23.0795C114.419 23.0795 114.8 23.483 114.964 23.8835H114.993V21.6818H116.382V27.5H115.007V26.7926H114.964C114.788 27.196 114.396 27.5625 113.737 27.5625ZM114.22 26.4801C114.726 26.4801 115.024 26.0256 115.024 25.3182C115.024 24.6051 114.729 24.1648 114.22 24.1648C113.703 24.1648 113.419 24.6165 113.419 25.3182C113.419 26.0227 113.706 26.4801 114.22 26.4801Z" fill="#CCCCDC" fill-opacity="0.4"/>
<path d="M122 35H82V48H122V35Z" fill="#CCCCDC" fill-opacity="0.12"/>
<path d="M102 3C101.308 3 100.631 3.20527 100.056 3.58986C99.4799 3.97444 99.0313 4.52107 98.7664 5.16061C98.5015 5.80015 98.4322 6.50388 98.5673 7.18282C98.7023 7.86175 99.0356 8.48539 99.5251 8.97487C100.015 9.46436 100.638 9.7977 101.317 9.93275C101.996 10.0678 102.7 9.99848 103.339 9.73358C103.979 9.46867 104.526 9.02007 104.91 8.44449C105.295 7.86892 105.5 7.19223 105.5 6.5C105.5 6.04037 105.409 5.58525 105.234 5.16061C105.058 4.73597 104.8 4.35013 104.475 4.02513C104.15 3.70012 103.764 3.44231 103.339 3.26642C102.915 3.09053 102.46 3 102 3ZM102 9.3C101.446 9.3 100.905 9.13578 100.444 8.82811C99.9839 8.52045 99.6251 8.08315 99.4131 7.57151C99.2012 7.05988 99.1458 6.49689 99.2538 5.95375C99.3618 5.4106 99.6285 4.91169 100.02 4.5201C100.412 4.12851 100.911 3.86184 101.454 3.7538C101.997 3.64576 102.56 3.70121 103.072 3.91314C103.583 4.12506 104.02 4.48395 104.328 4.9444C104.636 5.40486 104.8 5.94621 104.8 6.5C104.8 7.24261 104.505 7.9548 103.98 8.4799C103.455 9.005 102.743 9.3 102 9.3ZM102 4.4C101.907 4.4 101.818 4.43687 101.753 4.50251C101.687 4.56815 101.65 4.65717 101.65 4.75V6.15H100.95C100.857 6.15 100.768 6.18687 100.703 6.25251C100.637 6.31815 100.6 6.40717 100.6 6.5C100.6 6.59283 100.637 6.68185 100.703 6.74749C100.768 6.81312 100.857 6.85 100.95 6.85H102C102.093 6.85 102.182 6.81312 102.247 6.74749C102.313 6.68185 102.35 6.59283 102.35 6.5V4.75C102.35 4.65717 102.313 4.56815 102.247 4.50251C102.182 4.43687 102.093 4.4 102 4.4Z" fill="#CCCCDC" fill-opacity="0.4"/>
<path d="M93.2898 45.6364C92.9574 45.6364 92.6477 45.5824 92.4375 45.4972L92.7443 44.4886C93.1534 44.6222 93.4545 44.6165 93.5881 44.2898L93.642 44.1591L92.0909 39.6364H93.5455L94.3494 42.75H94.3949L95.2102 39.6364H96.6733L95.0284 44.4176C94.7869 45.1307 94.2898 45.6364 93.2898 45.6364ZM98.0554 45.6364C97.723 45.6364 97.4134 45.5824 97.2031 45.4972L97.5099 44.4886C97.919 44.6222 98.2202 44.6165 98.3537 44.2898L98.4077 44.1591L96.8565 39.6364H98.3111L99.1151 42.75H99.1605L99.9759 39.6364H101.439L99.794 44.4176C99.5526 45.1307 99.0554 45.6364 98.0554 45.6364ZM102.821 45.6364C102.489 45.6364 102.179 45.5824 101.969 45.4972L102.276 44.4886C102.685 44.6222 102.986 44.6165 103.119 44.2898L103.173 44.1591L101.622 39.6364H103.077L103.881 42.75H103.926L104.741 39.6364H106.205L104.56 44.4176C104.318 45.1307 103.821 45.6364 102.821 45.6364ZM107.587 45.6364C107.254 45.6364 106.945 45.5824 106.734 45.4972L107.041 44.4886C107.45 44.6222 107.751 44.6165 107.885 44.2898L107.939 44.1591L106.388 39.6364H107.842L108.646 42.75H108.692L109.507 39.6364H110.97L109.325 44.4176C109.084 45.1307 108.587 45.6364 107.587 45.6364Z" fill="#CCCCDC" fill-opacity="0.4"/>
<defs>
<clipPath id="clip0_1764_106222">
<rect width="54" height="48" fill="white"/>
</clipPath>
</defs>
</svg>
| public/img/transformations/disabled/formatTime.svg | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.003196962643414736,
0.0017626344924792647,
0.00017736268637236208,
0.0019135781330987811,
0.001237358432263136
] |
{
"id": 1,
"code_window": [
" cachingOptimizeSerializationMemoryUsage?: boolean;\n",
" panelTitleSearchInV1?: boolean;\n",
" pluginsInstrumentationStatusSource?: boolean;\n",
" costManagementUi?: boolean;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" managedPluginsInstall?: boolean;\n"
],
"file_path": "packages/grafana-data/src/types/featureToggles.gen.ts",
"type": "add",
"edit_start_line_idx": 149
} | import { css, cx } from '@emotion/css';
import React from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { stylesFactory, useStyles2 } from '../../themes';
import { Alert, AlertVariant } from '../Alert/Alert';
import { Icon } from '../Icon/Icon';
export interface InfoBoxProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
children: React.ReactNode;
/** Title of the box */
title?: string | JSX.Element;
/** Url of the read more link */
url?: string;
/** Text of the read more link */
urlTitle?: string;
/** Indicates whether or not box should be rendered with Grafana branding background */
branded?: boolean;
/** Color variant of the box */
severity?: AlertVariant;
/** Call back to be performed when box is dismissed */
onDismiss?: () => void;
}
/** @deprecated use Alert with severity info */
export const InfoBox = React.memo(
React.forwardRef<HTMLDivElement, InfoBoxProps>(
({ title, className, children, branded, url, urlTitle, onDismiss, severity = 'info', ...otherProps }, ref) => {
const styles = useStyles2(getStyles);
return (
<Alert severity={severity} className={className} {...otherProps} ref={ref} title={title as string}>
<div>{children}</div>
{url && (
<a href={url} className={cx('external-link', styles.docsLink)} target="_blank" rel="noreferrer">
<Icon name="book" /> {urlTitle || 'Read more'}
</a>
)}
</Alert>
);
}
)
);
InfoBox.displayName = 'InfoBox';
const getStyles = stylesFactory((theme: GrafanaTheme2) => {
return {
docsLink: css({
display: 'inline-block',
marginTop: theme.spacing(2),
}),
};
});
| packages/grafana-ui/src/components/InfoBox/InfoBox.tsx | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.00017603370361030102,
0.00017351727001369,
0.00017128336185123771,
0.0001733383978717029,
0.0000016486116010128171
] |
{
"id": 1,
"code_window": [
" cachingOptimizeSerializationMemoryUsage?: boolean;\n",
" panelTitleSearchInV1?: boolean;\n",
" pluginsInstrumentationStatusSource?: boolean;\n",
" costManagementUi?: boolean;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" managedPluginsInstall?: boolean;\n"
],
"file_path": "packages/grafana-data/src/types/featureToggles.gen.ts",
"type": "add",
"edit_start_line_idx": 149
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21,2H3A1,1,0,0,0,2,3V21a1,1,0,0,0,1,1H21a1,1,0,0,0,1-1V3A1,1,0,0,0,21,2ZM14,20H4V4H14Zm6,0H16V4h4Z"/></svg> | public/img/icons/unicons/web-section.svg | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.00016957057232502848,
0.00016957057232502848,
0.00016957057232502848,
0.00016957057232502848,
0
] |
{
"id": 2,
"code_window": [
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tFrontendOnly: false,\n",
"\t\t\tOwner: grafanaDatabasesFrontend,\n",
"\t\t},\n",
"\t}\n",
")"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\t{\n",
"\t\t\tName: \"managedPluginsInstall\",\n",
"\t\t\tDescription: \"Install managed plugins directly from plugins catalog\",\n",
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tRequiresDevMode: false,\n",
"\t\t\tOwner: grafanaPluginsPlatformSquad,\n",
"\t\t},\n"
],
"file_path": "pkg/services/featuremgmt/registry.go",
"type": "add",
"edit_start_line_idx": 906
} | // NOTE: This file was auto generated. DO NOT EDIT DIRECTLY!
// To change feature flags, edit:
// pkg/services/featuremgmt/registry.go
// Then run tests in:
// pkg/services/featuremgmt/toggles_gen_test.go
/**
* Describes available feature toggles in Grafana. These can be configured via
* conf/custom.ini to enable features under development or not yet available in
* stable version.
*
* Only enabled values will be returned in this interface.
*
* NOTE: the possible values may change between versions without notice, although
* this may cause compilation issues when depending on removed feature keys, the
* runtime state will continue to work.
*
* @public
*/
export interface FeatureToggles {
trimDefaults?: boolean;
disableEnvelopeEncryption?: boolean;
['live-service-web-worker']?: boolean;
queryOverLive?: boolean;
panelTitleSearch?: boolean;
publicDashboards?: boolean;
publicDashboardsEmailSharing?: boolean;
lokiExperimentalStreaming?: boolean;
featureHighlights?: boolean;
migrationLocking?: boolean;
storage?: boolean;
correlations?: boolean;
exploreContentOutline?: boolean;
datasourceQueryMultiStatus?: boolean;
traceToMetrics?: boolean;
newDBLibrary?: boolean;
autoMigrateOldPanels?: boolean;
disableAngular?: boolean;
canvasPanelNesting?: boolean;
scenes?: boolean;
disableSecretsCompatibility?: boolean;
logRequestsInstrumentedAsUnknown?: boolean;
dataConnectionsConsole?: boolean;
topnav?: boolean;
dockedMegaMenu?: boolean;
grpcServer?: boolean;
entityStore?: boolean;
cloudWatchCrossAccountQuerying?: boolean;
redshiftAsyncQueryDataSupport?: boolean;
athenaAsyncQueryDataSupport?: boolean;
cloudwatchNewRegionsHandler?: boolean;
showDashboardValidationWarnings?: boolean;
mysqlAnsiQuotes?: boolean;
accessControlOnCall?: boolean;
nestedFolders?: boolean;
nestedFolderPicker?: boolean;
accessTokenExpirationCheck?: boolean;
emptyDashboardPage?: boolean;
disablePrometheusExemplarSampling?: boolean;
alertingBacktesting?: boolean;
editPanelCSVDragAndDrop?: boolean;
alertingNoNormalState?: boolean;
logsContextDatasourceUi?: boolean;
lokiQuerySplitting?: boolean;
lokiQuerySplittingConfig?: boolean;
individualCookiePreferences?: boolean;
gcomOnlyExternalOrgRoleSync?: boolean;
prometheusMetricEncyclopedia?: boolean;
influxdbBackendMigration?: boolean;
clientTokenRotation?: boolean;
prometheusDataplane?: boolean;
lokiMetricDataplane?: boolean;
lokiLogsDataplane?: boolean;
dataplaneFrontendFallback?: boolean;
disableSSEDataplane?: boolean;
alertStateHistoryLokiSecondary?: boolean;
alertingNotificationsPoliciesMatchingInstances?: boolean;
alertStateHistoryLokiPrimary?: boolean;
alertStateHistoryLokiOnly?: boolean;
unifiedRequestLog?: boolean;
renderAuthJWT?: boolean;
externalServiceAuth?: boolean;
refactorVariablesTimeRange?: boolean;
useCachingService?: boolean;
enableElasticsearchBackendQuerying?: boolean;
advancedDataSourcePicker?: boolean;
faroDatasourceSelector?: boolean;
enableDatagridEditing?: boolean;
dataSourcePageHeader?: boolean;
extraThemes?: boolean;
lokiPredefinedOperations?: boolean;
pluginsFrontendSandbox?: boolean;
dashboardEmbed?: boolean;
frontendSandboxMonitorOnly?: boolean;
sqlDatasourceDatabaseSelection?: boolean;
lokiFormatQuery?: boolean;
cloudWatchLogsMonacoEditor?: boolean;
exploreScrollableLogsContainer?: boolean;
recordedQueriesMulti?: boolean;
pluginsDynamicAngularDetectionPatterns?: boolean;
vizAndWidgetSplit?: boolean;
prometheusIncrementalQueryInstrumentation?: boolean;
logsExploreTableVisualisation?: boolean;
awsDatasourcesTempCredentials?: boolean;
transformationsRedesign?: boolean;
toggleLabelsInLogsUI?: boolean;
mlExpressions?: boolean;
traceQLStreaming?: boolean;
metricsSummary?: boolean;
grafanaAPIServer?: boolean;
grafanaAPIServerWithExperimentalAPIs?: boolean;
featureToggleAdminPage?: boolean;
awsAsyncQueryCaching?: boolean;
splitScopes?: boolean;
azureMonitorDataplane?: boolean;
permissionsFilterRemoveSubquery?: boolean;
prometheusConfigOverhaulAuth?: boolean;
configurableSchedulerTick?: boolean;
influxdbSqlSupport?: boolean;
alertingNoDataErrorExecution?: boolean;
angularDeprecationUI?: boolean;
dashgpt?: boolean;
reportingRetries?: boolean;
newBrowseDashboards?: boolean;
sseGroupByDatasource?: boolean;
requestInstrumentationStatusSource?: boolean;
libraryPanelRBAC?: boolean;
lokiRunQueriesInParallel?: boolean;
wargamesTesting?: boolean;
alertingInsights?: boolean;
externalCorePlugins?: boolean;
pluginsAPIMetrics?: boolean;
httpSLOLevels?: boolean;
idForwarding?: boolean;
cloudWatchWildCardDimensionValues?: boolean;
externalServiceAccounts?: boolean;
panelMonitoring?: boolean;
enableNativeHTTPHistogram?: boolean;
formatString?: boolean;
transformationsVariableSupport?: boolean;
kubernetesPlaylists?: boolean;
navAdminSubsections?: boolean;
recoveryThreshold?: boolean;
teamHttpHeaders?: boolean;
awsDatasourcesNewFormStyling?: boolean;
cachingOptimizeSerializationMemoryUsage?: boolean;
panelTitleSearchInV1?: boolean;
pluginsInstrumentationStatusSource?: boolean;
costManagementUi?: boolean;
}
| packages/grafana-data/src/types/featureToggles.gen.ts | 1 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0014177286066114902,
0.0002561185392551124,
0.00016445510846097022,
0.00016724511806387454,
0.00030127764330245554
] |
{
"id": 2,
"code_window": [
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tFrontendOnly: false,\n",
"\t\t\tOwner: grafanaDatabasesFrontend,\n",
"\t\t},\n",
"\t}\n",
")"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\t{\n",
"\t\t\tName: \"managedPluginsInstall\",\n",
"\t\t\tDescription: \"Install managed plugins directly from plugins catalog\",\n",
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tRequiresDevMode: false,\n",
"\t\t\tOwner: grafanaPluginsPlatformSquad,\n",
"\t\t},\n"
],
"file_path": "pkg/services/featuremgmt/registry.go",
"type": "add",
"edit_start_line_idx": 906
} | package folder
import (
"context"
)
type Service interface {
// GetChildren returns an array containing all child folders.
GetChildren(ctx context.Context, cmd *GetChildrenQuery) ([]*Folder, error)
// GetParents returns an array containing add parent folders if nested folders are enabled
// otherwise it returns an empty array
GetParents(ctx context.Context, q GetParentsQuery) ([]*Folder, error)
Create(ctx context.Context, cmd *CreateFolderCommand) (*Folder, error)
// GetFolder takes a GetFolderCommand and returns a folder matching the
// request. One of ID, UID, or Title must be included. If multiple values
// are included in the request, Grafana will select one in order of
// specificity (ID, UID, Title).
Get(ctx context.Context, cmd *GetFolderQuery) (*Folder, error)
// Update is used to update a folder's UID, Title and Description. To change
// a folder's parent folder, use Move.
Update(ctx context.Context, cmd *UpdateFolderCommand) (*Folder, error)
Delete(ctx context.Context, cmd *DeleteFolderCommand) error
// Move changes a folder's parent folder to the requested new parent.
Move(ctx context.Context, cmd *MoveFolderCommand) (*Folder, error)
RegisterService(service RegistryService) error
GetDescendantCounts(ctx context.Context, cmd *GetDescendantCountsQuery) (DescendantCounts, error)
}
// FolderStore is a folder store.
//
//go:generate mockery --name FolderStore --structname FakeFolderStore --outpkg foldertest --output foldertest --filename folder_store_mock.go
type FolderStore interface {
// GetFolderByTitle retrieves a folder by its title
GetFolderByTitle(ctx context.Context, orgID int64, title string) (*Folder, error)
// GetFolderByUID retrieves a folder by its UID
GetFolderByUID(ctx context.Context, orgID int64, uid string) (*Folder, error)
// GetFolderByID retrieves a folder by its ID
GetFolderByID(ctx context.Context, orgID int64, id int64) (*Folder, error)
// GetFolders returns all folders for the given orgID and UIDs.
GetFolders(ctx context.Context, orgID int64, uids []string) (map[string]*Folder, error)
}
| pkg/services/folder/service.go | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.00018586352234706283,
0.0001704637979855761,
0.00016239382966887206,
0.00016615803178865463,
0.000008343183253600728
] |
{
"id": 2,
"code_window": [
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tFrontendOnly: false,\n",
"\t\t\tOwner: grafanaDatabasesFrontend,\n",
"\t\t},\n",
"\t}\n",
")"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\t{\n",
"\t\t\tName: \"managedPluginsInstall\",\n",
"\t\t\tDescription: \"Install managed plugins directly from plugins catalog\",\n",
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tRequiresDevMode: false,\n",
"\t\t\tOwner: grafanaPluginsPlatformSquad,\n",
"\t\t},\n"
],
"file_path": "pkg/services/featuremgmt/registry.go",
"type": "add",
"edit_start_line_idx": 906
} | package queryhistory
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/web"
)
func TestIntegrationPatchQueryCommentInQueryHistory(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
testScenarioWithQueryInQueryHistory(t, "When user tries to patch comment of query in query history that does not exist, it should fail",
func(t *testing.T, sc scenarioContext) {
resp := sc.service.patchCommentHandler(sc.reqContext)
require.Equal(t, 500, resp.Status())
})
testScenarioWithQueryInQueryHistory(t, "When user tries to patch comment of query in query history that exists, it should succeed",
func(t *testing.T, sc scenarioContext) {
cmd := PatchQueryCommentInQueryHistoryCommand{Comment: "test comment"}
sc.ctx.Req = web.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
sc.reqContext.Req.Body = mockRequestBody(cmd)
resp := sc.service.patchCommentHandler(sc.reqContext)
require.Equal(t, 200, resp.Status())
})
}
| pkg/services/queryhistory/queryhistory_patch_test.go | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.00016959889035206288,
0.00016854026762302965,
0.00016786789637990296,
0.0001681540161371231,
7.576180678370292e-7
] |
{
"id": 2,
"code_window": [
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tFrontendOnly: false,\n",
"\t\t\tOwner: grafanaDatabasesFrontend,\n",
"\t\t},\n",
"\t}\n",
")"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\t{\n",
"\t\t\tName: \"managedPluginsInstall\",\n",
"\t\t\tDescription: \"Install managed plugins directly from plugins catalog\",\n",
"\t\t\tStage: FeatureStageExperimental,\n",
"\t\t\tRequiresDevMode: false,\n",
"\t\t\tOwner: grafanaPluginsPlatformSquad,\n",
"\t\t},\n"
],
"file_path": "pkg/services/featuremgmt/registry.go",
"type": "add",
"edit_start_line_idx": 906
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9,11a1,1,0,1,0,1,1A1,1,0,0,0,9,11Zm8-9H7A5,5,0,0,0,2,7V17a5,5,0,0,0,5,5H17a5,5,0,0,0,5-5V7A5,5,0,0,0,17,2Zm3,15a3,3,0,0,1-3,3H7a3,3,0,0,1-3-3V7A3,3,0,0,1,7,4H17a3,3,0,0,1,3,3Zm-5-6a1,1,0,1,0,1,1A1,1,0,0,0,15,11Z"/></svg> | public/img/icons/unicons/dice-two.svg | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0001712147641228512,
0.0001712147641228512,
0.0001712147641228512,
0.0001712147641228512,
0
] |
{
"id": 3,
"code_window": [
"cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false\n",
"panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false\n",
"pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false\n",
"costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"managedPluginsInstall,experimental,@grafana/plugins-platform-backend,false,false,false,false"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.csv",
"type": "add",
"edit_start_line_idx": 130
} | // NOTE: This file was auto generated. DO NOT EDIT DIRECTLY!
// To change feature flags, edit:
// pkg/services/featuremgmt/registry.go
// Then run tests in:
// pkg/services/featuremgmt/toggles_gen_test.go
/**
* Describes available feature toggles in Grafana. These can be configured via
* conf/custom.ini to enable features under development or not yet available in
* stable version.
*
* Only enabled values will be returned in this interface.
*
* NOTE: the possible values may change between versions without notice, although
* this may cause compilation issues when depending on removed feature keys, the
* runtime state will continue to work.
*
* @public
*/
export interface FeatureToggles {
trimDefaults?: boolean;
disableEnvelopeEncryption?: boolean;
['live-service-web-worker']?: boolean;
queryOverLive?: boolean;
panelTitleSearch?: boolean;
publicDashboards?: boolean;
publicDashboardsEmailSharing?: boolean;
lokiExperimentalStreaming?: boolean;
featureHighlights?: boolean;
migrationLocking?: boolean;
storage?: boolean;
correlations?: boolean;
exploreContentOutline?: boolean;
datasourceQueryMultiStatus?: boolean;
traceToMetrics?: boolean;
newDBLibrary?: boolean;
autoMigrateOldPanels?: boolean;
disableAngular?: boolean;
canvasPanelNesting?: boolean;
scenes?: boolean;
disableSecretsCompatibility?: boolean;
logRequestsInstrumentedAsUnknown?: boolean;
dataConnectionsConsole?: boolean;
topnav?: boolean;
dockedMegaMenu?: boolean;
grpcServer?: boolean;
entityStore?: boolean;
cloudWatchCrossAccountQuerying?: boolean;
redshiftAsyncQueryDataSupport?: boolean;
athenaAsyncQueryDataSupport?: boolean;
cloudwatchNewRegionsHandler?: boolean;
showDashboardValidationWarnings?: boolean;
mysqlAnsiQuotes?: boolean;
accessControlOnCall?: boolean;
nestedFolders?: boolean;
nestedFolderPicker?: boolean;
accessTokenExpirationCheck?: boolean;
emptyDashboardPage?: boolean;
disablePrometheusExemplarSampling?: boolean;
alertingBacktesting?: boolean;
editPanelCSVDragAndDrop?: boolean;
alertingNoNormalState?: boolean;
logsContextDatasourceUi?: boolean;
lokiQuerySplitting?: boolean;
lokiQuerySplittingConfig?: boolean;
individualCookiePreferences?: boolean;
gcomOnlyExternalOrgRoleSync?: boolean;
prometheusMetricEncyclopedia?: boolean;
influxdbBackendMigration?: boolean;
clientTokenRotation?: boolean;
prometheusDataplane?: boolean;
lokiMetricDataplane?: boolean;
lokiLogsDataplane?: boolean;
dataplaneFrontendFallback?: boolean;
disableSSEDataplane?: boolean;
alertStateHistoryLokiSecondary?: boolean;
alertingNotificationsPoliciesMatchingInstances?: boolean;
alertStateHistoryLokiPrimary?: boolean;
alertStateHistoryLokiOnly?: boolean;
unifiedRequestLog?: boolean;
renderAuthJWT?: boolean;
externalServiceAuth?: boolean;
refactorVariablesTimeRange?: boolean;
useCachingService?: boolean;
enableElasticsearchBackendQuerying?: boolean;
advancedDataSourcePicker?: boolean;
faroDatasourceSelector?: boolean;
enableDatagridEditing?: boolean;
dataSourcePageHeader?: boolean;
extraThemes?: boolean;
lokiPredefinedOperations?: boolean;
pluginsFrontendSandbox?: boolean;
dashboardEmbed?: boolean;
frontendSandboxMonitorOnly?: boolean;
sqlDatasourceDatabaseSelection?: boolean;
lokiFormatQuery?: boolean;
cloudWatchLogsMonacoEditor?: boolean;
exploreScrollableLogsContainer?: boolean;
recordedQueriesMulti?: boolean;
pluginsDynamicAngularDetectionPatterns?: boolean;
vizAndWidgetSplit?: boolean;
prometheusIncrementalQueryInstrumentation?: boolean;
logsExploreTableVisualisation?: boolean;
awsDatasourcesTempCredentials?: boolean;
transformationsRedesign?: boolean;
toggleLabelsInLogsUI?: boolean;
mlExpressions?: boolean;
traceQLStreaming?: boolean;
metricsSummary?: boolean;
grafanaAPIServer?: boolean;
grafanaAPIServerWithExperimentalAPIs?: boolean;
featureToggleAdminPage?: boolean;
awsAsyncQueryCaching?: boolean;
splitScopes?: boolean;
azureMonitorDataplane?: boolean;
permissionsFilterRemoveSubquery?: boolean;
prometheusConfigOverhaulAuth?: boolean;
configurableSchedulerTick?: boolean;
influxdbSqlSupport?: boolean;
alertingNoDataErrorExecution?: boolean;
angularDeprecationUI?: boolean;
dashgpt?: boolean;
reportingRetries?: boolean;
newBrowseDashboards?: boolean;
sseGroupByDatasource?: boolean;
requestInstrumentationStatusSource?: boolean;
libraryPanelRBAC?: boolean;
lokiRunQueriesInParallel?: boolean;
wargamesTesting?: boolean;
alertingInsights?: boolean;
externalCorePlugins?: boolean;
pluginsAPIMetrics?: boolean;
httpSLOLevels?: boolean;
idForwarding?: boolean;
cloudWatchWildCardDimensionValues?: boolean;
externalServiceAccounts?: boolean;
panelMonitoring?: boolean;
enableNativeHTTPHistogram?: boolean;
formatString?: boolean;
transformationsVariableSupport?: boolean;
kubernetesPlaylists?: boolean;
navAdminSubsections?: boolean;
recoveryThreshold?: boolean;
teamHttpHeaders?: boolean;
awsDatasourcesNewFormStyling?: boolean;
cachingOptimizeSerializationMemoryUsage?: boolean;
panelTitleSearchInV1?: boolean;
pluginsInstrumentationStatusSource?: boolean;
costManagementUi?: boolean;
}
| packages/grafana-data/src/types/featureToggles.gen.ts | 1 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.9770810008049011,
0.06277038156986237,
0.00016183503612410277,
0.0001895942259579897,
0.23610973358154297
] |
{
"id": 3,
"code_window": [
"cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false\n",
"panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false\n",
"pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false\n",
"costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"managedPluginsInstall,experimental,@grafana/plugins-platform-backend,false,false,false,false"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.csv",
"type": "add",
"edit_start_line_idx": 130
} | import React from 'react';
import { SelectableValue } from '@grafana/data';
import { RadioButtonGroup } from '@grafana/ui';
import { EXPLORE_GRAPH_STYLES, ExploreGraphStyle } from 'app/types';
const ALL_GRAPH_STYLE_OPTIONS: Array<SelectableValue<ExploreGraphStyle>> = EXPLORE_GRAPH_STYLES.map((style) => ({
value: style,
// capital-case it and switch `_` to ` `
label: style[0].toUpperCase() + style.slice(1).replace(/_/, ' '),
}));
type Props = {
graphStyle: ExploreGraphStyle;
onChangeGraphStyle: (style: ExploreGraphStyle) => void;
};
export function ExploreGraphLabel(props: Props) {
const { graphStyle, onChangeGraphStyle } = props;
return (
<RadioButtonGroup size="sm" options={ALL_GRAPH_STYLE_OPTIONS} value={graphStyle} onChange={onChangeGraphStyle} />
);
}
| public/app/features/explore/Graph/ExploreGraphLabel.tsx | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0001734597608447075,
0.0001707333285594359,
0.00016644997231196612,
0.00017229023796971887,
0.000003066188810407766
] |
{
"id": 3,
"code_window": [
"cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false\n",
"panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false\n",
"pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false\n",
"costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"managedPluginsInstall,experimental,@grafana/plugins-platform-backend,false,false,false,false"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.csv",
"type": "add",
"edit_start_line_idx": 130
} | package api
import (
"github.com/grafana/grafana/pkg/api/response"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/datasources"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
)
type AlertmanagerApiHandler struct {
AMSvc *LotexAM
GrafanaSvc *AlertmanagerSrv
DatasourceCache datasources.CacheService
}
// NewForkingAM implements a set of routes that proxy to various Alertmanager-compatible backends.
func NewForkingAM(datasourceCache datasources.CacheService, proxy *LotexAM, grafana *AlertmanagerSrv) *AlertmanagerApiHandler {
return &AlertmanagerApiHandler{
AMSvc: proxy,
GrafanaSvc: grafana,
DatasourceCache: datasourceCache,
}
}
func (f *AlertmanagerApiHandler) getService(ctx *contextmodel.ReqContext) (*LotexAM, error) {
_, err := getDatasourceByUID(ctx, f.DatasourceCache, apimodels.AlertmanagerBackend)
if err != nil {
return nil, err
}
return f.AMSvc, nil
}
func (f *AlertmanagerApiHandler) handleRouteGetAMStatus(ctx *contextmodel.ReqContext, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteGetAMStatus(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteCreateSilence(ctx *contextmodel.ReqContext, body apimodels.PostableSilence, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteCreateSilence(ctx, body)
}
func (f *AlertmanagerApiHandler) handleRouteDeleteAlertingConfig(ctx *contextmodel.ReqContext, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteDeleteAlertingConfig(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteDeleteSilence(ctx *contextmodel.ReqContext, silenceID string, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteDeleteSilence(ctx, silenceID)
}
func (f *AlertmanagerApiHandler) handleRouteGetAlertingConfig(ctx *contextmodel.ReqContext, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteGetAlertingConfig(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetAMAlertGroups(ctx *contextmodel.ReqContext, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteGetAMAlertGroups(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetAMAlerts(ctx *contextmodel.ReqContext, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteGetAMAlerts(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetSilence(ctx *contextmodel.ReqContext, silenceID string, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteGetSilence(ctx, silenceID)
}
func (f *AlertmanagerApiHandler) handleRouteGetSilences(ctx *contextmodel.ReqContext, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RouteGetSilences(ctx)
}
func (f *AlertmanagerApiHandler) handleRoutePostAlertingConfig(ctx *contextmodel.ReqContext, body apimodels.PostableUserConfig, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
if !body.AlertmanagerConfig.ReceiverType().Can(apimodels.AlertmanagerReceiverType) {
return errorToResponse(backendTypeDoesNotMatchPayloadTypeError(apimodels.AlertmanagerBackend, body.AlertmanagerConfig.ReceiverType().String()))
}
return s.RoutePostAlertingConfig(ctx, body)
}
func (f *AlertmanagerApiHandler) handleRoutePostAMAlerts(ctx *contextmodel.ReqContext, body apimodels.PostableAlerts, dsUID string) response.Response {
s, err := f.getService(ctx)
if err != nil {
return errorToResponse(err)
}
return s.RoutePostAMAlerts(ctx, body)
}
func (f *AlertmanagerApiHandler) handleRouteDeleteGrafanaSilence(ctx *contextmodel.ReqContext, id string) response.Response {
return f.GrafanaSvc.RouteDeleteSilence(ctx, id)
}
func (f *AlertmanagerApiHandler) handleRouteDeleteGrafanaAlertingConfig(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteDeleteAlertingConfig(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteCreateGrafanaSilence(ctx *contextmodel.ReqContext, body apimodels.PostableSilence) response.Response {
return f.GrafanaSvc.RouteCreateSilence(ctx, body)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaAMStatus(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetAMStatus(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaAMAlerts(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetAMAlerts(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaAMAlertGroups(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetAMAlertGroups(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaAlertingConfig(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetAlertingConfig(ctx)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaAlertingConfigHistory(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetAlertingConfigHistory(ctx)
}
func (f *AlertmanagerApiHandler) handleRoutePostGrafanaAlertingConfigHistoryActivate(ctx *contextmodel.ReqContext, id string) response.Response {
return f.GrafanaSvc.RoutePostGrafanaAlertingConfigHistoryActivate(ctx, id)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaSilence(ctx *contextmodel.ReqContext, id string) response.Response {
return f.GrafanaSvc.RouteGetSilence(ctx, id)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaSilences(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetSilences(ctx)
}
func (f *AlertmanagerApiHandler) handleRoutePostGrafanaAlertingConfig(ctx *contextmodel.ReqContext, conf apimodels.PostableUserConfig) response.Response {
if !conf.AlertmanagerConfig.ReceiverType().Can(apimodels.GrafanaReceiverType) {
return errorToResponse(backendTypeDoesNotMatchPayloadTypeError(apimodels.GrafanaBackend, conf.AlertmanagerConfig.ReceiverType().String()))
}
return f.GrafanaSvc.RoutePostAlertingConfig(ctx, conf)
}
func (f *AlertmanagerApiHandler) handleRouteGetGrafanaReceivers(ctx *contextmodel.ReqContext) response.Response {
return f.GrafanaSvc.RouteGetReceivers(ctx)
}
func (f *AlertmanagerApiHandler) handleRoutePostTestGrafanaReceivers(ctx *contextmodel.ReqContext, conf apimodels.TestReceiversConfigBodyParams) response.Response {
return f.GrafanaSvc.RoutePostTestReceivers(ctx, conf)
}
func (f *AlertmanagerApiHandler) handleRoutePostTestGrafanaTemplates(ctx *contextmodel.ReqContext, conf apimodels.TestTemplatesConfigBodyParams) response.Response {
return f.GrafanaSvc.RoutePostTestTemplates(ctx, conf)
}
| pkg/services/ngalert/api/forking_alertmanager.go | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.00028877242584712803,
0.00018901791190728545,
0.00016116330516524613,
0.00016951371799223125,
0.00004032272408949211
] |
{
"id": 3,
"code_window": [
"cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false\n",
"panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false\n",
"pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false\n",
"costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"managedPluginsInstall,experimental,@grafana/plugins-platform-backend,false,false,false,false"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.csv",
"type": "add",
"edit_start_line_idx": 130
} | package userimpl
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotaimpl"
"github.com/grafana/grafana/pkg/services/searchusers/sortopts"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/supportbundles/supportbundlestest"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
func TestIntegrationUserGet(t *testing.T) {
testCases := []struct {
name string
wantErr error
searchLogin string
searchEmail string
caseInsensitive bool
}{
{
name: "user not found non exact - not case insensitive",
wantErr: user.ErrUserNotFound,
searchLogin: "Test",
searchEmail: "[email protected]",
caseInsensitive: false,
},
{
name: "user found exact - not case insensitive",
wantErr: nil,
searchLogin: "test",
searchEmail: "[email protected]",
caseInsensitive: false,
},
{
name: "user found non exact - case insensitive",
wantErr: nil,
searchLogin: "Test",
searchEmail: "[email protected]",
caseInsensitive: true,
},
{
name: "user found exact - case insensitive",
wantErr: nil,
searchLogin: "Test",
searchEmail: "[email protected]",
caseInsensitive: true,
},
{
name: "user not found - case insensitive",
wantErr: user.ErrUserNotFound,
searchLogin: "Test_login",
searchEmail: "Test*@email.com",
caseInsensitive: true,
},
}
if testing.Short() {
t.Skip("skipping integration test")
}
ss := db.InitTestDB(t)
cfg := ss.Cfg
userStore := ProvideStore(ss, cfg)
_, errUser := userStore.Insert(context.Background(),
&user.User{
Email: "[email protected]",
Name: "test",
Login: "test",
Created: time.Now(),
Updated: time.Now(),
},
)
require.NoError(t, errUser)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if !tc.caseInsensitive && db.IsTestDbMySQL() {
t.Skip("mysql is always case insensitive")
}
cfg.CaseInsensitiveLogin = tc.caseInsensitive
usr, err := userStore.Get(context.Background(),
&user.User{
Email: tc.searchEmail,
Login: tc.searchLogin,
},
)
if tc.wantErr != nil {
require.Error(t, err)
require.Nil(t, usr)
} else {
require.NoError(t, err)
require.NotNil(t, usr)
}
})
}
}
func TestIntegrationUserDataAccess(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
ss := db.InitTestDB(t)
quotaService := quotaimpl.ProvideService(ss, ss.Cfg)
orgService, err := orgimpl.ProvideService(ss, ss.Cfg, quotaService)
require.NoError(t, err)
userStore := ProvideStore(ss, setting.NewCfg())
usrSvc, err := ProvideService(ss, orgService, ss.Cfg, nil, nil, quotaService, supportbundlestest.NewFakeBundleService())
require.NoError(t, err)
usr := &user.SignedInUser{
OrgID: 1,
Permissions: map[int64]map[string][]string{1: {"users:read": {"global.users:*"}}},
}
t.Run("user not found", func(t *testing.T) {
_, err := userStore.Get(context.Background(),
&user.User{
Email: "[email protected]",
Name: "test1",
Login: "test1",
},
)
require.Error(t, err, user.ErrUserNotFound)
})
t.Run("insert user", func(t *testing.T) {
_, err := userStore.Insert(context.Background(),
&user.User{
Email: "[email protected]",
Name: "test1",
Login: "test1",
Created: time.Now(),
Updated: time.Now(),
},
)
require.NoError(t, err)
})
t.Run("get user", func(t *testing.T) {
_, err := userStore.Get(context.Background(),
&user.User{
Email: "[email protected]",
Name: "test1",
Login: "test1",
},
)
require.NoError(t, err)
})
t.Run("Testing DB - creates and loads user", func(t *testing.T) {
ss := db.InitTestDB(t)
_, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
cmd := user.CreateUserCommand{
Email: "[email protected]",
Name: "user name",
Login: "user_test_login",
}
usr, err := usrSvc.Create(context.Background(), &cmd)
require.NoError(t, err)
result, err := userStore.GetByID(context.Background(), usr.ID)
require.Nil(t, err)
require.Equal(t, result.Email, "[email protected]")
require.Equal(t, result.Password, "")
require.Len(t, result.Rands, 10)
require.Len(t, result.Salt, 10)
require.False(t, result.IsDisabled)
result, err = userStore.GetByID(context.Background(), usr.ID)
require.Nil(t, err)
require.Equal(t, result.Email, "[email protected]")
require.Equal(t, result.Password, "")
require.Len(t, result.Rands, 10)
require.Len(t, result.Salt, 10)
require.False(t, result.IsDisabled)
t.Run("Get User by email case insensitive", func(t *testing.T) {
userStore.cfg.CaseInsensitiveLogin = true
query := user.GetUserByEmailQuery{Email: "[email protected]"}
result, err := userStore.GetByEmail(context.Background(), &query)
require.Nil(t, err)
require.Equal(t, result.Email, "[email protected]")
require.Equal(t, result.Password, "")
require.Len(t, result.Rands, 10)
require.Len(t, result.Salt, 10)
require.False(t, result.IsDisabled)
userStore.cfg.CaseInsensitiveLogin = false
})
t.Run("Testing DB - creates and loads user", func(t *testing.T) {
result, err = userStore.GetByID(context.Background(), usr.ID)
require.Nil(t, err)
require.Equal(t, result.Email, "[email protected]")
require.Equal(t, result.Password, "")
require.Len(t, result.Rands, 10)
require.Len(t, result.Salt, 10)
require.False(t, result.IsDisabled)
result, err = userStore.GetByID(context.Background(), usr.ID)
require.Nil(t, err)
require.Equal(t, result.Email, "[email protected]")
require.Equal(t, result.Password, "")
require.Len(t, result.Rands, 10)
require.Len(t, result.Salt, 10)
require.False(t, result.IsDisabled)
ss.Cfg.CaseInsensitiveLogin = false
})
})
t.Run("Testing DB - error on case insensitive conflict", func(t *testing.T) {
if ss.GetDBType() == migrator.MySQL {
t.Skip("Skipping on MySQL due to case insensitive indexes")
}
userStore.cfg.CaseInsensitiveLogin = true
cmd := user.CreateUserCommand{
Email: "[email protected]",
Name: "user name",
Login: "user_email_conflict",
}
// userEmailConflict
_, err = usrSvc.Create(context.Background(), &cmd)
require.NoError(t, err)
cmd = user.CreateUserCommand{
Email: "[email protected]",
Name: "user name",
Login: "user_email_conflict_two",
}
_, err := usrSvc.Create(context.Background(), &cmd)
require.NoError(t, err)
cmd = user.CreateUserCommand{
Email: "[email protected]",
Name: "user name",
Login: "user_test_login_conflict",
}
// userLoginConflict
_, err = usrSvc.Create(context.Background(), &cmd)
require.NoError(t, err)
cmd = user.CreateUserCommand{
Email: "[email protected]",
Name: "user name",
Login: "user_test_login_CONFLICT",
}
_, err = usrSvc.Create(context.Background(), &cmd)
require.NoError(t, err)
ss.Cfg.CaseInsensitiveLogin = true
t.Run("GetByEmail - email conflict", func(t *testing.T) {
query := user.GetUserByEmailQuery{Email: "[email protected]"}
_, err = userStore.GetByEmail(context.Background(), &query)
require.Error(t, err)
})
t.Run("GetByEmail - login conflict", func(t *testing.T) {
query := user.GetUserByEmailQuery{Email: "[email protected]"}
_, err = userStore.GetByEmail(context.Background(), &query)
require.Error(t, err)
})
t.Run("GetByLogin - email conflict", func(t *testing.T) {
query := user.GetUserByLoginQuery{LoginOrEmail: "user_email_conflict_two"}
_, err = userStore.GetByLogin(context.Background(), &query)
require.Error(t, err)
})
t.Run("GetByLogin - login conflict", func(t *testing.T) {
query := user.GetUserByLoginQuery{LoginOrEmail: "user_test_login_conflict"}
_, err = userStore.GetByLogin(context.Background(), &query)
require.Error(t, err)
})
t.Run("GetByLogin - login conflict by email", func(t *testing.T) {
query := user.GetUserByLoginQuery{LoginOrEmail: "[email protected]"}
_, err = userStore.GetByLogin(context.Background(), &query)
require.Error(t, err)
})
t.Run("GetByLogin - user2 uses user1.email as login", func(t *testing.T) {
// create user_1
user1 := &user.User{
Email: "[email protected]",
Name: "user_1",
Login: "user_1",
Password: "user_1_password",
Created: time.Now(),
Updated: time.Now(),
IsDisabled: true,
}
_, err := userStore.Insert(context.Background(), user1)
require.Nil(t, err)
// create user_2
user2 := &user.User{
Email: "[email protected]",
Name: "user_2",
Login: "[email protected]",
Password: "user_2_password",
Created: time.Now(),
Updated: time.Now(),
IsDisabled: true,
}
_, err = userStore.Insert(context.Background(), user2)
require.Nil(t, err)
// query user database for user_1 email
query := user.GetUserByLoginQuery{LoginOrEmail: "[email protected]"}
result, err := userStore.GetByLogin(context.Background(), &query)
require.Nil(t, err)
// expect user_1 as result
require.Equal(t, user1.Email, result.Email)
require.Equal(t, user1.Login, result.Login)
require.Equal(t, user1.Name, result.Name)
require.NotEqual(t, user2.Email, result.Email)
require.NotEqual(t, user2.Login, result.Login)
require.NotEqual(t, user2.Name, result.Name)
})
ss.Cfg.CaseInsensitiveLogin = false
})
t.Run("Change user password", func(t *testing.T) {
err := userStore.ChangePassword(context.Background(), &user.ChangeUserPasswordCommand{})
require.NoError(t, err)
})
t.Run("update last seen at", func(t *testing.T) {
err := userStore.UpdateLastSeenAt(context.Background(), &user.UpdateUserLastSeenAtCommand{
UserID: 10, // Requires UserID
})
require.NoError(t, err)
err = userStore.UpdateLastSeenAt(context.Background(), &user.UpdateUserLastSeenAtCommand{
UserID: -1,
})
require.Error(t, err)
})
t.Run("get signed in user", func(t *testing.T) {
ss := db.InitTestDB(t)
orgService, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
users := createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: false,
}
})
err := orgService.AddOrgUser(context.Background(), &org.AddOrgUserCommand{
LoginOrEmail: users[1].Login, Role: org.RoleViewer,
OrgID: users[0].OrgID, UserID: users[1].ID,
})
require.Nil(t, err)
err = updateDashboardACL(t, ss, 1, &dashboards.DashboardACL{
DashboardID: 1, OrgID: users[0].OrgID, UserID: users[1].ID,
Permission: dashboards.PERMISSION_EDIT,
})
require.Nil(t, err)
ss.CacheService.Flush()
query := &user.GetSignedInUserQuery{OrgID: users[1].OrgID, UserID: users[1].ID}
result, err := userStore.GetSignedInUser(context.Background(), query)
require.NoError(t, err)
require.Equal(t, result.Email, "[email protected]")
// Throw errors for invalid user IDs
for _, userID := range []int64{-1, 0} {
_, err = userStore.GetSignedInUser(context.Background(),
&user.GetSignedInUserQuery{
OrgID: users[1].OrgID,
UserID: userID}) // zero
require.Error(t, err)
}
})
t.Run("update user", func(t *testing.T) {
err := userStore.UpdateUser(context.Background(), &user.User{ID: 1, Name: "testtestest", Login: "loginloginlogin"})
require.NoError(t, err)
result, err := userStore.GetByID(context.Background(), 1)
require.NoError(t, err)
assert.Equal(t, result.Name, "testtestest")
assert.Equal(t, result.Login, "loginloginlogin")
})
t.Run("Testing DB - grafana admin users", func(t *testing.T) {
ss := db.InitTestDB(t)
_, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
createUserCmd := user.CreateUserCommand{
Email: fmt.Sprint("admin", "@test.com"),
Name: "admin",
Login: "admin",
IsAdmin: true,
}
usr, err := usrSvc.Create(context.Background(), &createUserCmd)
require.Nil(t, err)
// Cannot make themselves a non-admin
updatePermsError := userStore.UpdatePermissions(context.Background(), usr.ID, false)
require.Equal(t, user.ErrLastGrafanaAdmin, updatePermsError)
query := user.GetUserByIDQuery{ID: usr.ID}
queryResult, getUserError := userStore.GetByID(context.Background(), query.ID)
require.Nil(t, getUserError)
require.True(t, queryResult.IsAdmin)
// One user
const email = "[email protected]"
const username = "user"
createUserCmd = user.CreateUserCommand{
Email: email,
Name: "user",
Login: username,
}
_, err = usrSvc.Create(context.Background(), &createUserCmd)
require.Nil(t, err)
// When trying to create a new user with the same email, an error is returned
createUserCmd = user.CreateUserCommand{
Email: email,
Name: "user2",
Login: "user2",
SkipOrgSetup: true,
}
_, err = usrSvc.Create(context.Background(), &createUserCmd)
require.Equal(t, user.ErrUserAlreadyExists, err)
// When trying to create a new user with the same login, an error is returned
createUserCmd = user.CreateUserCommand{
Email: "[email protected]",
Name: "user2",
Login: username,
SkipOrgSetup: true,
}
_, err = usrSvc.Create(context.Background(), &createUserCmd)
require.Equal(t, user.ErrUserAlreadyExists, err)
})
t.Run("GetProfile", func(t *testing.T) {
_, err := userStore.GetProfile(context.Background(), &user.GetUserProfileQuery{UserID: 1})
require.NoError(t, err)
})
t.Run("SetHelpFlag", func(t *testing.T) {
err := userStore.SetHelpFlag(context.Background(), &user.SetUserHelpFlagCommand{UserID: 1, HelpFlags1: user.HelpFlags1(1)})
require.NoError(t, err)
})
t.Run("Testing DB - return list users based on their is_disabled flag", func(t *testing.T) {
ss = db.InitTestDB(t)
_, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
userStore := ProvideStore(ss, ss.Cfg)
createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: i%2 == 0,
}
})
isDisabled := false
query := user.SearchUsersQuery{IsDisabled: &isDisabled, SignedInUser: usr}
result, err := userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, result.Users, 2)
first, third := false, false
for _, user := range result.Users {
if user.Name == "user1" {
first = true
}
if user.Name == "user3" {
third = true
}
}
require.True(t, first)
require.True(t, third)
// Re-init DB
ss := db.InitTestDB(t)
orgService, usrSvc = createOrgAndUserSvc(t, ss, ss.Cfg)
users := createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: false,
}
})
err = orgService.AddOrgUser(context.Background(), &org.AddOrgUserCommand{
LoginOrEmail: users[1].Login, Role: org.RoleViewer,
OrgID: users[0].OrgID, UserID: users[1].ID,
})
require.Nil(t, err)
err = updateDashboardACL(t, ss, 1, &dashboards.DashboardACL{
DashboardID: 1, OrgID: users[0].OrgID, UserID: users[1].ID,
Permission: dashboards.PERMISSION_EDIT,
})
require.Nil(t, err)
// When the user is deleted
err = userStore.Delete(context.Background(), users[1].ID)
require.Nil(t, err)
permQuery := &dashboards.GetDashboardACLInfoListQuery{DashboardID: 1, OrgID: users[0].OrgID}
permQueryResult, err := userStore.getDashboardACLInfoList(permQuery)
require.Nil(t, err)
require.Len(t, permQueryResult, 0)
// A user is an org member and has been assigned permissions
// Re-init DB
ss = db.InitTestDB(t)
orgService, usrSvc = createOrgAndUserSvc(t, ss, ss.Cfg)
users = createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: false,
}
})
err = orgService.AddOrgUser(context.Background(), &org.AddOrgUserCommand{
LoginOrEmail: users[1].Login, Role: org.RoleViewer,
OrgID: users[0].OrgID, UserID: users[1].ID,
})
require.Nil(t, err)
err = updateDashboardACL(t, ss, 1, &dashboards.DashboardACL{
DashboardID: 1, OrgID: users[0].OrgID, UserID: users[1].ID,
Permission: dashboards.PERMISSION_EDIT,
})
require.Nil(t, err)
ss.CacheService.Flush()
query3 := &user.GetSignedInUserQuery{OrgID: users[1].OrgID, UserID: users[1].ID}
query3Result, err := userStore.GetSignedInUser(context.Background(), query3)
require.Nil(t, err)
require.NotNil(t, query3Result)
require.Equal(t, query3.OrgID, users[1].OrgID)
disableCmd := user.BatchDisableUsersCommand{
UserIDs: []int64{users[0].ID, users[1].ID, users[2].ID, users[3].ID, users[4].ID},
IsDisabled: true,
}
err = userStore.BatchDisableUsers(context.Background(), &disableCmd)
require.Nil(t, err)
isDisabled = true
query5 := &user.SearchUsersQuery{IsDisabled: &isDisabled, SignedInUser: usr}
query5Result, err := userStore.Search(context.Background(), query5)
require.Nil(t, err)
require.EqualValues(t, query5Result.TotalCount, 5)
// the user is deleted
err = userStore.Delete(context.Background(), users[1].ID)
require.Nil(t, err)
permQuery = &dashboards.GetDashboardACLInfoListQuery{DashboardID: 1, OrgID: users[0].OrgID}
permQueryResult, err = userStore.getDashboardACLInfoList(permQuery)
require.Nil(t, err)
require.Len(t, permQueryResult, 0)
})
t.Run("Testing DB - return list of users that the SignedInUser has permission to read", func(t *testing.T) {
ss := db.InitTestDB(t)
orgService, err := orgimpl.ProvideService(ss, ss.Cfg, quotaService)
require.NoError(t, err)
usrSvc, err := ProvideService(ss, orgService, ss.Cfg, nil, nil, quotaService, supportbundlestest.NewFakeBundleService())
require.NoError(t, err)
createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
}
})
testUser := &user.SignedInUser{
OrgID: 1,
Permissions: map[int64]map[string][]string{1: {"users:read": {"global.users:id:1", "global.users:id:3"}}},
}
query := user.SearchUsersQuery{SignedInUser: testUser}
queryResult, err := userStore.Search(context.Background(), &query)
assert.Nil(t, err)
assert.Len(t, queryResult.Users, 2)
})
ss = db.InitTestDB(t)
t.Run("Testing DB - enable all users", func(t *testing.T) {
users := createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: true,
}
})
disableCmd := user.BatchDisableUsersCommand{
UserIDs: []int64{users[0].ID, users[1].ID, users[2].ID, users[3].ID, users[4].ID},
IsDisabled: false,
}
err := userStore.BatchDisableUsers(context.Background(), &disableCmd)
require.Nil(t, err)
isDisabled := false
query := &user.SearchUsersQuery{IsDisabled: &isDisabled, SignedInUser: usr}
queryResult, err := userStore.Search(context.Background(), query)
require.Nil(t, err)
require.EqualValues(t, queryResult.TotalCount, 5)
})
t.Run("Can search users", func(t *testing.T) {
ss = db.InitTestDB(t)
userStore.cfg.AutoAssignOrg = false
ac1cmd := user.CreateUserCommand{Login: "ac1", Email: "[email protected]", Name: "ac1 name"}
ac2cmd := user.CreateUserCommand{Login: "ac2", Email: "[email protected]", Name: "ac2 name", IsAdmin: true}
serviceaccountcmd := user.CreateUserCommand{Login: "serviceaccount", Email: "[email protected]", Name: "serviceaccount name", IsAdmin: true, IsServiceAccount: true}
_, err := usrSvc.Create(context.Background(), &ac1cmd)
require.NoError(t, err)
_, err = usrSvc.Create(context.Background(), &ac2cmd)
require.NoError(t, err)
// user only used for making sure we filter out the service accounts
_, err = usrSvc.Create(context.Background(), &serviceaccountcmd)
require.NoError(t, err)
query := user.SearchUsersQuery{Query: "", SignedInUser: &user.SignedInUser{
OrgID: 1,
Permissions: map[int64]map[string][]string{
1: {accesscontrol.ActionUsersRead: {accesscontrol.ScopeGlobalUsersAll}},
},
}}
queryResult, err := userStore.Search(context.Background(), &query)
require.NoError(t, err)
require.Len(t, queryResult.Users, 2)
require.Equal(t, queryResult.Users[0].Email, "[email protected]")
require.Equal(t, queryResult.Users[1].Email, "[email protected]")
})
ss = db.InitTestDB(t)
t.Run("Testing DB - disable only specific users", func(t *testing.T) {
users := createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: false,
}
})
userIdsToDisable := []int64{}
for i := 0; i < 3; i++ {
userIdsToDisable = append(userIdsToDisable, users[i].ID)
}
disableCmd := user.BatchDisableUsersCommand{
UserIDs: userIdsToDisable,
IsDisabled: true,
}
err := userStore.BatchDisableUsers(context.Background(), &disableCmd)
require.Nil(t, err)
query := user.SearchUsersQuery{SignedInUser: usr}
queryResult, err := userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.EqualValues(t, queryResult.TotalCount, 5)
for _, user := range queryResult.Users {
shouldBeDisabled := false
// Check if user id is in the userIdsToDisable list
for _, disabledUserId := range userIdsToDisable {
if user.ID == disabledUserId {
require.True(t, user.IsDisabled)
shouldBeDisabled = true
}
}
// Otherwise user shouldn't be disabled
if !shouldBeDisabled {
require.False(t, user.IsDisabled)
}
}
})
ss = db.InitTestDB(t)
t.Run("Testing DB - search users", func(t *testing.T) {
// Since previous tests were destructive
createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: false,
}
})
})
t.Run("Disable user", func(t *testing.T) {
id, err := userStore.Insert(context.Background(), &user.User{
Name: "user111",
Created: time.Now(),
Updated: time.Now(),
})
require.NoError(t, err)
err = userStore.Disable(context.Background(), &user.DisableUserCommand{UserID: id})
require.NoError(t, err)
})
t.Run("Testing DB - multiple users", func(t *testing.T) {
ss = db.InitTestDB(t)
createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("user", i, "@test.com"),
Name: fmt.Sprint("user", i),
Login: fmt.Sprint("loginuser", i),
IsDisabled: false,
}
})
// Return the first page of users and a total count
query := user.SearchUsersQuery{Query: "", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err := userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 3)
require.EqualValues(t, queryResult.TotalCount, 5)
// Return the second page of users and a total count
query = user.SearchUsersQuery{Query: "", Page: 2, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 2)
require.EqualValues(t, queryResult.TotalCount, 5)
// Return list of users matching query on user name
query = user.SearchUsersQuery{Query: "use", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 3)
require.EqualValues(t, queryResult.TotalCount, 5)
query = user.SearchUsersQuery{Query: "ser1", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 1)
require.EqualValues(t, queryResult.TotalCount, 1)
query = user.SearchUsersQuery{Query: "USER1", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 1)
require.EqualValues(t, queryResult.TotalCount, 1)
query = user.SearchUsersQuery{Query: "idontexist", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 0)
require.EqualValues(t, queryResult.TotalCount, 0)
// Return list of users matching query on email
query = user.SearchUsersQuery{Query: "[email protected]", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 1)
require.EqualValues(t, queryResult.TotalCount, 1)
// Return list of users matching query on login name
query = user.SearchUsersQuery{Query: "loginuser1", Page: 1, Limit: 3, SignedInUser: usr}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 1)
require.EqualValues(t, queryResult.TotalCount, 1)
// Custom ordering
sortOpts, err := sortopts.ParseSortQueryParam("login-asc,email-asc")
require.NoError(t, err)
query = user.SearchUsersQuery{Query: "", Page: 1, Limit: 3, SignedInUser: usr, SortOpts: sortOpts}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 3)
require.EqualValues(t, queryResult.TotalCount, 5)
for i := 0; i < 3; i++ {
require.Equal(t, fmt.Sprint("loginuser", i), queryResult.Users[i].Login)
}
sortOpts2, err := sortopts.ParseSortQueryParam("login-desc,email-asc")
require.NoError(t, err)
query = user.SearchUsersQuery{Query: "", Page: 1, Limit: 3, SignedInUser: usr, SortOpts: sortOpts2}
queryResult, err = userStore.Search(context.Background(), &query)
require.Nil(t, err)
require.Len(t, queryResult.Users, 3)
require.EqualValues(t, queryResult.TotalCount, 5)
for i := 0; i < 3; i++ {
require.Equal(t, fmt.Sprint("loginuser", 4-i), queryResult.Users[i].Login)
}
})
t.Run("Can get logged in user projection", func(t *testing.T) {
query := user.GetSignedInUserQuery{UserID: 2}
queryResult, err := userStore.GetSignedInUser(context.Background(), &query)
require.NoError(t, err)
assert.Equal(t, queryResult.Email, "[email protected]")
assert.EqualValues(t, queryResult.OrgID, 2)
assert.Equal(t, queryResult.Name, "user1")
assert.Equal(t, queryResult.Login, "loginuser1")
assert.EqualValues(t, queryResult.OrgRole, "Admin")
assert.Equal(t, queryResult.OrgName, "[email protected]")
assert.Equal(t, queryResult.IsGrafanaAdmin, false)
})
}
func TestIntegrationUserUpdate(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
ss := db.InitTestDB(t)
userStore := ProvideStore(ss, setting.NewCfg())
_, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
users := createFiveTestUsers(t, usrSvc, func(i int) *user.CreateUserCommand {
return &user.CreateUserCommand{
Email: fmt.Sprint("USER", i, "@test.com"),
Name: fmt.Sprint("USER", i),
Login: fmt.Sprint("loginUSER", i),
IsDisabled: false,
}
})
userStore.cfg.CaseInsensitiveLogin = true
t.Run("Testing DB - update generates duplicate user", func(t *testing.T) {
err := userStore.Update(context.Background(), &user.UpdateUserCommand{
Login: "loginuser2",
UserID: users[0].ID,
})
require.Error(t, err)
})
t.Run("Testing DB - update lowercases existing user", func(t *testing.T) {
err := userStore.Update(context.Background(), &user.UpdateUserCommand{
Login: "loginUSER0",
Email: "[email protected]",
UserID: users[0].ID,
})
require.NoError(t, err)
result, err := userStore.GetByID(context.Background(), users[0].ID)
require.NoError(t, err)
require.Equal(t, "loginuser0", result.Login)
require.Equal(t, "[email protected]", result.Email)
})
t.Run("Testing DB - no user info provided", func(t *testing.T) {
err := userStore.Update(context.Background(), &user.UpdateUserCommand{
Login: "",
Email: "",
Name: "Change Name",
UserID: users[3].ID,
})
require.NoError(t, err)
// query := user.GetUserByIDQuery{ID: users[3].ID}
result, err := userStore.GetByID(context.Background(), users[3].ID)
require.NoError(t, err)
// Changed
require.Equal(t, "Change Name", result.Name)
// Unchanged
require.Equal(t, "loginUSER3", result.Login)
require.Equal(t, "[email protected]", result.Email)
})
ss.Cfg.CaseInsensitiveLogin = false
}
func createFiveTestUsers(t *testing.T, svc user.Service, fn func(i int) *user.CreateUserCommand) []user.User {
t.Helper()
users := make([]user.User, 5)
for i := 0; i < 5; i++ {
cmd := fn(i)
user, err := svc.Create(context.Background(), cmd)
require.Nil(t, err)
users[i] = *user
}
return users
}
// TODO: Use FakeDashboardStore when org has its own service
func updateDashboardACL(t *testing.T, sqlStore db.DB, dashboardID int64, items ...*dashboards.DashboardACL) error {
t.Helper()
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
_, err := sess.Exec("DELETE FROM dashboard_acl WHERE dashboard_id=?", dashboardID)
if err != nil {
return fmt.Errorf("deleting from dashboard_acl failed: %w", err)
}
for _, item := range items {
item.Created = time.Now()
item.Updated = time.Now()
if item.UserID == 0 && item.TeamID == 0 && (item.Role == nil || !item.Role.IsValid()) {
return dashboards.ErrDashboardACLInfoMissing
}
if item.DashboardID == 0 {
return dashboards.ErrDashboardPermissionDashboardEmpty
}
sess.Nullable("user_id", "team_id")
if _, err := sess.Insert(item); err != nil {
return err
}
}
// Update dashboard HasACL flag
dashboard := dashboards.Dashboard{HasACL: true}
_, err = sess.Cols("has_acl").Where("id=?", dashboardID).Update(&dashboard)
return err
})
return err
}
func TestMetricsUsage(t *testing.T) {
ss := db.InitTestDB(t)
userStore := ProvideStore(ss, setting.NewCfg())
quotaService := quotaimpl.ProvideService(ss, ss.Cfg)
orgService, err := orgimpl.ProvideService(ss, ss.Cfg, quotaService)
require.NoError(t, err)
_, usrSvc := createOrgAndUserSvc(t, ss, ss.Cfg)
t.Run("Get empty role metrics for an org", func(t *testing.T) {
orgId := int64(1)
// create first user
createFirtUserCmd := &user.CreateUserCommand{
Login: "admin",
Email: "[email protected]",
Name: "admin",
OrgID: orgId,
}
_, err := usrSvc.Create(context.Background(), createFirtUserCmd)
require.NoError(t, err)
// create second user
createSecondUserCmd := &user.CreateUserCommand{
Login: "userWithoutRole",
Email: "[email protected]",
Name: "userWithoutRole",
}
secondUser, err := usrSvc.Create(context.Background(), createSecondUserCmd)
require.NoError(t, err)
// assign the user to the org
cmd := org.AddOrgUserCommand{
OrgID: secondUser.OrgID,
UserID: orgId,
Role: org.RoleNone,
}
err = orgService.AddOrgUser(context.Background(), &cmd)
require.NoError(t, err)
// get metric usage
stats, err := userStore.CountUserAccountsWithEmptyRole(context.Background())
require.NoError(t, err)
assert.Equal(t, int64(1), stats)
})
}
// This function was copied from pkg/services/dashboards/database to circumvent
// import cycles. When this org-related code is refactored into a service the
// tests can the real GetDashboardACLInfoList functions
func (ss *sqlStore) getDashboardACLInfoList(query *dashboards.GetDashboardACLInfoListQuery) ([]*dashboards.DashboardACLInfoDTO, error) {
queryResult := make([]*dashboards.DashboardACLInfoDTO, 0)
outerErr := ss.db.WithDbSession(context.Background(), func(dbSession *db.Session) error {
falseStr := ss.dialect.BooleanStr(false)
if query.DashboardID == 0 {
sql := `SELECT
da.id,
da.org_id,
da.dashboard_id,
da.user_id,
da.team_id,
da.permission,
da.role,
da.created,
da.updated,
'' as user_login,
'' as user_email,
'' as team,
'' as title,
'' as slug,
'' as uid,` +
falseStr + ` AS is_folder,` +
falseStr + ` AS inherited
FROM dashboard_acl as da
WHERE da.dashboard_id = -1`
return dbSession.SQL(sql).Find(&queryResult)
}
rawSQL := `
-- get permissions for the dashboard and its parent folder
SELECT
da.id,
da.org_id,
da.dashboard_id,
da.user_id,
da.team_id,
da.permission,
da.role,
da.created,
da.updated,
u.login AS user_login,
u.email AS user_email,
ug.name AS team,
ug.email AS team_email,
d.title,
d.slug,
d.uid,
d.is_folder,
CASE WHEN (da.dashboard_id = -1 AND d.folder_id > 0) OR da.dashboard_id = d.folder_id THEN ` + ss.dialect.BooleanStr(true) + ` ELSE ` + falseStr + ` END AS inherited
FROM dashboard as d
LEFT JOIN dashboard folder on folder.id = d.folder_id
LEFT JOIN dashboard_acl AS da ON
da.dashboard_id = d.id OR
da.dashboard_id = d.folder_id OR
(
-- include default permissions -->
da.org_id = -1 AND (
(folder.id IS NOT NULL AND folder.has_acl = ` + falseStr + `) OR
(folder.id IS NULL AND d.has_acl = ` + falseStr + `)
)
)
LEFT JOIN ` + ss.dialect.Quote("user") + ` AS u ON u.id = da.user_id
LEFT JOIN team ug on ug.id = da.team_id
WHERE d.org_id = ? AND d.id = ? AND da.id IS NOT NULL
ORDER BY da.id ASC
`
return dbSession.SQL(rawSQL, query.OrgID, query.DashboardID).Find(&queryResult)
})
if outerErr != nil {
return nil, outerErr
}
for _, p := range queryResult {
p.PermissionName = p.Permission.String()
}
return queryResult, nil
}
func createOrgAndUserSvc(t *testing.T, store db.DB, cfg *setting.Cfg) (org.Service, user.Service) {
t.Helper()
quotaService := quotaimpl.ProvideService(store, cfg)
orgService, err := orgimpl.ProvideService(store, cfg, quotaService)
require.NoError(t, err)
usrSvc, err := ProvideService(store, orgService, cfg, nil, nil, quotaService, supportbundlestest.NewFakeBundleService())
require.NoError(t, err)
return orgService, usrSvc
}
| pkg/services/user/userimpl/store_test.go | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.00018659706984180957,
0.0001704168098513037,
0.00016192115435842425,
0.0001707812334643677,
0.000002567340743553359
] |
{
"id": 4,
"code_window": [
"\t// FlagCostManagementUi\n",
"\t// Toggles the display of the cost management ui plugin\n",
"\tFlagCostManagementUi = \"costManagementUi\"\n",
")"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\t// FlagManagedPluginsInstall\n",
"\t// Install managed plugins directly from plugins catalog\n",
"\tFlagManagedPluginsInstall = \"managedPluginsInstall\"\n"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.go",
"type": "add",
"edit_start_line_idx": 524
} | Name,Stage,Owner,requiresDevMode,RequiresLicense,RequiresRestart,FrontendOnly
trimDefaults,preview,@grafana/grafana-as-code,false,false,false,false
disableEnvelopeEncryption,GA,@grafana/grafana-as-code,false,false,false,false
live-service-web-worker,experimental,@grafana/grafana-app-platform-squad,false,false,false,true
queryOverLive,experimental,@grafana/grafana-app-platform-squad,false,false,false,true
panelTitleSearch,preview,@grafana/grafana-app-platform-squad,false,false,false,false
publicDashboards,GA,@grafana/sharing-squad,false,false,false,false
publicDashboardsEmailSharing,preview,@grafana/sharing-squad,false,true,false,false
lokiExperimentalStreaming,experimental,@grafana/observability-logs,false,false,false,false
featureHighlights,GA,@grafana/grafana-as-code,false,false,false,false
migrationLocking,preview,@grafana/backend-platform,false,false,false,false
storage,experimental,@grafana/grafana-app-platform-squad,false,false,false,false
correlations,preview,@grafana/explore-squad,false,false,false,false
exploreContentOutline,GA,@grafana/explore-squad,false,false,false,true
datasourceQueryMultiStatus,experimental,@grafana/plugins-platform-backend,false,false,false,false
traceToMetrics,experimental,@grafana/observability-traces-and-profiling,false,false,false,true
newDBLibrary,preview,@grafana/backend-platform,false,false,false,false
autoMigrateOldPanels,preview,@grafana/dataviz-squad,false,false,false,true
disableAngular,preview,@grafana/dataviz-squad,false,false,false,true
canvasPanelNesting,experimental,@grafana/dataviz-squad,false,false,false,true
scenes,experimental,@grafana/dashboards-squad,false,false,false,true
disableSecretsCompatibility,experimental,@grafana/hosted-grafana-team,false,false,true,false
logRequestsInstrumentedAsUnknown,experimental,@grafana/hosted-grafana-team,false,false,false,false
dataConnectionsConsole,GA,@grafana/plugins-platform-backend,false,false,false,false
topnav,deprecated,@grafana/grafana-frontend-platform,false,false,false,false
dockedMegaMenu,experimental,@grafana/grafana-frontend-platform,false,false,false,true
grpcServer,preview,@grafana/grafana-app-platform-squad,false,false,false,false
entityStore,experimental,@grafana/grafana-app-platform-squad,true,false,false,false
cloudWatchCrossAccountQuerying,GA,@grafana/aws-datasources,false,false,false,false
redshiftAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,false
athenaAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,true
cloudwatchNewRegionsHandler,experimental,@grafana/aws-datasources,false,false,false,false
showDashboardValidationWarnings,experimental,@grafana/dashboards-squad,false,false,false,false
mysqlAnsiQuotes,experimental,@grafana/backend-platform,false,false,false,false
accessControlOnCall,preview,@grafana/grafana-authnz-team,false,false,false,false
nestedFolders,preview,@grafana/backend-platform,false,false,false,false
nestedFolderPicker,GA,@grafana/grafana-frontend-platform,false,false,false,true
accessTokenExpirationCheck,GA,@grafana/grafana-authnz-team,false,false,false,false
emptyDashboardPage,GA,@grafana/dashboards-squad,false,false,false,true
disablePrometheusExemplarSampling,GA,@grafana/observability-metrics,false,false,false,false
alertingBacktesting,experimental,@grafana/alerting-squad,false,false,false,false
editPanelCSVDragAndDrop,experimental,@grafana/grafana-bi-squad,false,false,false,true
alertingNoNormalState,preview,@grafana/alerting-squad,false,false,false,false
logsContextDatasourceUi,GA,@grafana/observability-logs,false,false,false,true
lokiQuerySplitting,experimental,@grafana/observability-logs,false,false,false,true
lokiQuerySplittingConfig,experimental,@grafana/observability-logs,false,false,false,true
individualCookiePreferences,experimental,@grafana/backend-platform,false,false,false,false
gcomOnlyExternalOrgRoleSync,GA,@grafana/grafana-authnz-team,false,false,false,false
prometheusMetricEncyclopedia,GA,@grafana/observability-metrics,false,false,false,true
influxdbBackendMigration,GA,@grafana/observability-metrics,false,false,false,true
clientTokenRotation,experimental,@grafana/grafana-authnz-team,false,false,false,false
prometheusDataplane,GA,@grafana/observability-metrics,false,false,false,false
lokiMetricDataplane,GA,@grafana/observability-logs,false,false,false,false
lokiLogsDataplane,experimental,@grafana/observability-logs,false,false,false,false
dataplaneFrontendFallback,GA,@grafana/observability-metrics,false,false,false,true
disableSSEDataplane,experimental,@grafana/observability-metrics,false,false,false,false
alertStateHistoryLokiSecondary,experimental,@grafana/alerting-squad,false,false,false,false
alertingNotificationsPoliciesMatchingInstances,GA,@grafana/alerting-squad,false,false,false,true
alertStateHistoryLokiPrimary,experimental,@grafana/alerting-squad,false,false,false,false
alertStateHistoryLokiOnly,experimental,@grafana/alerting-squad,false,false,false,false
unifiedRequestLog,experimental,@grafana/backend-platform,false,false,false,false
renderAuthJWT,preview,@grafana/grafana-as-code,false,false,false,false
externalServiceAuth,experimental,@grafana/grafana-authnz-team,true,false,false,false
refactorVariablesTimeRange,preview,@grafana/dashboards-squad,false,false,false,false
useCachingService,GA,@grafana/grafana-operator-experience-squad,false,false,true,false
enableElasticsearchBackendQuerying,GA,@grafana/observability-logs,false,false,false,false
advancedDataSourcePicker,GA,@grafana/dashboards-squad,false,false,false,true
faroDatasourceSelector,preview,@grafana/app-o11y,false,false,false,true
enableDatagridEditing,preview,@grafana/grafana-bi-squad,false,false,false,true
dataSourcePageHeader,preview,@grafana/enterprise-datasources,false,false,false,true
extraThemes,experimental,@grafana/grafana-frontend-platform,false,false,false,true
lokiPredefinedOperations,experimental,@grafana/observability-logs,false,false,false,true
pluginsFrontendSandbox,experimental,@grafana/plugins-platform-backend,false,false,false,true
dashboardEmbed,experimental,@grafana/grafana-as-code,false,false,false,true
frontendSandboxMonitorOnly,experimental,@grafana/plugins-platform-backend,false,false,false,true
sqlDatasourceDatabaseSelection,preview,@grafana/grafana-bi-squad,false,false,false,true
lokiFormatQuery,experimental,@grafana/observability-logs,false,false,false,true
cloudWatchLogsMonacoEditor,GA,@grafana/aws-datasources,false,false,false,true
exploreScrollableLogsContainer,experimental,@grafana/observability-logs,false,false,false,true
recordedQueriesMulti,GA,@grafana/observability-metrics,false,false,false,false
pluginsDynamicAngularDetectionPatterns,experimental,@grafana/plugins-platform-backend,false,false,false,false
vizAndWidgetSplit,experimental,@grafana/dashboards-squad,false,false,false,true
prometheusIncrementalQueryInstrumentation,experimental,@grafana/observability-metrics,false,false,false,true
logsExploreTableVisualisation,experimental,@grafana/observability-logs,false,false,false,true
awsDatasourcesTempCredentials,experimental,@grafana/aws-datasources,false,false,false,false
transformationsRedesign,GA,@grafana/observability-metrics,false,false,false,true
toggleLabelsInLogsUI,GA,@grafana/observability-logs,false,false,false,true
mlExpressions,experimental,@grafana/alerting-squad,false,false,false,false
traceQLStreaming,experimental,@grafana/observability-traces-and-profiling,false,false,false,true
metricsSummary,experimental,@grafana/observability-traces-and-profiling,false,false,false,true
grafanaAPIServer,experimental,@grafana/grafana-app-platform-squad,false,false,false,false
grafanaAPIServerWithExperimentalAPIs,experimental,@grafana/grafana-app-platform-squad,false,false,false,false
featureToggleAdminPage,experimental,@grafana/grafana-operator-experience-squad,false,false,true,false
awsAsyncQueryCaching,preview,@grafana/aws-datasources,false,false,false,false
splitScopes,preview,@grafana/grafana-authnz-team,false,false,true,false
azureMonitorDataplane,GA,@grafana/partner-datasources,false,false,false,false
permissionsFilterRemoveSubquery,experimental,@grafana/backend-platform,false,false,false,false
prometheusConfigOverhaulAuth,GA,@grafana/observability-metrics,false,false,false,false
configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false
influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false
alertingNoDataErrorExecution,privatePreview,@grafana/alerting-squad,false,false,true,false
angularDeprecationUI,experimental,@grafana/plugins-platform-backend,false,false,false,true
dashgpt,experimental,@grafana/dashboards-squad,false,false,false,true
reportingRetries,preview,@grafana/sharing-squad,false,false,true,false
newBrowseDashboards,GA,@grafana/grafana-frontend-platform,false,false,false,true
sseGroupByDatasource,experimental,@grafana/observability-metrics,false,false,false,false
requestInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false
libraryPanelRBAC,experimental,@grafana/dashboards-squad,false,false,true,false
lokiRunQueriesInParallel,privatePreview,@grafana/observability-logs,false,false,false,false
wargamesTesting,experimental,@grafana/hosted-grafana-team,false,false,false,false
alertingInsights,GA,@grafana/alerting-squad,false,false,false,true
externalCorePlugins,experimental,@grafana/plugins-platform-backend,false,false,false,false
pluginsAPIMetrics,experimental,@grafana/plugins-platform-backend,false,false,false,true
httpSLOLevels,experimental,@grafana/hosted-grafana-team,false,false,true,false
idForwarding,experimental,@grafana/grafana-authnz-team,true,false,false,false
cloudWatchWildCardDimensionValues,GA,@grafana/aws-datasources,false,false,false,false
externalServiceAccounts,experimental,@grafana/grafana-authnz-team,true,false,false,false
panelMonitoring,experimental,@grafana/dataviz-squad,false,false,false,true
enableNativeHTTPHistogram,experimental,@grafana/hosted-grafana-team,false,false,false,false
formatString,experimental,@grafana/grafana-bi-squad,false,false,false,true
transformationsVariableSupport,experimental,@grafana/grafana-bi-squad,false,false,false,true
kubernetesPlaylists,experimental,@grafana/grafana-app-platform-squad,false,false,false,true
navAdminSubsections,experimental,@grafana/grafana-frontend-platform,false,false,false,false
recoveryThreshold,experimental,@grafana/alerting-squad,false,false,true,false
teamHttpHeaders,experimental,@grafana/grafana-authnz-team,false,false,false,false
awsDatasourcesNewFormStyling,experimental,@grafana/aws-datasources,false,false,false,true
cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false
panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false
pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false
costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false
| pkg/services/featuremgmt/toggles_gen.csv | 1 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0001815949653973803,
0.00017054949421435595,
0.00016379250155296177,
0.00017068025772459805,
0.0000037971374240441946
] |
{
"id": 4,
"code_window": [
"\t// FlagCostManagementUi\n",
"\t// Toggles the display of the cost management ui plugin\n",
"\tFlagCostManagementUi = \"costManagementUi\"\n",
")"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\t// FlagManagedPluginsInstall\n",
"\t// Install managed plugins directly from plugins catalog\n",
"\tFlagManagedPluginsInstall = \"managedPluginsInstall\"\n"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.go",
"type": "add",
"edit_start_line_idx": 524
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { render, screen } from '@testing-library/react';
import React from 'react';
import traceGenerator from '../demo/trace-generators';
import transformTraceData from '../model/transform-trace-data';
import { Trace } from '../types';
import { formatDuration } from '../utils/date';
import SpanTreeOffset from './SpanTreeOffset';
import VirtualizedTraceView, { VirtualizedTraceViewProps } from './VirtualizedTraceView';
jest.mock('./SpanTreeOffset');
const trace = transformTraceData(traceGenerator.trace({ numberOfSpans: 2 }))!;
const topOfExploreViewRef = jest.fn();
let props = {
childrenHiddenIDs: new Set(),
childrenToggle: jest.fn(),
currentViewRangeTime: [0.25, 0.75],
detailLogItemToggle: jest.fn(),
detailLogsToggle: jest.fn(),
detailProcessToggle: jest.fn(),
detailStates: new Map(),
detailTagsToggle: jest.fn(),
detailToggle: jest.fn(),
findMatchesIDs: null,
setSpanNameColumnWidth: jest.fn(),
spanNameColumnWidth: 0.5,
trace,
uiFind: 'uiFind',
topOfExploreViewRef,
} as unknown as VirtualizedTraceViewProps;
describe('<VirtualizedTraceViewImpl>', () => {
beforeEach(() => {
jest.mocked(SpanTreeOffset).mockReturnValue(<div />);
Object.keys(props).forEach((key) => {
if (typeof props[key as keyof VirtualizedTraceViewProps] === 'function') {
(props[key as keyof VirtualizedTraceViewProps] as jest.Mock).mockReset();
}
});
});
it('renders service name, operation name and duration for each span', () => {
render(<VirtualizedTraceView {...props} />);
expect(screen.getAllByText(trace.services[0].name)).toBeTruthy();
if (trace.services.length > 1) {
expect(screen.getAllByText(trace.services[1].name)).toBeTruthy();
}
expect(screen.getAllByText(trace.spans[0].operationName)).toBeTruthy();
expect(screen.getAllByText(trace.spans[1].operationName)).toBeTruthy();
let durationSpan = formatDuration(trace.spans[0].duration);
expect(screen.getAllByText(durationSpan)).toBeTruthy();
});
it('renders without exploding', () => {
render(<VirtualizedTraceView {...props} />);
expect(screen.getByTestId('ListView')).toBeInTheDocument();
expect(screen.getByTitle('Scroll to top')).toBeInTheDocument();
});
it('renders when a trace is not set', () => {
props = { ...props, trace: null as unknown as Trace };
render(<VirtualizedTraceView {...props} />);
expect(screen.getByTestId('ListView')).toBeInTheDocument();
expect(screen.getByTitle('Scroll to top')).toBeInTheDocument();
});
it('renders ListView', () => {
render(<VirtualizedTraceView {...props} />);
expect(screen.getByTestId('ListView')).toBeInTheDocument();
});
it('renders scrollToTopButton', () => {
render(<VirtualizedTraceView {...props} />);
expect(
screen.getByRole('button', {
name: /Scroll to top/i,
})
).toBeInTheDocument();
});
});
| public/app/features/explore/TraceView/components/TraceTimelineViewer/VirtualizedTraceView.test.tsx | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0001776802382664755,
0.0001718507701298222,
0.0001678059488767758,
0.00017131277127191424,
0.0000031274337288778042
] |
{
"id": 4,
"code_window": [
"\t// FlagCostManagementUi\n",
"\t// Toggles the display of the cost management ui plugin\n",
"\tFlagCostManagementUi = \"costManagementUi\"\n",
")"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\t// FlagManagedPluginsInstall\n",
"\t// Install managed plugins directly from plugins catalog\n",
"\tFlagManagedPluginsInstall = \"managedPluginsInstall\"\n"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.go",
"type": "add",
"edit_start_line_idx": 524
} | import { screen, getAllByRole } from '@testing-library/react';
export function getLabelSelects(index = 0) {
const labels = screen.getByText(/Label filters/);
const selects = getAllByRole(labels.parentElement!.parentElement!.parentElement!, 'combobox');
return {
name: selects[3 * index],
value: selects[3 * index + 2],
};
}
| public/app/plugins/datasource/prometheus/querybuilder/testUtils.ts | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0001815949653973803,
0.0001770599774317816,
0.0001725249894661829,
0.0001770599774317816,
0.0000045349879655987024
] |
{
"id": 4,
"code_window": [
"\t// FlagCostManagementUi\n",
"\t// Toggles the display of the cost management ui plugin\n",
"\tFlagCostManagementUi = \"costManagementUi\"\n",
")"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\t// FlagManagedPluginsInstall\n",
"\t// Install managed plugins directly from plugins catalog\n",
"\tFlagManagedPluginsInstall = \"managedPluginsInstall\"\n"
],
"file_path": "pkg/services/featuremgmt/toggles_gen.go",
"type": "add",
"edit_start_line_idx": 524
} | import { e2e } from '../utils';
const DASHBOARD_ID = 'XMjIZPmik';
const DASHBOARD_NAME = 'Panel Tests - Graph Time Regions';
describe('Auto-migrate graph panel', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Annotation markers exist for time regions', () => {
e2e.flows.openDashboard({ uid: DASHBOARD_ID });
cy.contains(DASHBOARD_NAME).should('be.visible');
cy.contains('uplot-main-div').should('not.exist');
e2e.flows.openDashboard({ uid: DASHBOARD_ID, queryParams: { '__feature.autoMigrateOldPanels': true } });
e2e.components.Panels.Panel.title('Business Hours')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
e2e.components.Panels.Panel.title("Sunday's 20-23")
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
e2e.components.Panels.Panel.title('Each day of week')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
cy.get('body').children().find('.scrollbar-view').first().scrollTo('bottom');
e2e.components.Panels.Panel.title('05:00')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
e2e.components.Panels.Panel.title('From 22:00 to 00:30 (crossing midnight)')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
});
});
| e2e/various-suite/graph-auto-migrate.spec.ts | 0 | https://github.com/grafana/grafana/commit/43add83d1a84fe0945860a9cc700df92c7e8341f | [
0.0001752086536725983,
0.0001738991995807737,
0.000172919433680363,
0.0001735699624987319,
8.875227308635658e-7
] |
{
"id": 0,
"code_window": [
"// --------------------------------------------------\n",
"\n",
"$modal-ios-background-color: $background-ios-color !default;\n",
"$modal-ios-border-radius: 5px !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-ios-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ios.scss",
"type": "replace",
"edit_start_line_idx": 7
} | @import "../../globals.ios";
// iOS Modals
// --------------------------------------------------
$modal-ios-background-color: $background-ios-color !default;
$modal-ios-border-radius: 5px !default;
.modal-wrapper {
background-color: $modal-ios-background-color;
}
| src/components/modal/modal.ios.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9954544305801392,
0.504298746585846,
0.01314303558319807,
0.504298746585846,
0.4911556839942932
] |
{
"id": 0,
"code_window": [
"// --------------------------------------------------\n",
"\n",
"$modal-ios-background-color: $background-ios-color !default;\n",
"$modal-ios-border-radius: 5px !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-ios-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ios.scss",
"type": "replace",
"edit_start_line_idx": 7
} | import {App} from '../../../../../src';
@App({
templateUrl: 'main.html'
})
class E2EApp {}
| src/components/grid/test/full/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001665615855017677,
0.0001665615855017677,
0.0001665615855017677,
0.0001665615855017677,
0
] |
{
"id": 0,
"code_window": [
"// --------------------------------------------------\n",
"\n",
"$modal-ios-background-color: $background-ios-color !default;\n",
"$modal-ios-border-radius: 5px !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-ios-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ios.scss",
"type": "replace",
"edit_start_line_idx": 7
} | @import "../../globals.core";
// Typography
// --------------------------------------------------
// All font sizes use rem units
// By default, 1rem equals 10px. For example, 1.4rem === 14px
// $font-size-root value, which is on the <html> element
// is what can scale all fonts
$font-size-root: 62.5% !default;
$headings-font-weight: 500 !default;
$headings-line-height: 1.2 !default;
$h1-font-size: 2.6rem !default;
$h2-font-size: 2.4rem !default;
$h3-font-size: 2.2rem !default;
$h4-font-size: 2rem !default;
$h5-font-size: 1.8rem !default;
$h6-font-size: 1.6rem !default;
html {
font-size: $font-size-root;
}
a {
background-color: transparent;
}
.enable-hover a:hover {
opacity: .7;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 1.6rem;
margin-bottom: 1rem;
font-weight: $headings-font-weight;
line-height: $headings-line-height;
}
[padding] {
h1,
h2,
h3,
h4,
h5,
h6 {
&:first-child {
margin-top: -.3rem;
}
}
}
h1 + h2,
h1 + h3,
h2 + h3 {
margin-top: -.3rem;
}
h1 {
margin-top: 2rem;
font-size: $h1-font-size;
}
h2 {
margin-top: 1.8rem;
font-size: $h2-font-size;
}
h3 {
font-size: $h3-font-size;
}
h4 {
font-size: $h4-font-size;
}
h5 {
font-size: $h5-font-size;
}
h6 {
font-size: $h6-font-size;
}
small {
font-size: 75%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -.5em;
}
sub {
bottom: -.25em;
}
// Text Alignment
// --------------------------------------------------
[text-left] {
text-align: left;
}
[text-center] {
text-align: center;
}
[text-right] {
text-align: right;
}
[text-justify] {
text-align: justify;
}
[text-nowrap] {
white-space: nowrap;
}
// Text Transformation
// --------------------------------------------------
[text-uppercase] {
text-transform: uppercase;
}
[text-lowercase] {
text-transform: lowercase;
}
[text-capitalize] {
text-transform: capitalize;
}
| src/components/app/typography.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0002813202445395291,
0.0001863068318925798,
0.0001658174442127347,
0.00016944491653703153,
0.00003347464371472597
] |
{
"id": 0,
"code_window": [
"// --------------------------------------------------\n",
"\n",
"$modal-ios-background-color: $background-ios-color !default;\n",
"$modal-ios-border-radius: 5px !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-ios-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ios.scss",
"type": "replace",
"edit_start_line_idx": 7
} | @import "../../globals.core";
ion-scroll {
position: relative;
display: block;
&.scroll-x scroll-content {
overflow-x: auto;
}
&.scroll-y scroll-content {
overflow-y: auto;
}
&[center] {
scroll-content {
display: flex;
align-items: center;
justify-content: center;
}
}
scroll-content {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow-y: hidden;
overflow-x: hidden;
-webkit-overflow-scrolling: touch;
will-change: scroll-position;
}
}
| src/components/scroll/scroll.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00016804646293167025,
0.00016719038831070065,
0.0001662720023887232,
0.00016722155851311982,
7.387936307168275e-7
] |
{
"id": 1,
"code_window": [
"// Material Design Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-md-background-color: $background-md-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-md-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.md.scss",
"type": "replace",
"edit_start_line_idx": 6
} | import {Component, ComponentRef, DynamicComponentLoader, ElementRef, ViewChild, ViewContainerRef} from '@angular/core';
import {windowDimensions} from '../../util/dom';
import {pascalCaseToDashCase} from '../../util/util';
import {NavParams} from '../nav/nav-params';
import {ViewController} from '../nav/view-controller';
import {Animation} from '../../animations/animation';
import {Transition, TransitionOptions} from '../../transitions/transition';
/**
* @name Modal
* @description
* A Modal is a content pane that goes over the user's current page.
* Usually it is used for making a choice or editing an item. A modal uses the
* `NavController` to
* {@link /docs/v2/api/components/nav/NavController/#present present}
* itself in the root nav stack. It is added to the stack similar to how
* {@link /docs/v2/api/components/nav/NavController/#push NavController.push}
* works.
*
* When a modal (or any other overlay such as an alert or actionsheet) is
* "presented" to a nav controller, the overlay is added to the app's root nav.
* After the modal has been presented, from within the component instance The
* modal can later be closed or "dismissed" by using the ViewController's
* `dismiss` method. Additionally, you can dismiss any overlay by using `pop`
* on the root nav controller.
*
* Data can be passed to a new modal through `Modal.create()` as the second
* argument. The data can then be accessed from the opened page by injecting
* `NavParams`. Note that the page, which opened as a modal, has no special
* "modal" logic within it, but uses `NavParams` no differently than a
* standard page.
*
* @usage
* ```ts
* import {Page, Modal, NavController, NavParams} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(params: NavParams) {
* console.log('UserId', params.get('userId'));
* }
*
* }
* ```
*
* A modal can also emit data, which is useful when it is used to add or edit
* data. For example, a profile page could slide up in a modal, and on submit,
* the submit button could pass the updated profile data, then dismiss the
* modal.
*
* ```ts
* import {Page, Modal, NavController, ViewController} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentContactModal() {
* let contactModal = Modal.create(ContactUs);
* this.nav.present(contactModal);
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* profileModal.onDismiss(data => {
* console.log(data);
* });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(viewCtrl: ViewController) {
* this.viewCtrl = viewCtrl;
* }
*
* dismiss() {
* let data = { 'foo': 'bar' };
* this.viewCtrl.dismiss(data);
* }
*
* }
* ```
* @demo /docs/v2/demos/modal/
* @see {@link /docs/v2/components#modals Modal Component Docs}
*/
export class Modal extends ViewController {
public modalViewType: string;
constructor(componentType, data: any = {}) {
data.componentType = componentType;
super(ModalCmp, data);
this.modalViewType = componentType.name;
this.viewType = 'modal';
this.isOverlay = true;
}
/**
* @private
*/
getTransitionName(direction) {
let key = (direction === 'back' ? 'modalLeave' : 'modalEnter');
return this._nav && this._nav.config.get(key);
}
/**
* @param {any} componentType Modal
* @param {object} data Modal options
*/
static create(componentType, data = {}) {
return new Modal(componentType, data);
}
// Override the load method and load our child component
loaded(done) {
// grab the instance, and proxy the ngAfterViewInit method
let originalNgAfterViewInit = this.instance.ngAfterViewInit;
this.instance.ngAfterViewInit = () => {
if ( originalNgAfterViewInit ) {
originalNgAfterViewInit();
}
this.instance.loadComponent().then( (componentRef: ComponentRef<any>) => {
this.setInstance(componentRef.instance);
done();
});
};
}
}
@Component({
selector: 'ion-modal',
template:
'<div class="backdrop"></div>' +
'<div class="modal-wrapper">' +
'<div #viewport></div>' +
'</div>'
})
export class ModalCmp {
@ViewChild('viewport', {read: ViewContainerRef}) viewport: ViewContainerRef;
constructor(protected _eleRef: ElementRef, protected _loader: DynamicComponentLoader, protected _navParams: NavParams, protected _viewCtrl: ViewController) {
}
loadComponent(): Promise<ComponentRef<any>> {
return this._loader.loadNextToLocation(this._navParams.data.componentType, this.viewport).then(componentRef => {
return componentRef;
});
}
ngAfterViewInit() {
// intentionally kept empty
}
}
/**
* Animations for modals
*/
class ModalSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
wrapper.fromTo('translateY', '100%', '0%');
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapperEle = <HTMLElement> ele.querySelector('.modal-wrapper');
let wrapperEleRect = wrapperEle.getBoundingClientRect();
let wrapper = new Animation(wrapperEle);
// height of the screen - top of the container tells us how much to scoot it down
// so it's off-screen
let screenDimensions = windowDimensions();
wrapper.fromTo('translateY', '0px', `${screenDimensions.height - wrapperEleRect.top}px`);
this
.element(leavingView.pageRef())
.easing('ease-out')
.duration(250)
.add(backdrop)
.add(wrapper);
}
}
Transition.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '40px', '0px');
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fadeIn()
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '0px', '40px');
this
.element(leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fadeOut()
.add(wrapper)
.add(backdrop);
}
}
Transition.register('modal-md-slide-out', ModalMDSlideOut);
| src/components/modal/modal.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.5173578858375549,
0.030747829005122185,
0.00016587942081969231,
0.0002527254109736532,
0.11314865201711655
] |
{
"id": 1,
"code_window": [
"// Material Design Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-md-background-color: $background-md-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-md-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.md.scss",
"type": "replace",
"edit_start_line_idx": 6
} | @import "../../globals.core";
// Img
// --------------------------------------------------
ion-img {
position: relative;
display: block;
}
ion-img img {
display: block;
}
ion-img .img-placeholder {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #eee;
transition: opacity 200ms;
}
ion-img.img-loaded .img-placeholder {
opacity: 0;
}
| src/components/img/img.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017578595725353807,
0.000169113976880908,
0.00016520684584975243,
0.00016773153038229793,
0.000004196860572847072
] |
{
"id": 1,
"code_window": [
"// Material Design Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-md-background-color: $background-md-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-md-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.md.scss",
"type": "replace",
"edit_start_line_idx": 6
} | {
"sitePath": "../ionic-site",
"v2DocsDir": "docs/v2",
"docsDest": "../ionic-site/docs/v2"
}
| scripts/config.json | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001675454986980185,
0.0001675454986980185,
0.0001675454986980185,
0.0001675454986980185,
0
] |
{
"id": 1,
"code_window": [
"// Material Design Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-md-background-color: $background-md-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-md-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.md.scss",
"type": "replace",
"edit_start_line_idx": 6
} |
// it('should go to Tab1 Page1', function() {
// element(by.css('#signIn')).click();
// });
//
// it('should go to Tab1 Page2', function() {
// element(by.css('#goToTab1Page2')).click();
// });
//
// it('should go back to Tab1 Page1', function() {
// element(by.css('#backToTab1Page1')).click();
// });
//
// it('should go to Tab2 Page1', function() {
// element(by.css('.tab-button:nth-of-type(2)')).click();
// });
//
// it('should go back to Tab1 Page1', function() {
// element(by.css('.tab-button:nth-of-type(1)')).click();
// });
| src/components/tabs/test/advanced/e2e.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017578563711140305,
0.00017249541997443885,
0.0001706542680040002,
0.00017104636935982853,
0.000002332031726837158
] |
{
"id": 2,
"code_window": [
" z-index: 10;\n",
"\n",
" height: 100%;\n",
"\n",
" @media only screen and (min-width: $modal-inset-min-width) and (min-height: $modal-inset-min-height-small) {\n",
" position: absolute;\n",
" top: calc(50% - (#{$modal-inset-height-small}/2));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // hidden by default to prevent flickers, the animation will show it\n",
" transform: translate3d(0, 100%, 0);\n"
],
"file_path": "src/components/modal/modal.scss",
"type": "add",
"edit_start_line_idx": 33
} | import {Output, EventEmitter, Type, TemplateRef, ViewContainerRef, ElementRef, Renderer, ChangeDetectorRef} from '@angular/core';
import {Navbar} from '../navbar/navbar';
import {NavController, NavOptions} from './nav-controller';
import {NavParams} from './nav-params';
import {isPresent} from '../../util/util';
/**
* @name ViewController
* @description
* Access various features and information about the current view.
* @usage
* ```ts
* import {Page, ViewController} from 'ionic-angular';
* @Page....
* export class MyPage{
* constructor(viewCtrl: ViewController){
* this.viewCtrl = viewCtrl;
* }
* }
* ```
*/
export class ViewController {
private _cntDir: any;
private _cntRef: ElementRef;
private _tbRefs: ElementRef[] = [];
private _destroys: Function[] = [];
private _hdAttr: string = null;
private _leavingOpts: NavOptions = null;
private _loaded: boolean = false;
private _nbDir: Navbar;
private _nbTmpRef: TemplateRef<Object>;
private _nbVwRef: ViewContainerRef;
private _onDismiss: Function = null;
private _pgRef: ElementRef;
private _cd: ChangeDetectorRef;
protected _nav: NavController;
didLoad: EventEmitter<any>;
willEnter: EventEmitter<any>;
didEnter: EventEmitter<any>;
willLeave: EventEmitter<any>;
didLeave: EventEmitter<any>;
willUnload: EventEmitter<any>;
didUnload: EventEmitter<any>;
/**
* @private
*/
data: any;
/**
* @private
*/
id: string;
/**
* @private
*/
instance: any = {};
/**
* @private
*/
state: string = '';
/**
* @private
*/
viewType: string = '';
/**
* @private
* If this is currently the active view, then set to false
* if it does not want the other views to fire their own lifecycles.
*/
fireOtherLifecycles: boolean = true;
/**
* @private
*/
isOverlay: boolean = false;
/**
* @private
*/
usePortal: boolean = false;
/**
* @private
*/
zIndex: number;
/**
* @private
*/
@Output() private _emitter: EventEmitter<any> = new EventEmitter();
constructor(public componentType?: Type, data?: any) {
// passed in data could be NavParams, but all we care about is its data object
this.data = (data instanceof NavParams ? data.data : (isPresent(data) ? data : {}));
this.didLoad = new EventEmitter();
this.willEnter = new EventEmitter();
this.didEnter = new EventEmitter();
this.willLeave = new EventEmitter();
this.didLeave = new EventEmitter();
this.willUnload = new EventEmitter();
this.didUnload = new EventEmitter();
}
subscribe(generatorOrNext?: any): any {
return this._emitter.subscribe(generatorOrNext);
}
/**
* @private
*/
emit(data?: any) {
this._emitter.emit(data);
}
onDismiss(callback: Function) {
this._onDismiss = callback;
}
dismiss(data?: any, role?: any) {
return this._nav.remove(this._nav.indexOf(this), 1, this._leavingOpts).then(() => {
this._onDismiss && this._onDismiss(data, role);
return data;
});
}
/**
* @private
*/
setNav(navCtrl: NavController) {
this._nav = navCtrl;
}
/**
* @private
*/
getTransitionName(direction: string): string {
return this._nav && this._nav.config.get('pageTransition');
}
/**
* @private
*/
getNavParams(): NavParams {
return new NavParams(this.data);
}
/**
* @private
*/
setLeavingOpts(opts: NavOptions) {
this._leavingOpts = opts;
}
/**
* Check to see if you can go back in the navigation stack.
* @param {boolean} Check whether or not you can go back from this page
* @returns {boolean} Returns if it's possible to go back from this Page.
*/
enableBack(): boolean {
// update if it's possible to go back from this nav item
if (this._nav) {
let previousItem = this._nav.getPrevious(this);
// the previous view may exist, but if it's about to be destroyed
// it shouldn't be able to go back to
return !!(previousItem);
}
return false;
}
/**
* @private
*/
setChangeDetector(cd: ChangeDetectorRef) {
this._cd = cd;
}
/**
* @private
*/
setInstance(instance: any) {
this.instance = instance;
}
/**
* @private
*/
get name(): string {
return this.componentType ? this.componentType['name'] : '';
}
/**
* You can find out the index of the current view is in the current navigation stack.
*
* ```typescript
* export class Page1 {
* constructor(view: ViewController){
* this.view = view;
* // Just log out the index
* console.log(this.view.index);
* }
* }
* ```
*
* @returns {number} Returns the index of this page within its NavController.
*/
get index(): number {
return (this._nav ? this._nav.indexOf(this) : -1);
}
/**
* @private
*/
private isRoot(): boolean {
// deprecated warning
console.warn('ViewController isRoot() has been renamed to isFirst()');
return this.isFirst();
}
/**
* @returns {boolean} Returns if this Page is the first in the stack of pages within its NavController.
*/
isFirst(): boolean {
return (this._nav ? this._nav.first() === this : false);
}
/**
* @returns {boolean} Returns if this Page is the last in the stack of pages within its NavController.
*/
isLast(): boolean {
return (this._nav ? this._nav.last() === this : false);
}
/**
* @private
*/
domShow(shouldShow: boolean, renderer: Renderer) {
// using hidden element attribute to display:none and not render views
// renderAttr of '' means the hidden attribute will be added
// renderAttr of null means the hidden attribute will be removed
// doing checks to make sure we only make an update to the element when needed
if (this._pgRef &&
(shouldShow && this._hdAttr === '' ||
!shouldShow && this._hdAttr !== '')) {
this._hdAttr = (shouldShow ? null : '');
renderer.setElementAttribute(this._pgRef.nativeElement, 'hidden', this._hdAttr);
let navbarRef = this.navbarRef();
if (navbarRef) {
renderer.setElementAttribute(navbarRef.nativeElement, 'hidden', this._hdAttr);
}
}
}
/**
* @private
*/
setZIndex(zIndex: number, renderer: Renderer) {
if (this._pgRef && zIndex !== this.zIndex) {
this.zIndex = zIndex;
renderer.setElementStyle(this._pgRef.nativeElement, 'z-index', zIndex.toString());
}
}
/**
* @private
*/
setNavbarTemplateRef(templateRef: TemplateRef<Object>) {
this._nbTmpRef = templateRef;
}
/**
* @private
*/
getNavbarTemplateRef(): TemplateRef<Object> {
return this._nbTmpRef;
}
/**
* @private
*/
getNavbarViewRef() {
return this._nbVwRef;
}
/**
* @private
*/
setNavbarViewRef(viewContainerRef: ViewContainerRef) {
this._nbVwRef = viewContainerRef;
}
/**
* @private
*/
setPageRef(elementRef: ElementRef) {
this._pgRef = elementRef;
}
/**
* @private
* @returns {elementRef} Returns the Page's ElementRef
*/
pageRef(): ElementRef {
return this._pgRef;
}
/**
* @private
*/
setContentRef(elementRef: ElementRef) {
this._cntRef = elementRef;
}
/**
* @private
* @returns {elementRef} Returns the Page's Content ElementRef
*/
contentRef(): ElementRef {
return this._cntRef;
}
/**
* @private
*/
setToolbarRef(elementRef: ElementRef) {
this._tbRefs.push(elementRef);
}
/**
* @private
* @returns {elementRef} Returns the Page's Content ElementRef
*/
toolbarRefs(): ElementRef[] {
return this._tbRefs;
}
/**
* @private
*/
setContent(directive) {
this._cntDir = directive;
}
/**
* @private
* @returns {component} Returns the Page's Content component reference.
*/
getContent() {
return this._cntDir;
}
/**
* @private
*/
setNavbar(directive: Navbar) {
this._nbDir = directive;
}
/**
* @private
*/
getNavbar() {
return this._nbDir;
}
/**
* You can find out of the current view has a Navbar or not. Be sure to wrap this in an `onPageWillEnter` method in order to make sure the view has rendered fully.
*
* ```typescript
* export class Page1 {
* constructor(view: ViewController) {
* this.view = view
* }
* onPageWillEnter(){
* console.log('Do we have a Navbar?', this.view.hasNavbar());
* }
*}
* ```
*
* @returns {boolean} Returns a boolean if this Page has a navbar or not.
*/
hasNavbar(): boolean {
return !!this.getNavbar();
}
/**
* @private
*/
navbarRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getElementRef();
}
/**
* @private
*/
titleRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getTitleRef();
}
/**
* @private
*/
navbarItemRefs(): Array<ElementRef> {
let navbar = this.getNavbar();
return navbar && navbar.getItemRefs();
}
/**
* @private
*/
backBtnRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getBackButtonRef();
}
/**
* @private
*/
backBtnTextRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getBackButtonTextRef();
}
/**
* @private
*/
navbarBgRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getBackgroundRef();
}
/**
* You can change the text of the back button on a view-by-view basis.
*
* ```ts
* export class MyClass{
* constructor(viewCtrl: ViewController){
* this.viewCtrl = viewCtrl
* }
* onPageWillEnter() {
* this.viewCtrl.setBackButtonText('Previous');
* }
* }
* ```
* Make sure you use the view events when calling this method, otherwise the back-button will not have been created
*
* @param {string} backButtonText Set the back button text.
*/
setBackButtonText(val: string) {
let navbar = this.getNavbar();
if (navbar) {
navbar.setBackButtonText(val);
}
}
/**
* Set if the back button for the current view is visible or not. Be sure to wrap this in `onPageWillEnter` to make sure the has been compleltly rendered.
* @param {boolean} Set if this Page's back button should show or not.
*/
showBackButton(shouldShow: boolean) {
let navbar = this.getNavbar();
if (navbar) {
navbar.hideBackButton = !shouldShow;
}
}
/**
* @private
*/
isLoaded(): boolean {
return this._loaded;
}
/**
* The loaded method is used to load any dynamic content/components
* into the dom before proceeding with the transition. If a component needs
* dynamic component loading, extending ViewController and overriding
* this method is a good option
* @param {function} done is a callback that must be called when async loading/actions are completed
*/
loaded(done: (() => any)) {
done();
}
/**
* @private
* The view has loaded. This event only happens once per view being
* created. If a view leaves but is cached, then this will not
* fire again on a subsequent viewing. This method is a good place
* to put your setup code for the view; however, it is not the
* recommended method to use when a view becomes active.
*/
fireLoaded() {
this._loaded = true;
this.didLoad.emit(null);
ctrlFn(this, 'onPageLoaded');
}
/**
* @private
* The view is about to enter and become the active view.
*/
fireWillEnter() {
if (this._cd) {
// ensure this has been re-attached to the change detector
this._cd.reattach();
// detect changes before we run any user code
this._cd.detectChanges();
}
this.willEnter.emit(null);
ctrlFn(this, 'onPageWillEnter');
}
/**
* @private
* The view has fully entered and is now the active view. This
* will fire, whether it was the first load or loaded from the cache.
*/
fireDidEnter() {
let navbar = this.getNavbar();
navbar && navbar.didEnter();
this.didEnter.emit(null);
ctrlFn(this, 'onPageDidEnter');
}
/**
* @private
* The view has is about to leave and no longer be the active view.
*/
fireWillLeave() {
this.willLeave.emit(null);
ctrlFn(this, 'onPageWillLeave');
}
/**
* @private
* The view has finished leaving and is no longer the active view. This
* will fire, whether it is cached or unloaded.
*/
fireDidLeave() {
this.didLeave.emit(null);
ctrlFn(this, 'onPageDidLeave');
// when this is not the active page
// we no longer need to detect changes
this._cd && this._cd.detach();
}
/**
* @private
* The view is about to be destroyed and have its elements removed.
*/
fireWillUnload() {
this.willUnload.emit(null);
ctrlFn(this, 'onPageWillUnload');
}
/**
* @private
*/
onDestroy(destroyFn: Function) {
this._destroys.push(destroyFn);
}
/**
* @private
*/
destroy() {
this.didUnload.emit(null);
ctrlFn(this, 'onPageDidUnload');
for (var i = 0; i < this._destroys.length; i++) {
this._destroys[i]();
}
this._destroys.length = 0;
this._tbRefs.length = 0;
}
}
export interface LifeCycleEvent {
componentType?: any;
}
function ctrlFn(viewCtrl: ViewController, fnName: string) {
if (viewCtrl.instance && viewCtrl.instance[fnName]) {
try {
viewCtrl.instance[fnName]();
} catch (e) {
console.error(viewCtrl.name + ' ' + fnName + ': ' + e.message);
}
}
}
| src/components/nav/view-controller.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00019837553554680198,
0.00017162632138933986,
0.00016341420996468514,
0.00017217495769727975,
0.000004920348601444857
] |
{
"id": 2,
"code_window": [
" z-index: 10;\n",
"\n",
" height: 100%;\n",
"\n",
" @media only screen and (min-width: $modal-inset-min-width) and (min-height: $modal-inset-min-height-small) {\n",
" position: absolute;\n",
" top: calc(50% - (#{$modal-inset-height-small}/2));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // hidden by default to prevent flickers, the animation will show it\n",
" transform: translate3d(0, 100%, 0);\n"
],
"file_path": "src/components/modal/modal.scss",
"type": "add",
"edit_start_line_idx": 33
} | <ion-toolbar><ion-title>List No Lines</ion-title></ion-toolbar>
<ion-content class="outer-content">
<ion-list no-lines>
<ion-list-header>
List With No Lines
</ion-list-header>
<ion-item>
<ion-icon name="wifi" item-left></ion-icon>
<ion-label>Wifi</ion-label>
<ion-toggle></ion-toggle>
</ion-item>
<ion-item>
<ion-icon name="heart" item-left></ion-icon>
Affection
<ion-note item-right>
Very Little
</ion-note>
</ion-item>
<ion-item>
<ion-icon name="home" item-left></ion-icon>
Home
<ion-note item-right>
Where the heart is
</ion-note>
</ion-item>
</ion-list>
<ion-list no-lines>
<ion-list-header>
List With Checkboxes No Lines
</ion-list-header>
<ion-item>
<ion-checkbox item-left></ion-checkbox>
<ion-avatar item-left>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==">
</ion-avatar>
<ion-label>Wifi</ion-label>
</ion-item>
<ion-item>
<ion-checkbox item-left></ion-checkbox>
<ion-avatar item-left>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==">
</ion-avatar>
<ion-label>Affection</ion-label>
</ion-item>
<ion-item>
<ion-checkbox item-left></ion-checkbox>
<ion-avatar item-left>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==">
</ion-avatar>
<ion-label>Home</ion-label>
</ion-item>
</ion-list>
<ion-list>
<ion-list-header>
List With No Lines First Item
</ion-list-header>
<ion-item no-lines>
<ion-icon name="pizza" item-left></ion-icon>
Pizza
<ion-note item-right>
Always
</ion-note>
</ion-item>
<ion-item>
<ion-icon name="beer" item-left></ion-icon>
Beer
<ion-note item-right>
Yes Plz
</ion-note>
</ion-item>
<ion-item>
<ion-icon name="wine" item-left></ion-icon>
Wine
<ion-note item-right>
All the time
</ion-note>
</ion-item>
</ion-list>
<ion-list>
<ion-list-header>
List With No Lines Middle Item
</ion-list-header>
<ion-item>
<ion-icon name="pizza" item-left></ion-icon>
Pizza
<ion-note item-right>
Always
</ion-note>
</ion-item>
<ion-item no-lines>
<ion-icon name="beer" item-left></ion-icon>
Beer
<ion-note item-right>
Yes Plz
</ion-note>
</ion-item>
<ion-item>
<ion-icon name="wine" item-left></ion-icon>
Wine
<ion-note item-right>
All the time
</ion-note>
</ion-item>
</ion-list>
<ion-list>
<ion-list-header>
List With No Lines Last Item
</ion-list-header>
<ion-item>
<ion-icon name="pizza" item-left></ion-icon>
Pizza
<ion-note item-right>
Always
</ion-note>
</ion-item>
<ion-item>
<ion-icon name="beer" item-left></ion-icon>
Beer
<ion-note item-right>
Yes Plz
</ion-note>
</ion-item>
<ion-item no-lines>
<ion-icon name="wine" item-left></ion-icon>
Wine
<ion-note item-right>
All the time
</ion-note>
</ion-item>
</ion-list>
</ion-content>
<style>
img {
height: 100px;
}
</style>
| src/components/list/test/no-lines/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017627759370952845,
0.0001727804628899321,
0.00016616690845694393,
0.0001736282283673063,
0.0000029404834549495718
] |
{
"id": 2,
"code_window": [
" z-index: 10;\n",
"\n",
" height: 100%;\n",
"\n",
" @media only screen and (min-width: $modal-inset-min-width) and (min-height: $modal-inset-min-height-small) {\n",
" position: absolute;\n",
" top: calc(50% - (#{$modal-inset-height-small}/2));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // hidden by default to prevent flickers, the animation will show it\n",
" transform: translate3d(0, 100%, 0);\n"
],
"file_path": "src/components/modal/modal.scss",
"type": "add",
"edit_start_line_idx": 33
} |
<ion-navbar *navbar>
<ion-title>Loading</ion-title>
</ion-navbar>
<ion-content padding>
<button block (click)="presentLoadingIos()">iOS Spinner</button>
<button block (click)="presentLoadingDots()">Dots Spinner</button>
<button block (click)="presentLoadingBubbles()">Bubbles Spinner</button>
<button block (click)="presentLoadingCircles()">Circles Spinner</button>
<button block (click)="presentLoadingCrescent()">Crescent Spinner</button>
<button block (click)="presentLoadingDefault()" secondary class="e2eLoadingDefaultSpinner">Default Spinner</button>
<button block (click)="presentLoadingCustom()" light>Custom Spinner</button>
<button block (click)="presentLoadingText()" dark>Content Only w/ Nav</button>
<button block (click)="presentLoadingMultiple()" danger>Multiple Loading</button>
<button block (click)="presentLoadingMultipleNav()" danger>Multiple Nav Loading</button>
</ion-content>
<ion-toolbar position="bottom">
<ion-buttons end>
<button (click)="goToPage2()">
Navigate
<ion-icon name="arrow-forward"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
| src/components/loading/test/basic/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017413539171684533,
0.00017098688113037497,
0.00016652140766382217,
0.00017230388766620308,
0.000003244897470722208
] |
{
"id": 2,
"code_window": [
" z-index: 10;\n",
"\n",
" height: 100%;\n",
"\n",
" @media only screen and (min-width: $modal-inset-min-width) and (min-height: $modal-inset-min-height-small) {\n",
" position: absolute;\n",
" top: calc(50% - (#{$modal-inset-height-small}/2));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // hidden by default to prevent flickers, the animation will show it\n",
" transform: translate3d(0, 100%, 0);\n"
],
"file_path": "src/components/modal/modal.scss",
"type": "add",
"edit_start_line_idx": 33
} | @import "../../globals.core";
// Refresher
// --------------------------------------------------
$refresher-height: 60px !default;
$refresher-icon-color: #000 !default;
$refresher-icon-font-size: 30px !default;
$refresher-text-color: #000 !default;
$refresher-text-font-size: 16px !default;
$refresher-border-color: #ddd !default;
ion-refresher {
position: absolute;
top: 0;
left: 0;
z-index: $z-index-refresher;
display: none;
width: 100%;
height: $refresher-height;
&.refresher-active {
display: block;
}
}
.has-refresher > scroll-content {
// when the refresher is let go or has completed
// this transition is what is used to put the
// scroll content back into it's original location
margin-top: -1px;
border-top: 1px solid $refresher-border-color;
transition: all 320ms cubic-bezier(.36, .66, .04, 1);
}
// Refresher Content
// --------------------------------------------------
ion-refresher-content {
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
}
.refresher-pulling,
.refresher-refreshing {
display: none;
width: 100%;
}
.refresher-pulling-icon,
.refresher-refreshing-icon {
font-size: $refresher-icon-font-size;
text-align: center;
color: $refresher-icon-color;
transform-origin: center;
transition: 200ms;
}
.refresher-pulling-text,
.refresher-refreshing-text {
font-size: $refresher-text-font-size;
text-align: center;
color: $refresher-text-color;
}
// Refresher Content States
// --------------------------------------------------
ion-refresher-content[state=pulling] {
.refresher-pulling {
display: block;
}
}
ion-refresher-content[state=ready] {
.refresher-pulling {
display: block;
}
.refresher-pulling-icon {
transform: rotate(180deg);
}
}
ion-refresher-content[state=refreshing] {
.refresher-refreshing {
display: block;
}
}
ion-refresher-content[state=cancelling] {
.refresher-pulling {
display: block;
}
.refresher-pulling-icon {
transform: scale(0);
}
}
ion-refresher-content[state=completing] {
.refresher-refreshing {
display: block;
}
.refresher-refreshing-icon {
transform: scale(0);
}
}
| src/components/refresher/refresher.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.007055890280753374,
0.0007010311237536371,
0.00016763914027251303,
0.00017314479919150472,
0.0018344921991229057
] |
{
"id": 3,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 191
} | @import "../../globals.md";
// Material Design Modals
// --------------------------------------------------
$modal-md-background-color: $background-md-color !default;
.modal-wrapper {
background-color: $modal-md-background-color;
}
| src/components/modal/modal.md.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001713939564069733,
0.0001681843859842047,
0.00016497481556143612,
0.0001681843859842047,
0.000003209570422768593
] |
{
"id": 3,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 191
} | ---
layout: "v2_fluid/docs_base"
version: "<$ version.current.name $>"
versionHref: "<$ version.current.href $>"
path: ""
category: api
id: api
title: Javascript
header_sub_title: Extend Ionic even further with the power of AngularJS
searchable: false
---
# Ionic 2 API Docs
<img class="section-header" src="/img/docs/api-intro-header.png" />
Ionic 2 takes everything you know and loved about Ionic 1, and builds on top of it to provide a much more flexible framework.
In the API docs, you'll find two kinds of doc pages: Component and Service APIs.
The Component APIs include classes like `Checkbox`, `Toggle` or `Item` and show you how to use them, in addition to listing their selectors, available properties and events.
The Service APIs are classes like `MenuController`, `Config` or `Platform`. These are services provided by Ionic 2 that can be injected into your classes.
| scripts/docs/templates/api_index.template.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017562713765073568,
0.00017012232274282724,
0.0001626800949452445,
0.00017205975018441677,
0.000005460261490952689
] |
{
"id": 3,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 191
} | src/components/input/test/floating-labels/e2e.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00016828809748403728,
0.00016828809748403728,
0.00016828809748403728,
0.00016828809748403728,
0
] |
|
{
"id": 3,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 191
} |
import {Animation} from './animation';
class SlideIn extends Animation {
constructor(element) {
super(element);
this
.easing('cubic-bezier(0.1,0.7,0.1,1)')
.duration(400)
.fromTo('translateY', '100%', '0%');
}
}
Animation.register('slide-in', SlideIn);
class SlideOut extends Animation {
constructor(element) {
super(element);
this
.easing('ease-out')
.duration(250)
.fromTo('translateY', '0%', '100%');
}
}
Animation.register('slide-out', SlideOut);
class FadeIn extends Animation {
constructor(element) {
super(element);
this
.easing('ease-in')
.duration(400)
.fadeIn();
}
}
Animation.register('fade-in', FadeIn);
class FadeOut extends Animation {
constructor(element) {
super(element);
this
.easing('ease-out')
.duration(250)
.fadeOut();
}
}
Animation.register('fade-out', FadeOut);
| src/animations/builtins.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017082210979424417,
0.0001673119404586032,
0.0001648568722885102,
0.00016684237925801426,
0.0000018680237872104044
] |
{
"id": 4,
"code_window": [
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" wrapper.fromTo('translateY', '100%', '0%');\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(400)\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const DURATION = 400;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 198
} | import {Component, ComponentRef, DynamicComponentLoader, ElementRef, ViewChild, ViewContainerRef} from '@angular/core';
import {windowDimensions} from '../../util/dom';
import {pascalCaseToDashCase} from '../../util/util';
import {NavParams} from '../nav/nav-params';
import {ViewController} from '../nav/view-controller';
import {Animation} from '../../animations/animation';
import {Transition, TransitionOptions} from '../../transitions/transition';
/**
* @name Modal
* @description
* A Modal is a content pane that goes over the user's current page.
* Usually it is used for making a choice or editing an item. A modal uses the
* `NavController` to
* {@link /docs/v2/api/components/nav/NavController/#present present}
* itself in the root nav stack. It is added to the stack similar to how
* {@link /docs/v2/api/components/nav/NavController/#push NavController.push}
* works.
*
* When a modal (or any other overlay such as an alert or actionsheet) is
* "presented" to a nav controller, the overlay is added to the app's root nav.
* After the modal has been presented, from within the component instance The
* modal can later be closed or "dismissed" by using the ViewController's
* `dismiss` method. Additionally, you can dismiss any overlay by using `pop`
* on the root nav controller.
*
* Data can be passed to a new modal through `Modal.create()` as the second
* argument. The data can then be accessed from the opened page by injecting
* `NavParams`. Note that the page, which opened as a modal, has no special
* "modal" logic within it, but uses `NavParams` no differently than a
* standard page.
*
* @usage
* ```ts
* import {Page, Modal, NavController, NavParams} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(params: NavParams) {
* console.log('UserId', params.get('userId'));
* }
*
* }
* ```
*
* A modal can also emit data, which is useful when it is used to add or edit
* data. For example, a profile page could slide up in a modal, and on submit,
* the submit button could pass the updated profile data, then dismiss the
* modal.
*
* ```ts
* import {Page, Modal, NavController, ViewController} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentContactModal() {
* let contactModal = Modal.create(ContactUs);
* this.nav.present(contactModal);
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* profileModal.onDismiss(data => {
* console.log(data);
* });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(viewCtrl: ViewController) {
* this.viewCtrl = viewCtrl;
* }
*
* dismiss() {
* let data = { 'foo': 'bar' };
* this.viewCtrl.dismiss(data);
* }
*
* }
* ```
* @demo /docs/v2/demos/modal/
* @see {@link /docs/v2/components#modals Modal Component Docs}
*/
export class Modal extends ViewController {
public modalViewType: string;
constructor(componentType, data: any = {}) {
data.componentType = componentType;
super(ModalCmp, data);
this.modalViewType = componentType.name;
this.viewType = 'modal';
this.isOverlay = true;
}
/**
* @private
*/
getTransitionName(direction) {
let key = (direction === 'back' ? 'modalLeave' : 'modalEnter');
return this._nav && this._nav.config.get(key);
}
/**
* @param {any} componentType Modal
* @param {object} data Modal options
*/
static create(componentType, data = {}) {
return new Modal(componentType, data);
}
// Override the load method and load our child component
loaded(done) {
// grab the instance, and proxy the ngAfterViewInit method
let originalNgAfterViewInit = this.instance.ngAfterViewInit;
this.instance.ngAfterViewInit = () => {
if ( originalNgAfterViewInit ) {
originalNgAfterViewInit();
}
this.instance.loadComponent().then( (componentRef: ComponentRef<any>) => {
this.setInstance(componentRef.instance);
done();
});
};
}
}
@Component({
selector: 'ion-modal',
template:
'<div class="backdrop"></div>' +
'<div class="modal-wrapper">' +
'<div #viewport></div>' +
'</div>'
})
export class ModalCmp {
@ViewChild('viewport', {read: ViewContainerRef}) viewport: ViewContainerRef;
constructor(protected _eleRef: ElementRef, protected _loader: DynamicComponentLoader, protected _navParams: NavParams, protected _viewCtrl: ViewController) {
}
loadComponent(): Promise<ComponentRef<any>> {
return this._loader.loadNextToLocation(this._navParams.data.componentType, this.viewport).then(componentRef => {
return componentRef;
});
}
ngAfterViewInit() {
// intentionally kept empty
}
}
/**
* Animations for modals
*/
class ModalSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
wrapper.fromTo('translateY', '100%', '0%');
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapperEle = <HTMLElement> ele.querySelector('.modal-wrapper');
let wrapperEleRect = wrapperEle.getBoundingClientRect();
let wrapper = new Animation(wrapperEle);
// height of the screen - top of the container tells us how much to scoot it down
// so it's off-screen
let screenDimensions = windowDimensions();
wrapper.fromTo('translateY', '0px', `${screenDimensions.height - wrapperEleRect.top}px`);
this
.element(leavingView.pageRef())
.easing('ease-out')
.duration(250)
.add(backdrop)
.add(wrapper);
}
}
Transition.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '40px', '0px');
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fadeIn()
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '0px', '40px');
this
.element(leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fadeOut()
.add(wrapper)
.add(backdrop);
}
}
Transition.register('modal-md-slide-out', ModalMDSlideOut);
| src/components/modal/modal.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9982886910438538,
0.13472798466682434,
0.00016102906374726444,
0.00019272539066150784,
0.3315935432910919
] |
{
"id": 4,
"code_window": [
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" wrapper.fromTo('translateY', '100%', '0%');\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(400)\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const DURATION = 400;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 198
} | @import "../../globals.wp";
@import "./alert";
// Windows Alerts
// --------------------------------------------------
$alert-wp-backdrop-background: #fff !default;
$alert-wp-width: 100% !default;
$alert-wp-max-width: 520px !default;
$alert-wp-border-width: 1px !default;
$alert-wp-border-style: solid !default;
$alert-wp-border-color: color($colors-wp, primary) !default;
$alert-wp-border-radius: 0 !default;
$alert-wp-background: #e6e6e6 !default;
$alert-wp-head-padding: 20px 22px 5px 22px !default;
$alert-wp-head-text-align: left !default;
$alert-wp-title-font-size: 20px !default;
$alert-wp-title-font-weight: 400 !default;
$alert-wp-sub-title-font-size: 16px !default;
$alert-wp-message-padding: 0 22px 8px 22px !default;
$alert-wp-message-padding-empty: 0 !default;
$alert-wp-message-text-color: #000 !default;
$alert-wp-message-font-size: 13px !default;
$alert-wp-content-max-height: 240px !default;
$alert-wp-input-margin: 5px 0 5px 0 !default;
$alert-wp-input-padding: 0 8px !default;
$alert-wp-input-border-width: 2px !default;
$alert-wp-input-border-style: $alert-wp-border-style !default;
$alert-wp-input-border-color: $input-wp-border-color !default;
$alert-wp-input-border-color-focused: color($colors-wp, primary) !default;
$alert-wp-input-line-height: 3rem !default;
$alert-wp-input-text-color: #000 !default;
$alert-wp-button-padding: 5px !default;
$alert-wp-button-width: 49.5% !default;
$alert-wp-button-border-radius: 0 !default;
$alert-wp-button-font-weight: 400 !default;
$alert-wp-button-text-color: #000 !default;
$alert-wp-button-background: #b8b8b8 !default;
$alert-wp-button-background-activated: color-shade($alert-wp-button-background) !default;
$alert-wp-button-margin-right: 1% !default;
$alert-wp-button-group-padding: 20px 22px 20px 22px !default;
$alert-wp-button-group-justify-content: flex-end !default;
$alert-wp-button-group-flex-wrap: wrap-reverse !default;
$alert-wp-button-group-vertical-width: 100% !default;
$alert-wp-button-group-vertical-margin-top: 5px !default;
$alert-wp-radio-background: color($colors-wp, primary) !default;
$alert-wp-radio-border-color: $input-wp-border-color !default;
$alert-wp-radio-label-padding: 13px 26px !default;
$alert-wp-radio-label-text-color-checked: $alert-wp-button-text-color !default;
$alert-wp-radio-top: 0 !default;
$alert-wp-radio-left: 13px !default;
$alert-wp-radio-width: 16px !default;
$alert-wp-radio-height: 16px !default;
$alert-wp-radio-border-width: 2px !default;
$alert-wp-radio-border-style: solid !default;
$alert-wp-radio-border-radius: 50% !default;
$alert-wp-radio-border-color: $input-wp-border-color !default;
$alert-wp-radio-icon-top: 2px !default;
$alert-wp-radio-icon-left: 2px !default;
$alert-wp-radio-icon-width: 8px !default;
$alert-wp-radio-icon-height: 8px !default;
$alert-wp-radio-icon-border-radius: $alert-wp-radio-border-radius !default;
$alert-wp-checkbox-label-padding: 13px 26px !default;
$alert-wp-checkbox-label-text-color-checked: initial !default;
$alert-wp-checkbox-top: 0 !default;
$alert-wp-checkbox-left: 13px !default;
$alert-wp-checkbox-width: 16px !default;
$alert-wp-checkbox-height: 16px !default;
$alert-wp-checkbox-border-width: 2px !default;
$alert-wp-checkbox-border-style: solid !default;
$alert-wp-checkbox-border-radius: 0 !default;
$alert-wp-checkbox-border-color: $input-wp-border-color !default;
$alert-wp-checkbox-background-off: transparent !default;
$alert-wp-checkbox-background-on: color($colors-wp, primary) !default;
$alert-wp-checkbox-icon-top: -2px !default;
$alert-wp-checkbox-icon-left: 3px !default;
$alert-wp-checkbox-icon-width: 6px !default;
$alert-wp-checkbox-icon-height: 12px !default;
$alert-wp-checkbox-icon-border-width: 1px !default;
$alert-wp-checkbox-icon-border-style: solid !default;
$alert-wp-checkbox-icon-border-color: color-contrast($colors-wp, $alert-wp-checkbox-background-on) !default;
$alert-wp-checkbox-icon-transform: rotate(45deg) !default;
ion-alert {
.backdrop {
background: $alert-wp-backdrop-background;
}
}
.alert-wrapper {
width: $alert-wp-width;
max-width: $alert-wp-max-width;
border: $alert-wp-border-width $alert-wp-border-style $alert-wp-border-color;
border-radius: $alert-wp-border-radius;
background: $alert-wp-background;
}
// Windows Alert Header
// --------------------------------------------------
.alert-head {
padding: $alert-wp-head-padding;
text-align: $alert-wp-head-text-align;
}
.alert-title {
font-size: $alert-wp-title-font-size;
font-weight: $alert-wp-title-font-weight;
}
.alert-sub-title {
font-size: $alert-wp-sub-title-font-size;
}
// Windows Alert Message
// --------------------------------------------------
.alert-message,
.alert-input-group {
padding: $alert-wp-message-padding;
color: $alert-wp-message-text-color;
}
.alert-message {
max-height: $alert-wp-content-max-height;
font-size: $alert-wp-message-font-size;
&:empty {
padding: $alert-wp-message-padding-empty;
}
}
// Windows Alert Input
// --------------------------------------------------
.alert-input {
margin: $alert-wp-input-margin;
padding: $alert-wp-input-padding;
border: $alert-wp-input-border-width $alert-wp-input-border-style $alert-wp-input-border-color;
line-height: $alert-wp-input-line-height;
color: $alert-wp-input-text-color;
&:focus {
border-color: $alert-wp-input-border-color-focused;
}
}
// Windows Alert Radio/Checkbox Group
// --------------------------------------------------
.alert-radio-group,
.alert-checkbox-group {
position: relative;
overflow: auto;
max-height: $alert-wp-content-max-height;
}
.alert-tappable {
position: relative;
display: flex;
overflow: hidden;
// TODO this should be a variable that matches item
min-height: 4.4rem;
}
// Windows Alert Radio Label
// --------------------------------------------------
.alert-radio-label {
overflow: hidden;
flex: 1;
padding: $alert-wp-radio-label-padding;
text-overflow: ellipsis;
white-space: nowrap;
}
// Windows Alert Radio Unchecked Circle
// ---------------------------------------------------
.alert-radio-icon {
position: relative;
top: $alert-wp-radio-top;
left: $alert-wp-radio-left;
display: block;
margin: 0;
width: $alert-wp-radio-width;
height: $alert-wp-radio-height;
border-width: $alert-wp-radio-border-width;
border-style: $alert-wp-radio-border-style;
border-radius: $alert-wp-radio-border-radius;
border-color: $alert-wp-radio-border-color;
}
// Windows Alert Radio Checked Dot
// ---------------------------------------------------
.alert-radio-inner {
position: absolute;
top: $alert-wp-radio-icon-top;
left: $alert-wp-radio-icon-left;
display: none;
width: $alert-wp-radio-icon-width;
height: $alert-wp-radio-icon-height;
border-radius: $alert-wp-radio-icon-border-radius;
background: $alert-wp-radio-background;
}
// Windows Alert Radio Checked
// ---------------------------------------------------
.alert-radio[aria-checked=true] {
.alert-radio-label {
color: $alert-wp-radio-label-text-color-checked;
}
.alert-radio-icon {
border-color: $alert-wp-radio-border-color;
}
.alert-radio-inner {
display: block;
}
}
// Windows Alert Checkbox Label
// --------------------------------------------------
.alert-checkbox-label {
overflow: hidden;
flex: 1;
padding: $alert-wp-checkbox-label-padding;
text-overflow: ellipsis;
white-space: nowrap;
}
.alert-checkbox[aria-checked=true] .alert-checkbox-label {
color: $alert-wp-checkbox-label-text-color-checked;
}
// Windows Alert Checkbox Outline: Unchecked
// --------------------------------------------------
.alert-checkbox-icon {
position: relative;
top: $alert-wp-checkbox-top;
left: $alert-wp-checkbox-left;
width: $alert-wp-checkbox-width;
height: $alert-wp-checkbox-height;
border-width: $alert-wp-checkbox-border-width;
border-style: $alert-wp-checkbox-border-style;
border-radius: $alert-wp-checkbox-border-radius;
border-color: $alert-wp-checkbox-border-color;
background: $alert-wp-checkbox-background-off;
}
// Windows Alert Checkbox Outline: Checked
// --------------------------------------------------
.alert-checkbox[aria-checked=true] .alert-checkbox-icon {
border-color: $alert-wp-checkbox-background-on;
background: $alert-wp-checkbox-background-on;
}
// Windows Alert Checkbox Checkmark: Checked
// --------------------------------------------------
.alert-checkbox[aria-checked=true] .alert-checkbox-inner {
position: absolute;
top: $alert-wp-checkbox-icon-top;
left: $alert-wp-checkbox-icon-left;
width: $alert-wp-checkbox-icon-width;
height: $alert-wp-checkbox-icon-height;
border-width: $alert-wp-checkbox-icon-border-width;
border-top-width: 0;
border-left-width: 0;
border-style: $alert-wp-checkbox-icon-border-style;
border-color: $alert-wp-checkbox-icon-border-color;
transform: $alert-wp-checkbox-icon-transform;
}
// Windows Alert Button
// --------------------------------------------------
.alert-button-group {
flex-wrap: $alert-wp-button-group-flex-wrap;
justify-content: $alert-wp-button-group-justify-content;
padding: $alert-wp-button-group-padding;
&.vertical .alert-button {
margin-top: $alert-wp-button-group-vertical-margin-top;
width: $alert-wp-button-group-vertical-width;
&:first-child:not(:only-child) {
margin-top: 0;
}
}
}
.alert-button {
padding: $alert-wp-button-padding;
width: $alert-wp-button-width;
border-radius: $alert-wp-button-border-radius;
font-weight: $alert-wp-button-font-weight;
color: $alert-wp-button-text-color;
background: $alert-wp-button-background;
&:first-child:not(:only-child) {
margin-right: $alert-wp-button-margin-right;
}
&.activated {
background: $alert-wp-button-background-activated;
}
}
| src/components/alert/alert.wp.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017265962378587574,
0.00016853836132213473,
0.00016433784912806004,
0.0001692446239758283,
0.0000024066519017651444
] |
{
"id": 4,
"code_window": [
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" wrapper.fromTo('translateY', '100%', '0%');\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(400)\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const DURATION = 400;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 198
} | import {Routes} from '@angular/router';
import {Location} from '@angular/common';
import {App, Page, NavParams, ViewController} from '../../../../../src';
@Page({templateUrl: 'view1.html'})
class View1Cmp {
path: string;
windowHash: string;
constructor(location: Location, private viewCtrl: ViewController) {
this.path = location.path();
console.log(`View1Cmp, path: ${this.path}`);
}
onPageDidEnter() {
this.windowHash = window.location.hash;
}
}
@Page({templateUrl: 'view2.html'})
class View2Cmp {
path: string;
windowHash: string;
constructor(location: Location, private viewCtrl: ViewController) {
this.path = location.path();
console.log(`View2Cmp, path: ${this.path}`);
}
onPageDidEnter() {
this.windowHash = window.location.hash;
}
}
@Page({templateUrl: 'view3.html'})
class View3Cmp {
id: string;
path: string;
windowHash: string;
constructor(params: NavParams, location: Location, private viewCtrl: ViewController) {
this.id = params.get('id');
this.path = location.path();
console.log(`View3Cmp, path: ${this.path}, param id: ${this.id}`);
}
onPageDidEnter() {
this.windowHash = window.location.hash;
}
}
@App()
@Routes([
{ path: '/', component: View1Cmp },
{ path: '/2', component: View2Cmp },
{ path: '/3/:id', component: View3Cmp }
])
class InboxApp {
constructor(private location: Location) {}
}
| src/components/nav/test/routing/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00016876969311852008,
0.00016644841525703669,
0.00016452441923320293,
0.00016671571938786656,
0.000001337176286142494
] |
{
"id": 4,
"code_window": [
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" wrapper.fromTo('translateY', '100%', '0%');\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(400)\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const DURATION = 400;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 198
} | <ion-toolbar>
<ion-title>Full Buttons</ion-title>
</ion-toolbar>
<ion-content>
<p>
<a button full href="#">a[button][full]</a>
<button full>button[full]</button>
</p>
<p>
<a button full href="#">
<ion-icon name="help-circle"></ion-icon>
a[button][full] + icon
</a>
<button full>
<ion-icon name="help-circle"></ion-icon>
button[full] + icon
</button>
</p>
<p>
<a button full outline secondary href="#">a[button][full][outline][secondary]</a>
<button full outline secondary>button[full][outline][secondary]</button>
</p>
<p>
<a button full clear light href="#">a[button][full][clear][light]</a>
<button full clear light>button[full][clear][light]</button>
</p>
<p>
<a button full clear dark href="#">a[button][full][clear][dark]</a>
<button full clear dark>button[full][clear][dark]</button>
</p>
</ion-content> | src/components/button/test/full/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001745571498759091,
0.00017298513557761908,
0.00017132483480963856,
0.0001730293151922524,
0.0000014723690355822328
] |
{
"id": 5,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" wrapper.fromTo('translateY', '40px', '0px');\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 255
} | import {Component, ComponentRef, DynamicComponentLoader, ElementRef, ViewChild, ViewContainerRef} from '@angular/core';
import {windowDimensions} from '../../util/dom';
import {pascalCaseToDashCase} from '../../util/util';
import {NavParams} from '../nav/nav-params';
import {ViewController} from '../nav/view-controller';
import {Animation} from '../../animations/animation';
import {Transition, TransitionOptions} from '../../transitions/transition';
/**
* @name Modal
* @description
* A Modal is a content pane that goes over the user's current page.
* Usually it is used for making a choice or editing an item. A modal uses the
* `NavController` to
* {@link /docs/v2/api/components/nav/NavController/#present present}
* itself in the root nav stack. It is added to the stack similar to how
* {@link /docs/v2/api/components/nav/NavController/#push NavController.push}
* works.
*
* When a modal (or any other overlay such as an alert or actionsheet) is
* "presented" to a nav controller, the overlay is added to the app's root nav.
* After the modal has been presented, from within the component instance The
* modal can later be closed or "dismissed" by using the ViewController's
* `dismiss` method. Additionally, you can dismiss any overlay by using `pop`
* on the root nav controller.
*
* Data can be passed to a new modal through `Modal.create()` as the second
* argument. The data can then be accessed from the opened page by injecting
* `NavParams`. Note that the page, which opened as a modal, has no special
* "modal" logic within it, but uses `NavParams` no differently than a
* standard page.
*
* @usage
* ```ts
* import {Page, Modal, NavController, NavParams} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(params: NavParams) {
* console.log('UserId', params.get('userId'));
* }
*
* }
* ```
*
* A modal can also emit data, which is useful when it is used to add or edit
* data. For example, a profile page could slide up in a modal, and on submit,
* the submit button could pass the updated profile data, then dismiss the
* modal.
*
* ```ts
* import {Page, Modal, NavController, ViewController} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentContactModal() {
* let contactModal = Modal.create(ContactUs);
* this.nav.present(contactModal);
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* profileModal.onDismiss(data => {
* console.log(data);
* });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(viewCtrl: ViewController) {
* this.viewCtrl = viewCtrl;
* }
*
* dismiss() {
* let data = { 'foo': 'bar' };
* this.viewCtrl.dismiss(data);
* }
*
* }
* ```
* @demo /docs/v2/demos/modal/
* @see {@link /docs/v2/components#modals Modal Component Docs}
*/
export class Modal extends ViewController {
public modalViewType: string;
constructor(componentType, data: any = {}) {
data.componentType = componentType;
super(ModalCmp, data);
this.modalViewType = componentType.name;
this.viewType = 'modal';
this.isOverlay = true;
}
/**
* @private
*/
getTransitionName(direction) {
let key = (direction === 'back' ? 'modalLeave' : 'modalEnter');
return this._nav && this._nav.config.get(key);
}
/**
* @param {any} componentType Modal
* @param {object} data Modal options
*/
static create(componentType, data = {}) {
return new Modal(componentType, data);
}
// Override the load method and load our child component
loaded(done) {
// grab the instance, and proxy the ngAfterViewInit method
let originalNgAfterViewInit = this.instance.ngAfterViewInit;
this.instance.ngAfterViewInit = () => {
if ( originalNgAfterViewInit ) {
originalNgAfterViewInit();
}
this.instance.loadComponent().then( (componentRef: ComponentRef<any>) => {
this.setInstance(componentRef.instance);
done();
});
};
}
}
@Component({
selector: 'ion-modal',
template:
'<div class="backdrop"></div>' +
'<div class="modal-wrapper">' +
'<div #viewport></div>' +
'</div>'
})
export class ModalCmp {
@ViewChild('viewport', {read: ViewContainerRef}) viewport: ViewContainerRef;
constructor(protected _eleRef: ElementRef, protected _loader: DynamicComponentLoader, protected _navParams: NavParams, protected _viewCtrl: ViewController) {
}
loadComponent(): Promise<ComponentRef<any>> {
return this._loader.loadNextToLocation(this._navParams.data.componentType, this.viewport).then(componentRef => {
return componentRef;
});
}
ngAfterViewInit() {
// intentionally kept empty
}
}
/**
* Animations for modals
*/
class ModalSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
wrapper.fromTo('translateY', '100%', '0%');
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapperEle = <HTMLElement> ele.querySelector('.modal-wrapper');
let wrapperEleRect = wrapperEle.getBoundingClientRect();
let wrapper = new Animation(wrapperEle);
// height of the screen - top of the container tells us how much to scoot it down
// so it's off-screen
let screenDimensions = windowDimensions();
wrapper.fromTo('translateY', '0px', `${screenDimensions.height - wrapperEleRect.top}px`);
this
.element(leavingView.pageRef())
.easing('ease-out')
.duration(250)
.add(backdrop)
.add(wrapper);
}
}
Transition.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '40px', '0px');
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fadeIn()
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '0px', '40px');
this
.element(leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fadeOut()
.add(wrapper)
.add(backdrop);
}
}
Transition.register('modal-md-slide-out', ModalMDSlideOut);
| src/components/modal/modal.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9986088871955872,
0.1573803573846817,
0.00016029694234021008,
0.00018887956684920937,
0.35422906279563904
] |
{
"id": 5,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" wrapper.fromTo('translateY', '40px', '0px');\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 255
} | import {App} from '../../../../../src';
@App({
templateUrl: 'main.html'
})
class E2EApp {}
| src/components/input/test/placeholder-labels/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00016767176566645503,
0.00016767176566645503,
0.00016767176566645503,
0.00016767176566645503,
0
] |
{
"id": 5,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" wrapper.fromTo('translateY', '40px', '0px');\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 255
} | @import "../../globals.core";
// Toast
// --------------------------------------------------
$toast-width: 100% !default;
$toast-max-width: 700px !default;
ion-toast {
position: absolute;
top: 0;
left: 0;
z-index: $z-index-overlay;
display: block;
width: $toast-width;
height: $toast-width;
pointer-events: none;
}
.toast-container {
display: flex;
align-items: center;
pointer-events: auto;
}
.toast-button {
padding: 19px 16px 17px;
font-size: 1.5rem;
}
.toast-message {
flex: 1;
}
.toast-wrapper {
position: absolute;
right: 0;
bottom: 0;
left: 0;
z-index: $z-index-overlay-wrapper;
display: block;
margin: auto;
max-width: $toast-max-width;
transform: translate3d(0, 100%, 0);
}
| src/components/toast/toast.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017418204515706748,
0.00016900256741791964,
0.00016163931286428124,
0.00016943927039392292,
0.000003919551090802997
] |
{
"id": 5,
"code_window": [
" backdrop.fromTo('opacity', 0.01, 0.4);\n",
" let wrapper = new Animation(ele.querySelector('.modal-wrapper'));\n",
" wrapper.fromTo('translateY', '40px', '0px');\n",
" let page = <HTMLElement> ele.querySelector('ion-page');\n",
" page.classList.add('show-page');\n",
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 255
} | import {App} from '../../../../../src';
@App({
templateUrl: 'main.html'
})
class E2EApp {
constructor() {
this.groups = [];
var letters = "abcdefghijklmnopqrstuvwxyz".split('');
for(let i = 0; i < letters.length; i++) {
let group = [];
for(let j = 0; j < 10; j++) {
group.push({
title: letters[i] + j
});
}
this.groups.push({
title: letters[i].toUpperCase(),
items: group
});
}
}
}
| src/components/list/test/sticky/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017388917331118137,
0.0001718886778689921,
0.00016806568601168692,
0.0001737111888360232,
0.000002704243343032431
] |
{
"id": 6,
"code_window": [
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(280)\n",
" .fadeIn()\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n",
" enteringNavBar.before.addClass('show-navbar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const DURATION = 280;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).fadeIn().add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 261
} | import {Component, ComponentRef, DynamicComponentLoader, ElementRef, ViewChild, ViewContainerRef} from '@angular/core';
import {windowDimensions} from '../../util/dom';
import {pascalCaseToDashCase} from '../../util/util';
import {NavParams} from '../nav/nav-params';
import {ViewController} from '../nav/view-controller';
import {Animation} from '../../animations/animation';
import {Transition, TransitionOptions} from '../../transitions/transition';
/**
* @name Modal
* @description
* A Modal is a content pane that goes over the user's current page.
* Usually it is used for making a choice or editing an item. A modal uses the
* `NavController` to
* {@link /docs/v2/api/components/nav/NavController/#present present}
* itself in the root nav stack. It is added to the stack similar to how
* {@link /docs/v2/api/components/nav/NavController/#push NavController.push}
* works.
*
* When a modal (or any other overlay such as an alert or actionsheet) is
* "presented" to a nav controller, the overlay is added to the app's root nav.
* After the modal has been presented, from within the component instance The
* modal can later be closed or "dismissed" by using the ViewController's
* `dismiss` method. Additionally, you can dismiss any overlay by using `pop`
* on the root nav controller.
*
* Data can be passed to a new modal through `Modal.create()` as the second
* argument. The data can then be accessed from the opened page by injecting
* `NavParams`. Note that the page, which opened as a modal, has no special
* "modal" logic within it, but uses `NavParams` no differently than a
* standard page.
*
* @usage
* ```ts
* import {Page, Modal, NavController, NavParams} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(params: NavParams) {
* console.log('UserId', params.get('userId'));
* }
*
* }
* ```
*
* A modal can also emit data, which is useful when it is used to add or edit
* data. For example, a profile page could slide up in a modal, and on submit,
* the submit button could pass the updated profile data, then dismiss the
* modal.
*
* ```ts
* import {Page, Modal, NavController, ViewController} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentContactModal() {
* let contactModal = Modal.create(ContactUs);
* this.nav.present(contactModal);
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* profileModal.onDismiss(data => {
* console.log(data);
* });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(viewCtrl: ViewController) {
* this.viewCtrl = viewCtrl;
* }
*
* dismiss() {
* let data = { 'foo': 'bar' };
* this.viewCtrl.dismiss(data);
* }
*
* }
* ```
* @demo /docs/v2/demos/modal/
* @see {@link /docs/v2/components#modals Modal Component Docs}
*/
export class Modal extends ViewController {
public modalViewType: string;
constructor(componentType, data: any = {}) {
data.componentType = componentType;
super(ModalCmp, data);
this.modalViewType = componentType.name;
this.viewType = 'modal';
this.isOverlay = true;
}
/**
* @private
*/
getTransitionName(direction) {
let key = (direction === 'back' ? 'modalLeave' : 'modalEnter');
return this._nav && this._nav.config.get(key);
}
/**
* @param {any} componentType Modal
* @param {object} data Modal options
*/
static create(componentType, data = {}) {
return new Modal(componentType, data);
}
// Override the load method and load our child component
loaded(done) {
// grab the instance, and proxy the ngAfterViewInit method
let originalNgAfterViewInit = this.instance.ngAfterViewInit;
this.instance.ngAfterViewInit = () => {
if ( originalNgAfterViewInit ) {
originalNgAfterViewInit();
}
this.instance.loadComponent().then( (componentRef: ComponentRef<any>) => {
this.setInstance(componentRef.instance);
done();
});
};
}
}
@Component({
selector: 'ion-modal',
template:
'<div class="backdrop"></div>' +
'<div class="modal-wrapper">' +
'<div #viewport></div>' +
'</div>'
})
export class ModalCmp {
@ViewChild('viewport', {read: ViewContainerRef}) viewport: ViewContainerRef;
constructor(protected _eleRef: ElementRef, protected _loader: DynamicComponentLoader, protected _navParams: NavParams, protected _viewCtrl: ViewController) {
}
loadComponent(): Promise<ComponentRef<any>> {
return this._loader.loadNextToLocation(this._navParams.data.componentType, this.viewport).then(componentRef => {
return componentRef;
});
}
ngAfterViewInit() {
// intentionally kept empty
}
}
/**
* Animations for modals
*/
class ModalSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
wrapper.fromTo('translateY', '100%', '0%');
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapperEle = <HTMLElement> ele.querySelector('.modal-wrapper');
let wrapperEleRect = wrapperEle.getBoundingClientRect();
let wrapper = new Animation(wrapperEle);
// height of the screen - top of the container tells us how much to scoot it down
// so it's off-screen
let screenDimensions = windowDimensions();
wrapper.fromTo('translateY', '0px', `${screenDimensions.height - wrapperEleRect.top}px`);
this
.element(leavingView.pageRef())
.easing('ease-out')
.duration(250)
.add(backdrop)
.add(wrapper);
}
}
Transition.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '40px', '0px');
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fadeIn()
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '0px', '40px');
this
.element(leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fadeOut()
.add(wrapper)
.add(backdrop);
}
}
Transition.register('modal-md-slide-out', ModalMDSlideOut);
| src/components/modal/modal.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9981352090835571,
0.13299418985843658,
0.00015950972738210112,
0.00020820841018576175,
0.33306142687797546
] |
{
"id": 6,
"code_window": [
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(280)\n",
" .fadeIn()\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n",
" enteringNavBar.before.addClass('show-navbar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const DURATION = 280;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).fadeIn().add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 261
} | import {Injectable, NgZone} from '@angular/core';
import {IonicApp} from '../app/app';
import {Config} from '../../config/config';
import {pointerCoord, hasPointerMoved} from '../../util/dom';
import {Activator} from './activator';
import {RippleActivator} from './ripple';
/**
* @private
*/
@Injectable()
export class TapClick {
private lastTouch: number = 0;
private disableClick: number = 0;
private lastActivated: number = 0;
private usePolyfill: boolean;
private activator: Activator;
private startCoord: any;
private pointerMove: any;
constructor(
config: Config,
private app: IonicApp,
private zone: NgZone
) {
let self = this;
if (config.get('activator') === 'ripple') {
self.activator = new RippleActivator(app, config, zone);
} else if (config.get('activator') === 'highlight') {
self.activator = new Activator(app, config, zone);
}
self.usePolyfill = (config.get('tapPolyfill') === true);
zone.runOutsideAngular(() => {
addListener('click', self.click.bind(self), true);
addListener('touchstart', self.touchStart.bind(self));
addListener('touchend', self.touchEnd.bind(self));
addListener('touchcancel', self.pointerCancel.bind(self));
addListener('mousedown', self.mouseDown.bind(self), true);
addListener('mouseup', self.mouseUp.bind(self), true);
});
self.pointerMove = function(ev) {
if ( hasPointerMoved(POINTER_MOVE_UNTIL_CANCEL, self.startCoord, pointerCoord(ev)) ) {
self.pointerCancel(ev);
}
};
}
touchStart(ev) {
this.lastTouch = Date.now();
this.pointerStart(ev);
}
touchEnd(ev) {
this.lastTouch = Date.now();
if (this.usePolyfill && this.startCoord && this.app.isEnabled()) {
// only dispatch mouse click events from a touchend event
// when tapPolyfill config is true, and the startCoordand endCoord
// are not too far off from each other
let endCoord = pointerCoord(ev);
if (!hasPointerMoved(POINTER_TOLERANCE, this.startCoord, endCoord)) {
// prevent native mouse click events for XX amount of time
this.disableClick = this.lastTouch + DISABLE_NATIVE_CLICK_AMOUNT;
if (this.app.isScrolling()) {
// do not fire off a click event while the app was scrolling
console.debug('click from touch prevented by scrolling ' + Date.now());
} else {
// dispatch a mouse click event
console.debug('create click from touch ' + Date.now());
let clickEvent: any = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, window, 1, 0, 0, endCoord.x, endCoord.y, false, false, false, false, 0, null);
clickEvent.isIonicTap = true;
ev.target.dispatchEvent(clickEvent);
}
}
}
this.pointerEnd(ev);
}
mouseDown(ev) {
if (this.isDisabledNativeClick()) {
console.debug('mouseDown prevent ' + ev.target.tagName + ' ' + Date.now());
// does not prevent default on purpose
// so native blur events from inputs can happen
ev.stopPropagation();
} else if (this.lastTouch + DISABLE_NATIVE_CLICK_AMOUNT < Date.now()) {
this.pointerStart(ev);
}
}
mouseUp(ev) {
if (this.isDisabledNativeClick()) {
console.debug('mouseUp prevent ' + ev.target.tagName + ' ' + Date.now());
ev.preventDefault();
ev.stopPropagation();
}
if (this.lastTouch + DISABLE_NATIVE_CLICK_AMOUNT < Date.now()) {
this.pointerEnd(ev);
}
}
pointerStart(ev) {
let activatableEle = getActivatableTarget(ev.target);
if (activatableEle) {
this.startCoord = pointerCoord(ev);
let now = Date.now();
if (this.lastActivated + 150 < now) {
this.activator && this.activator.downAction(ev, activatableEle, this.startCoord.x, this.startCoord.y);
this.lastActivated = now;
}
this.moveListeners(true);
} else {
this.startCoord = null;
}
}
pointerEnd(ev) {
let activatableEle = getActivatableTarget(ev.target);
if (activatableEle && this.startCoord) {
this.activator && this.activator.upAction(ev, activatableEle, this.startCoord.x, this.startCoord.y);
}
this.moveListeners(false);
}
pointerCancel(ev) {
console.debug('pointerCancel from ' + ev.type + ' ' + Date.now());
this.activator && this.activator.clearState();
this.moveListeners(false);
}
moveListeners(shouldAdd) {
removeListener(this.usePolyfill ? 'touchmove' : 'mousemove', this.pointerMove);
if (shouldAdd) {
addListener(this.usePolyfill ? 'touchmove' : 'mousemove', this.pointerMove);
}
}
click(ev: any) {
let preventReason = null;
if (!this.app.isEnabled()) {
preventReason = 'appDisabled';
} else if (!ev.isIonicTap && this.isDisabledNativeClick()) {
preventReason = 'nativeClick';
}
if (preventReason !== null) {
console.debug('click prevent ' + preventReason + ' ' + Date.now());
ev.preventDefault();
ev.stopPropagation();
}
}
isDisabledNativeClick() {
return this.disableClick > Date.now();
}
}
function getActivatableTarget(ele) {
let targetEle = ele;
for (let x = 0; x < 4; x++) {
if (!targetEle) break;
if (isActivatable(targetEle)) return targetEle;
targetEle = targetEle.parentElement;
}
return null;
}
/**
* @private
*/
export function isActivatable(ele) {
if (ACTIVATABLE_ELEMENTS.test(ele.tagName)) {
return true;
}
let attributes = ele.attributes;
for (let i = 0, l = attributes.length; i < l; i++) {
if (ACTIVATABLE_ATTRIBUTES.test(attributes[i].name)) {
return true;
}
}
return false;
}
function addListener(type, listener, useCapture?) {
document.addEventListener(type, listener, useCapture);
}
function removeListener(type, listener) {
document.removeEventListener(type, listener);
}
const ACTIVATABLE_ELEMENTS = /^(A|BUTTON)$/;
const ACTIVATABLE_ATTRIBUTES = /tappable|button/i;
const POINTER_TOLERANCE = 4;
const POINTER_MOVE_UNTIL_CANCEL = 10;
const DISABLE_NATIVE_CLICK_AMOUNT = 2500;
| src/components/tap-click/tap-click.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.000169191844179295,
0.00016559050709474832,
0.00016120896907523274,
0.0001658405235502869,
0.000002160871417800081
] |
{
"id": 6,
"code_window": [
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(280)\n",
" .fadeIn()\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n",
" enteringNavBar.before.addClass('show-navbar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const DURATION = 280;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).fadeIn().add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 261
} | import {Gesture} from './gesture';
import {defaults} from '../util';
export class DragGesture extends Gesture {
public dragging: boolean;
constructor(element, opts = {}) {
defaults(opts, {});
super(element, opts);
}
listen() {
super.listen();
this.on('panstart', ev => {
if (this.onDragStart(ev) !== false) {
this.dragging = true;
}
});
this.on('panmove', ev => {
if (!this.dragging) return;
if (this.onDrag(ev) === false) {
this.dragging = false;
}
});
this.on('panend', ev => {
if (!this.dragging) return;
this.onDragEnd(ev);
this.dragging = false;
});
}
onDrag(ev: any): boolean { return true; }
onDragStart(ev: any): boolean { return true; }
onDragEnd(ev: any): void {}
}
| src/gestures/drag-gesture.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.0001664513983996585,
0.00016565332771278918,
0.00016488235269207507,
0.0001656397944316268,
6.388794986378343e-7
] |
{
"id": 6,
"code_window": [
"\n",
" // auto-add page css className created from component JS class name\n",
" let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);\n",
" page.classList.add(cssClassName);\n",
"\n",
" this\n",
" .element(enteringView.pageRef())\n",
" .easing('cubic-bezier(0.36,0.66,0.04,1)')\n",
" .duration(280)\n",
" .fadeIn()\n",
" .before.addClass('show-page')\n",
" .add(backdrop)\n",
" .add(wrapper);\n",
"\n",
" if (enteringView.hasNavbar()) {\n",
" // entering page has a navbar\n",
" let enteringNavBar = new Animation(enteringView.navbarRef());\n",
" enteringNavBar.before.addClass('show-navbar');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const DURATION = 280;\n",
" const EASING = 'cubic-bezier(0.36,0.66,0.04,1)';\n",
" this.element(enteringView.pageRef()).easing(EASING).duration(DURATION).fadeIn().add(backdrop).add(wrapper);\n",
" this.element(new ElementRef(page)).easing(EASING).duration(DURATION).before.addClass('show-page');\n"
],
"file_path": "src/components/modal/modal.ts",
"type": "replace",
"edit_start_line_idx": 261
} | import {Component, ChangeDetectionStrategy, ViewEncapsulation, Type} from '@angular/core';
const _reflect: any = Reflect;
export interface PageMetadata {
selector?: string;
inputs?: string[];
outputs?: string[];
properties?: string[];
events?: string[];
host?: {
[key: string]: string;
};
providers?: any[];
directives?: Array<Type | any[]>;
pipes?: Array<Type | any[]>;
exportAs?: string;
queries?: {
[key: string]: any;
};
template?: string;
templateUrl?: string;
moduleId?: string;
styleUrls?: string[];
styles?: string[];
changeDetection?: ChangeDetectionStrategy;
encapsulation?: ViewEncapsulation;
}
/**
* @name Page
* @description
*
* The Page decorator indicates that the decorated class is an Ionic
* navigation component, meaning it can be navigated to using a
* [NavController](../../nav/NavController).
*
* Since the app has already been bootstrapped with Ionic's core directives, it
* is not needed to include `IONIC_DIRECTIVES` in the directives property. Additionally,
* Angular's [CORE_DIRECTIVES](https://angular.io/docs/ts/latest/api/common/CORE_DIRECTIVES-let.html)
* and [FORM_DIRECTIVES](https://angular.io/docs/ts/latest/api/common/FORM_DIRECTIVES-let.html),
* are also already provided, so you only need to supply any custom components and directives
* to your pages:
*
* @usage
*
* ```ts
* @Page({
* template: `
* <ion-content>
* I am a page!
* </ion-content>
* `
* })
* class MyPage {}
* ```
*
* Pages have their content automatically wrapped in `<ion-page>`, so although
* you may see these tags if you inspect your markup, you don't need to include
* them in your templates.
*
* For more information on how pages are created, see the [NavController API Docs](../../components/nav/NavController/#creating_pages)
*/
export function Page(config: PageMetadata) {
return function(cls) {
config.selector = 'ion-page';
config.host = config.host || {};
config.host['[hidden]'] = '_hidden';
config.host['[class.tab-subpage]'] = '_tabSubPage';
var annotations = _reflect.getMetadata('annotations', cls) || [];
annotations.push(new Component(config));
_reflect.defineMetadata('annotations', annotations, cls);
return cls;
};
}
| src/decorators/page.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.001227906090207398,
0.0002970407949760556,
0.00015893735690042377,
0.00016478548059239984,
0.00035184939042665064
] |
{
"id": 7,
"code_window": [
"// Windows Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-wp-background-color: $background-wp-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-wp-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.wp.scss",
"type": "replace",
"edit_start_line_idx": 6
} | import {Component, ComponentRef, DynamicComponentLoader, ElementRef, ViewChild, ViewContainerRef} from '@angular/core';
import {windowDimensions} from '../../util/dom';
import {pascalCaseToDashCase} from '../../util/util';
import {NavParams} from '../nav/nav-params';
import {ViewController} from '../nav/view-controller';
import {Animation} from '../../animations/animation';
import {Transition, TransitionOptions} from '../../transitions/transition';
/**
* @name Modal
* @description
* A Modal is a content pane that goes over the user's current page.
* Usually it is used for making a choice or editing an item. A modal uses the
* `NavController` to
* {@link /docs/v2/api/components/nav/NavController/#present present}
* itself in the root nav stack. It is added to the stack similar to how
* {@link /docs/v2/api/components/nav/NavController/#push NavController.push}
* works.
*
* When a modal (or any other overlay such as an alert or actionsheet) is
* "presented" to a nav controller, the overlay is added to the app's root nav.
* After the modal has been presented, from within the component instance The
* modal can later be closed or "dismissed" by using the ViewController's
* `dismiss` method. Additionally, you can dismiss any overlay by using `pop`
* on the root nav controller.
*
* Data can be passed to a new modal through `Modal.create()` as the second
* argument. The data can then be accessed from the opened page by injecting
* `NavParams`. Note that the page, which opened as a modal, has no special
* "modal" logic within it, but uses `NavParams` no differently than a
* standard page.
*
* @usage
* ```ts
* import {Page, Modal, NavController, NavParams} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(params: NavParams) {
* console.log('UserId', params.get('userId'));
* }
*
* }
* ```
*
* A modal can also emit data, which is useful when it is used to add or edit
* data. For example, a profile page could slide up in a modal, and on submit,
* the submit button could pass the updated profile data, then dismiss the
* modal.
*
* ```ts
* import {Page, Modal, NavController, ViewController} from 'ionic-angular';
*
* @Page(...)
* class HomePage {
*
* constructor(nav: NavController) {
* this.nav = nav;
* }
*
* presentContactModal() {
* let contactModal = Modal.create(ContactUs);
* this.nav.present(contactModal);
* }
*
* presentProfileModal() {
* let profileModal = Modal.create(Profile, { userId: 8675309 });
* profileModal.onDismiss(data => {
* console.log(data);
* });
* this.nav.present(profileModal);
* }
*
* }
*
* @Page(...)
* class Profile {
*
* constructor(viewCtrl: ViewController) {
* this.viewCtrl = viewCtrl;
* }
*
* dismiss() {
* let data = { 'foo': 'bar' };
* this.viewCtrl.dismiss(data);
* }
*
* }
* ```
* @demo /docs/v2/demos/modal/
* @see {@link /docs/v2/components#modals Modal Component Docs}
*/
export class Modal extends ViewController {
public modalViewType: string;
constructor(componentType, data: any = {}) {
data.componentType = componentType;
super(ModalCmp, data);
this.modalViewType = componentType.name;
this.viewType = 'modal';
this.isOverlay = true;
}
/**
* @private
*/
getTransitionName(direction) {
let key = (direction === 'back' ? 'modalLeave' : 'modalEnter');
return this._nav && this._nav.config.get(key);
}
/**
* @param {any} componentType Modal
* @param {object} data Modal options
*/
static create(componentType, data = {}) {
return new Modal(componentType, data);
}
// Override the load method and load our child component
loaded(done) {
// grab the instance, and proxy the ngAfterViewInit method
let originalNgAfterViewInit = this.instance.ngAfterViewInit;
this.instance.ngAfterViewInit = () => {
if ( originalNgAfterViewInit ) {
originalNgAfterViewInit();
}
this.instance.loadComponent().then( (componentRef: ComponentRef<any>) => {
this.setInstance(componentRef.instance);
done();
});
};
}
}
@Component({
selector: 'ion-modal',
template:
'<div class="backdrop"></div>' +
'<div class="modal-wrapper">' +
'<div #viewport></div>' +
'</div>'
})
export class ModalCmp {
@ViewChild('viewport', {read: ViewContainerRef}) viewport: ViewContainerRef;
constructor(protected _eleRef: ElementRef, protected _loader: DynamicComponentLoader, protected _navParams: NavParams, protected _viewCtrl: ViewController) {
}
loadComponent(): Promise<ComponentRef<any>> {
return this._loader.loadNextToLocation(this._navParams.data.componentType, this.viewport).then(componentRef => {
return componentRef;
});
}
ngAfterViewInit() {
// intentionally kept empty
}
}
/**
* Animations for modals
*/
class ModalSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
wrapper.fromTo('translateY', '100%', '0%');
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(400)
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-slide-in', ModalSlideIn);
class ModalSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapperEle = <HTMLElement> ele.querySelector('.modal-wrapper');
let wrapperEleRect = wrapperEle.getBoundingClientRect();
let wrapper = new Animation(wrapperEle);
// height of the screen - top of the container tells us how much to scoot it down
// so it's off-screen
let screenDimensions = windowDimensions();
wrapper.fromTo('translateY', '0px', `${screenDimensions.height - wrapperEleRect.top}px`);
this
.element(leavingView.pageRef())
.easing('ease-out')
.duration(250)
.add(backdrop)
.add(wrapper);
}
}
Transition.register('modal-slide-out', ModalSlideOut);
class ModalMDSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = enteringView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.01, 0.4);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '40px', '0px');
let page = <HTMLElement> ele.querySelector('ion-page');
page.classList.add('show-page');
// auto-add page css className created from component JS class name
let cssClassName = pascalCaseToDashCase((<Modal>enteringView).modalViewType);
page.classList.add(cssClassName);
this
.element(enteringView.pageRef())
.easing('cubic-bezier(0.36,0.66,0.04,1)')
.duration(280)
.fadeIn()
.before.addClass('show-page')
.add(backdrop)
.add(wrapper);
if (enteringView.hasNavbar()) {
// entering page has a navbar
let enteringNavBar = new Animation(enteringView.navbarRef());
enteringNavBar.before.addClass('show-navbar');
this.add(enteringNavBar);
}
}
}
Transition.register('modal-md-slide-in', ModalMDSlideIn);
class ModalMDSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(opts);
let ele = leavingView.pageRef().nativeElement;
let backdrop = new Animation(ele.querySelector('.backdrop'));
backdrop.fromTo('opacity', 0.4, 0.0);
let wrapper = new Animation(ele.querySelector('.modal-wrapper'));
wrapper.fromTo('translateY', '0px', '40px');
this
.element(leavingView.pageRef())
.duration(200)
.easing('cubic-bezier(0.47,0,0.745,0.715)')
.fadeOut()
.add(wrapper)
.add(backdrop);
}
}
Transition.register('modal-md-slide-out', ModalMDSlideOut);
| src/components/modal/modal.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9393662214279175,
0.03496155887842178,
0.0001652369392104447,
0.00019644976418931037,
0.1663537174463272
] |
{
"id": 7,
"code_window": [
"// Windows Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-wp-background-color: $background-wp-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-wp-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.wp.scss",
"type": "replace",
"edit_start_line_idx": 6
} | @import "../../globals.core";
// Z-Index
// --------------------------------------------------
// Grouped by elements which would be siblings
$z-index-menu-overlay: 80;
$z-index-menu-backdrop: 79;
$z-index-overlay: 1000;
$z-index-click-block: 9999;
$z-index-fixed-content: 2;
$z-index-scroll-content: 1;
$z-index-refresher: 0;
$z-index-navbar-section: 10;
$z-index-toolbar: 10;
$z-index-toolbar-background: -1;
$z-index-toolbar-border: 20;
$z-index-list-border: 50;
$z-index-backdrop: 2;
$z-index-overlay-wrapper: 10;
$z-index-item-options: 1;
// Flex Order
// --------------------------------------------------
$flex-order-toolbar-top: -10;
$flex-order-toolbar-bottom: 10;
$flex-order-tabbar-navbar: -30;
$flex-order-tabbar-top: -20;
$flex-order-tabbar-bottom: 20;
// App Structure
// --------------------------------------------------
* {
box-sizing: border-box;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
}
html {
width: 100%;
height: 100%;
text-size-adjust: 100%;
}
body {
@include user-select-none();
position: fixed;
overflow: hidden;
margin: 0;
padding: 0;
width: 100%;
max-width: 100%;
height: 100%;
max-height: 100%;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-rendering: optimizeLegibility;
-webkit-user-drag: none;
-ms-content-zooming: none;
touch-action: manipulation;
word-wrap: break-word;
text-size-adjust: none;
}
ion-app,
ion-nav,
ion-tabs {
position: absolute;
top: 0;
left: 0;
display: flex;
overflow: hidden;
flex-direction: column;
width: 100%;
height: 100%;
}
ion-navbar-section {
display: block;
width: 100%;
min-height: 50px;
}
ion-content-section {
position: relative;
display: block;
flex: 1;
width: 100%;
height: 100%;
}
ion-page {
position: absolute;
top: 0;
left: 0;
display: none;
flex-direction: column;
width: 100%;
height: 100%;
&.show-page {
display: flex;
}
}
ion-content {
position: relative;
display: block;
flex: 1;
width: 100%;
height: 100%;
}
scroll-content {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: $z-index-scroll-content;
display: block;
overflow-x: hidden;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
will-change: scroll-position;
}
ion-content.js-scroll > scroll-content {
position: relative;
min-height: 100%;
overflow-x: initial;
overflow-y: initial;
-webkit-overflow-scrolling: auto;
will-change: initial;
}
ion-tabbar {
position: absolute;
top: 0;
left: 0;
display: block;
width: 100%;
min-height: 50px;
}
ion-tab-section {
position: relative;
top: 0;
left: 0;
display: block;
overflow: hidden;
width: 100%;
height: 100%;
}
ion-page.tab-subpage {
position: fixed;
z-index: 10;
}
ion-navbar {
position: absolute;
top: 0;
left: 0;
z-index: $z-index-navbar-section;
display: block;
width: 100%;
min-height: 50px;
}
ion-navbar-section ion-navbar.toolbar {
position: absolute;
}
ion-toolbar {
display: block;
width: 100%;
}
ion-toolbar[position=bottom] {
bottom: 0;
z-index: $z-index-toolbar;
}
.sticky {
position: sticky;
top: 0;
}
| src/components/app/structure.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00020270264940336347,
0.00017248197400476784,
0.00016338210843969136,
0.0001706677721813321,
0.000008829056241665967
] |
{
"id": 7,
"code_window": [
"// Windows Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-wp-background-color: $background-wp-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-wp-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.wp.scss",
"type": "replace",
"edit_start_line_idx": 6
} | <ion-tabs>
<% _.forEach(tabs, function(tab, i) { %>
<ion-tab [root]="tab<%= ++i %>Root" tabTitle="<%= tab.name %>" tabIcon="star"></ion-tab>
<% }); %>
</ion-tabs>
| tooling/generators/tabs/tabs.tmpl.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00019434187561273575,
0.00019434187561273575,
0.00019434187561273575,
0.00019434187561273575,
0
] |
{
"id": 7,
"code_window": [
"// Windows Modals\n",
"// --------------------------------------------------\n",
"\n",
"$modal-wp-background-color: $background-wp-color !default;\n",
"\n",
"\n",
".modal-wrapper {\n",
" background-color: $modal-wp-background-color;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "src/components/modal/modal.wp.scss",
"type": "replace",
"edit_start_line_idx": 6
} | <ion-menu [content]="content" id="menu1">
<ion-toolbar secondary>
<ion-title>Menu 1</ion-title>
</ion-toolbar>
<ion-content>
<ion-list>
<button ion-item menuClose="menu1" detail-none>
Close Menu 1
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-menu [content]="content" id="menu2">
<ion-toolbar danger>
<ion-title>Menu 2</ion-title>
</ion-toolbar>
<ion-content>
<ion-list>
<button ion-item menuClose="menu2" detail-none>
Close Menu 2
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav id="nav" [root]="rootView" #content swipeBackEnabled="false"></ion-nav>
| demos/id/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017257797298952937,
0.00017034015036188066,
0.00016822328325361013,
0.00017027967260219157,
0.0000021085045318613993
] |
{
"id": 8,
"code_window": [
"import {Output, EventEmitter, Type, TemplateRef, ViewContainerRef, ElementRef, Renderer, ChangeDetectorRef} from '@angular/core';\n",
"\n",
"import {Navbar} from '../navbar/navbar';\n",
"import {NavController, NavOptions} from './nav-controller';\n",
"import {NavParams} from './nav-params';\n",
"import {isPresent} from '../../util/util';\n",
"\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {isPresent, merge} from '../../util/util';\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 5
} | import {Output, EventEmitter, Type, TemplateRef, ViewContainerRef, ElementRef, Renderer, ChangeDetectorRef} from '@angular/core';
import {Navbar} from '../navbar/navbar';
import {NavController, NavOptions} from './nav-controller';
import {NavParams} from './nav-params';
import {isPresent} from '../../util/util';
/**
* @name ViewController
* @description
* Access various features and information about the current view.
* @usage
* ```ts
* import {Page, ViewController} from 'ionic-angular';
* @Page....
* export class MyPage{
* constructor(viewCtrl: ViewController){
* this.viewCtrl = viewCtrl;
* }
* }
* ```
*/
export class ViewController {
private _cntDir: any;
private _cntRef: ElementRef;
private _tbRefs: ElementRef[] = [];
private _destroys: Function[] = [];
private _hdAttr: string = null;
private _leavingOpts: NavOptions = null;
private _loaded: boolean = false;
private _nbDir: Navbar;
private _nbTmpRef: TemplateRef<Object>;
private _nbVwRef: ViewContainerRef;
private _onDismiss: Function = null;
private _pgRef: ElementRef;
private _cd: ChangeDetectorRef;
protected _nav: NavController;
didLoad: EventEmitter<any>;
willEnter: EventEmitter<any>;
didEnter: EventEmitter<any>;
willLeave: EventEmitter<any>;
didLeave: EventEmitter<any>;
willUnload: EventEmitter<any>;
didUnload: EventEmitter<any>;
/**
* @private
*/
data: any;
/**
* @private
*/
id: string;
/**
* @private
*/
instance: any = {};
/**
* @private
*/
state: string = '';
/**
* @private
*/
viewType: string = '';
/**
* @private
* If this is currently the active view, then set to false
* if it does not want the other views to fire their own lifecycles.
*/
fireOtherLifecycles: boolean = true;
/**
* @private
*/
isOverlay: boolean = false;
/**
* @private
*/
usePortal: boolean = false;
/**
* @private
*/
zIndex: number;
/**
* @private
*/
@Output() private _emitter: EventEmitter<any> = new EventEmitter();
constructor(public componentType?: Type, data?: any) {
// passed in data could be NavParams, but all we care about is its data object
this.data = (data instanceof NavParams ? data.data : (isPresent(data) ? data : {}));
this.didLoad = new EventEmitter();
this.willEnter = new EventEmitter();
this.didEnter = new EventEmitter();
this.willLeave = new EventEmitter();
this.didLeave = new EventEmitter();
this.willUnload = new EventEmitter();
this.didUnload = new EventEmitter();
}
subscribe(generatorOrNext?: any): any {
return this._emitter.subscribe(generatorOrNext);
}
/**
* @private
*/
emit(data?: any) {
this._emitter.emit(data);
}
onDismiss(callback: Function) {
this._onDismiss = callback;
}
dismiss(data?: any, role?: any) {
return this._nav.remove(this._nav.indexOf(this), 1, this._leavingOpts).then(() => {
this._onDismiss && this._onDismiss(data, role);
return data;
});
}
/**
* @private
*/
setNav(navCtrl: NavController) {
this._nav = navCtrl;
}
/**
* @private
*/
getTransitionName(direction: string): string {
return this._nav && this._nav.config.get('pageTransition');
}
/**
* @private
*/
getNavParams(): NavParams {
return new NavParams(this.data);
}
/**
* @private
*/
setLeavingOpts(opts: NavOptions) {
this._leavingOpts = opts;
}
/**
* Check to see if you can go back in the navigation stack.
* @param {boolean} Check whether or not you can go back from this page
* @returns {boolean} Returns if it's possible to go back from this Page.
*/
enableBack(): boolean {
// update if it's possible to go back from this nav item
if (this._nav) {
let previousItem = this._nav.getPrevious(this);
// the previous view may exist, but if it's about to be destroyed
// it shouldn't be able to go back to
return !!(previousItem);
}
return false;
}
/**
* @private
*/
setChangeDetector(cd: ChangeDetectorRef) {
this._cd = cd;
}
/**
* @private
*/
setInstance(instance: any) {
this.instance = instance;
}
/**
* @private
*/
get name(): string {
return this.componentType ? this.componentType['name'] : '';
}
/**
* You can find out the index of the current view is in the current navigation stack.
*
* ```typescript
* export class Page1 {
* constructor(view: ViewController){
* this.view = view;
* // Just log out the index
* console.log(this.view.index);
* }
* }
* ```
*
* @returns {number} Returns the index of this page within its NavController.
*/
get index(): number {
return (this._nav ? this._nav.indexOf(this) : -1);
}
/**
* @private
*/
private isRoot(): boolean {
// deprecated warning
console.warn('ViewController isRoot() has been renamed to isFirst()');
return this.isFirst();
}
/**
* @returns {boolean} Returns if this Page is the first in the stack of pages within its NavController.
*/
isFirst(): boolean {
return (this._nav ? this._nav.first() === this : false);
}
/**
* @returns {boolean} Returns if this Page is the last in the stack of pages within its NavController.
*/
isLast(): boolean {
return (this._nav ? this._nav.last() === this : false);
}
/**
* @private
*/
domShow(shouldShow: boolean, renderer: Renderer) {
// using hidden element attribute to display:none and not render views
// renderAttr of '' means the hidden attribute will be added
// renderAttr of null means the hidden attribute will be removed
// doing checks to make sure we only make an update to the element when needed
if (this._pgRef &&
(shouldShow && this._hdAttr === '' ||
!shouldShow && this._hdAttr !== '')) {
this._hdAttr = (shouldShow ? null : '');
renderer.setElementAttribute(this._pgRef.nativeElement, 'hidden', this._hdAttr);
let navbarRef = this.navbarRef();
if (navbarRef) {
renderer.setElementAttribute(navbarRef.nativeElement, 'hidden', this._hdAttr);
}
}
}
/**
* @private
*/
setZIndex(zIndex: number, renderer: Renderer) {
if (this._pgRef && zIndex !== this.zIndex) {
this.zIndex = zIndex;
renderer.setElementStyle(this._pgRef.nativeElement, 'z-index', zIndex.toString());
}
}
/**
* @private
*/
setNavbarTemplateRef(templateRef: TemplateRef<Object>) {
this._nbTmpRef = templateRef;
}
/**
* @private
*/
getNavbarTemplateRef(): TemplateRef<Object> {
return this._nbTmpRef;
}
/**
* @private
*/
getNavbarViewRef() {
return this._nbVwRef;
}
/**
* @private
*/
setNavbarViewRef(viewContainerRef: ViewContainerRef) {
this._nbVwRef = viewContainerRef;
}
/**
* @private
*/
setPageRef(elementRef: ElementRef) {
this._pgRef = elementRef;
}
/**
* @private
* @returns {elementRef} Returns the Page's ElementRef
*/
pageRef(): ElementRef {
return this._pgRef;
}
/**
* @private
*/
setContentRef(elementRef: ElementRef) {
this._cntRef = elementRef;
}
/**
* @private
* @returns {elementRef} Returns the Page's Content ElementRef
*/
contentRef(): ElementRef {
return this._cntRef;
}
/**
* @private
*/
setToolbarRef(elementRef: ElementRef) {
this._tbRefs.push(elementRef);
}
/**
* @private
* @returns {elementRef} Returns the Page's Content ElementRef
*/
toolbarRefs(): ElementRef[] {
return this._tbRefs;
}
/**
* @private
*/
setContent(directive) {
this._cntDir = directive;
}
/**
* @private
* @returns {component} Returns the Page's Content component reference.
*/
getContent() {
return this._cntDir;
}
/**
* @private
*/
setNavbar(directive: Navbar) {
this._nbDir = directive;
}
/**
* @private
*/
getNavbar() {
return this._nbDir;
}
/**
* You can find out of the current view has a Navbar or not. Be sure to wrap this in an `onPageWillEnter` method in order to make sure the view has rendered fully.
*
* ```typescript
* export class Page1 {
* constructor(view: ViewController) {
* this.view = view
* }
* onPageWillEnter(){
* console.log('Do we have a Navbar?', this.view.hasNavbar());
* }
*}
* ```
*
* @returns {boolean} Returns a boolean if this Page has a navbar or not.
*/
hasNavbar(): boolean {
return !!this.getNavbar();
}
/**
* @private
*/
navbarRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getElementRef();
}
/**
* @private
*/
titleRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getTitleRef();
}
/**
* @private
*/
navbarItemRefs(): Array<ElementRef> {
let navbar = this.getNavbar();
return navbar && navbar.getItemRefs();
}
/**
* @private
*/
backBtnRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getBackButtonRef();
}
/**
* @private
*/
backBtnTextRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getBackButtonTextRef();
}
/**
* @private
*/
navbarBgRef(): ElementRef {
let navbar = this.getNavbar();
return navbar && navbar.getBackgroundRef();
}
/**
* You can change the text of the back button on a view-by-view basis.
*
* ```ts
* export class MyClass{
* constructor(viewCtrl: ViewController){
* this.viewCtrl = viewCtrl
* }
* onPageWillEnter() {
* this.viewCtrl.setBackButtonText('Previous');
* }
* }
* ```
* Make sure you use the view events when calling this method, otherwise the back-button will not have been created
*
* @param {string} backButtonText Set the back button text.
*/
setBackButtonText(val: string) {
let navbar = this.getNavbar();
if (navbar) {
navbar.setBackButtonText(val);
}
}
/**
* Set if the back button for the current view is visible or not. Be sure to wrap this in `onPageWillEnter` to make sure the has been compleltly rendered.
* @param {boolean} Set if this Page's back button should show or not.
*/
showBackButton(shouldShow: boolean) {
let navbar = this.getNavbar();
if (navbar) {
navbar.hideBackButton = !shouldShow;
}
}
/**
* @private
*/
isLoaded(): boolean {
return this._loaded;
}
/**
* The loaded method is used to load any dynamic content/components
* into the dom before proceeding with the transition. If a component needs
* dynamic component loading, extending ViewController and overriding
* this method is a good option
* @param {function} done is a callback that must be called when async loading/actions are completed
*/
loaded(done: (() => any)) {
done();
}
/**
* @private
* The view has loaded. This event only happens once per view being
* created. If a view leaves but is cached, then this will not
* fire again on a subsequent viewing. This method is a good place
* to put your setup code for the view; however, it is not the
* recommended method to use when a view becomes active.
*/
fireLoaded() {
this._loaded = true;
this.didLoad.emit(null);
ctrlFn(this, 'onPageLoaded');
}
/**
* @private
* The view is about to enter and become the active view.
*/
fireWillEnter() {
if (this._cd) {
// ensure this has been re-attached to the change detector
this._cd.reattach();
// detect changes before we run any user code
this._cd.detectChanges();
}
this.willEnter.emit(null);
ctrlFn(this, 'onPageWillEnter');
}
/**
* @private
* The view has fully entered and is now the active view. This
* will fire, whether it was the first load or loaded from the cache.
*/
fireDidEnter() {
let navbar = this.getNavbar();
navbar && navbar.didEnter();
this.didEnter.emit(null);
ctrlFn(this, 'onPageDidEnter');
}
/**
* @private
* The view has is about to leave and no longer be the active view.
*/
fireWillLeave() {
this.willLeave.emit(null);
ctrlFn(this, 'onPageWillLeave');
}
/**
* @private
* The view has finished leaving and is no longer the active view. This
* will fire, whether it is cached or unloaded.
*/
fireDidLeave() {
this.didLeave.emit(null);
ctrlFn(this, 'onPageDidLeave');
// when this is not the active page
// we no longer need to detect changes
this._cd && this._cd.detach();
}
/**
* @private
* The view is about to be destroyed and have its elements removed.
*/
fireWillUnload() {
this.willUnload.emit(null);
ctrlFn(this, 'onPageWillUnload');
}
/**
* @private
*/
onDestroy(destroyFn: Function) {
this._destroys.push(destroyFn);
}
/**
* @private
*/
destroy() {
this.didUnload.emit(null);
ctrlFn(this, 'onPageDidUnload');
for (var i = 0; i < this._destroys.length; i++) {
this._destroys[i]();
}
this._destroys.length = 0;
this._tbRefs.length = 0;
}
}
export interface LifeCycleEvent {
componentType?: any;
}
function ctrlFn(viewCtrl: ViewController, fnName: string) {
if (viewCtrl.instance && viewCtrl.instance[fnName]) {
try {
viewCtrl.instance[fnName]();
} catch (e) {
console.error(viewCtrl.name + ' ' + fnName + ': ' + e.message);
}
}
}
| src/components/nav/view-controller.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9838760495185852,
0.01661166362464428,
0.00016349245561286807,
0.00017803195805754513,
0.1248759925365448
] |
{
"id": 8,
"code_window": [
"import {Output, EventEmitter, Type, TemplateRef, ViewContainerRef, ElementRef, Renderer, ChangeDetectorRef} from '@angular/core';\n",
"\n",
"import {Navbar} from '../navbar/navbar';\n",
"import {NavController, NavOptions} from './nav-controller';\n",
"import {NavParams} from './nav-params';\n",
"import {isPresent} from '../../util/util';\n",
"\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {isPresent, merge} from '../../util/util';\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 5
} | @import "../../globals.core";
// Windows Popover
// --------------------------------------------------
$popover-wp-width: 200px !default;
$popover-wp-max-height: 90% !default;
$popover-wp-border: 2px solid #ccc !default;
$popover-wp-border-radius: 0 !default;
$popover-wp-text-color: #000 !default;
$popover-wp-background: #f2f2f2 !default;
$popover-wp-item-background: $popover-wp-background !default;
.popover-content {
width: $popover-wp-width;
min-width: 0;
min-height: 0;
max-height: $popover-wp-max-height;
border: $popover-wp-border;
border-radius: $popover-wp-border-radius;
color: $popover-wp-text-color;
background: $popover-wp-background;
transform-origin: top left;
}
.popover-content .item {
background-color: $popover-wp-item-background;
}
.popover-viewport {
opacity: 0;
transition-delay: 100ms;
}
| src/components/popover/popover.wp.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017702968034427613,
0.00017559999832883477,
0.00017453168402425945,
0.00017541932174935937,
0.000001068812593985058
] |
{
"id": 8,
"code_window": [
"import {Output, EventEmitter, Type, TemplateRef, ViewContainerRef, ElementRef, Renderer, ChangeDetectorRef} from '@angular/core';\n",
"\n",
"import {Navbar} from '../navbar/navbar';\n",
"import {NavController, NavOptions} from './nav-controller';\n",
"import {NavParams} from './nav-params';\n",
"import {isPresent} from '../../util/util';\n",
"\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {isPresent, merge} from '../../util/util';\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 5
} | import {App, Page, ActionSheet, Alert, Modal, NavController, ViewController, Platform} from '../../../../../src';
@Page({
templateUrl: 'main.html'
})
class E2EPage {
result: string = '';
constructor(private nav: NavController, private platform: Platform) {}
presentActionSheet1() {
this.result = '';
let actionSheet = ActionSheet.create({
title: 'Albums',
buttons: [
{
text: 'Delete',
role: 'destructive',
icon: !this.platform.is('ios') ? 'trash' : null,
handler: () => {
console.log('Delete clicked');
this.result = 'Deleted';
}
},
{
text: 'Share',
icon: !this.platform.is('ios') ? 'share' : null,
handler: () => {
console.log('Share clicked');
this.result = 'Shared';
}
},
{
text: 'Play',
icon: !this.platform.is('ios') ? 'arrow-dropright-circle' : null,
handler: () => {
let modal = Modal.create(ModalPage);
this.nav.present(modal);
// returning false does not allow the actionsheet to be closed
return false;
}
},
{
text: 'Favorite',
icon: !this.platform.is('ios') ? 'heart' : null,
handler: () => {
console.log('Favorite clicked');
this.result = 'Favorited';
}
},
{
text: 'Cancel',
role: 'cancel', // will always sort to be on the bottom
icon: !this.platform.is('ios') ? 'close' : null,
handler: () => {
console.log('Cancel clicked');
this.result = 'Canceled';
}
}
]
});
this.nav.present(actionSheet);
}
presentActionSheet2(ev) {
this.result = '';
let actionSheet = ActionSheet.create({
enableBackdropDismiss: false,
buttons: [
{
text: 'Archive',
handler: () => {
console.log('Archive clicked');
this.result = 'Archived';
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('cancel this clicked');
this.result = 'Canceled';
}
},
{
text: 'Destructive',
role: 'destructive',
handler: () => {
console.log('Destructive clicked');
this.result = 'Destructive';
}
}
]
});
this.nav.present(actionSheet);
}
presentActionSheet3(ev) {
this.result = '';
let actionSheet = ActionSheet.create({
buttons: [
{
text: 'Open Alert',
handler: () => {
this.result = 'Opened alert';
let alert = Alert.create();
alert.setTitle('Alert!');
alert.setMessage('Alert opened from an action sheet');
alert.addButton({
text: 'Cancel',
role: 'cancel',
handler: () => {
this.result = 'pressed Cancel button in alert from action sheet';
}
});
alert.addButton({
text: 'Okay',
handler: () => {
this.result = 'pressed Okay button in alert from action sheet';
}
});
this.nav.present(alert).then(() => {
this.result = 'Alert from action sheet opened';
});
// do not close the action sheet yet
return false;
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
this.result = 'Canceled';
}
}
]
});
this.nav.present(actionSheet);
}
}
@Page({
template: `
<ion-toolbar>
<ion-buttons start>
<button (click)="dismiss()">Close</button>
</ion-buttons>
<ion-title>Modal</ion-title>
</ion-toolbar>
<ion-content padding>
Hi, I'm Bob, and I'm a modal.
</ion-content>
`
})
class ModalPage {
constructor(private viewCtrl: ViewController) {}
dismiss() {
this.viewCtrl.dismiss();
}
}
@App({
template: '<ion-nav [root]="root"></ion-nav>'
})
class E2EApp {
constructor() {
this.root = E2EPage;
}
}
| src/components/action-sheet/test/basic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00036165345227345824,
0.00018225864914711565,
0.00016355919069610536,
0.0001746232301229611,
0.00004252422877470963
] |
{
"id": 8,
"code_window": [
"import {Output, EventEmitter, Type, TemplateRef, ViewContainerRef, ElementRef, Renderer, ChangeDetectorRef} from '@angular/core';\n",
"\n",
"import {Navbar} from '../navbar/navbar';\n",
"import {NavController, NavOptions} from './nav-controller';\n",
"import {NavParams} from './nav-params';\n",
"import {isPresent} from '../../util/util';\n",
"\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {isPresent, merge} from '../../util/util';\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 5
} | #!/bin/bash
echo "##### "
echo "##### prepare.sh"
echo "#####"
function init {
cd ..
SITE_PATH=$(readJsonProp "config.json" "sitePath")
cd ..
export IONIC_DIR=$PWD
SITE_DIR=$IONIC_DIR/$SITE_PATH
}
function run {
if [ ! -d "$SITE_DIR" ]; then
echo "checking out"
cd ./scripts
./git/clone.sh --repository="ionic-site" \
--directory="$SITE_DIR" \
--branch="master"
else
echo "using existing"
cd $SITE_DIR
git reset --hard
git pull origin master
fi
}
source $(dirname $0)/../utils.sh.inc
| scripts/docs/prepare.sh | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017766414384823292,
0.00017529066826682538,
0.00017263770860154182,
0.00017543041030876338,
0.000001844042571974569
] |
{
"id": 9,
"code_window": [
"\n",
" onDismiss(callback: Function) {\n",
" this._onDismiss = callback;\n",
" }\n",
"\n",
" dismiss(data?: any, role?: any) {\n",
" return this._nav.remove(this._nav.indexOf(this), 1, this._leavingOpts).then(() => {\n",
" this._onDismiss && this._onDismiss(data, role);\n",
" return data;\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" dismiss(data?: any, role?: any, navOptions: NavOptions = {}) {\n",
" let options = merge({}, this._leavingOpts, navOptions);\n",
" return this._nav.remove(this._nav.indexOf(this), 1, options).then(() => {\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 127
} | @import "../../globals.wp";
// Windows Modals
// --------------------------------------------------
$modal-wp-background-color: $background-wp-color !default;
.modal-wrapper {
background-color: $modal-wp-background-color;
}
| src/components/modal/modal.wp.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.00017775835294742137,
0.0001770035014487803,
0.00017624866450205445,
0.0001770035014487803,
7.548442226834595e-7
] |
{
"id": 9,
"code_window": [
"\n",
" onDismiss(callback: Function) {\n",
" this._onDismiss = callback;\n",
" }\n",
"\n",
" dismiss(data?: any, role?: any) {\n",
" return this._nav.remove(this._nav.indexOf(this), 1, this._leavingOpts).then(() => {\n",
" this._onDismiss && this._onDismiss(data, role);\n",
" return data;\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" dismiss(data?: any, role?: any, navOptions: NavOptions = {}) {\n",
" let options = merge({}, this._leavingOpts, navOptions);\n",
" return this._nav.remove(this._nav.indexOf(this), 1, options).then(() => {\n"
],
"file_path": "src/components/nav/view-controller.ts",
"type": "replace",
"edit_start_line_idx": 127
} | import {App, Page, ActionSheet, Loading, NavController, ViewController, Platform} from '../../../../../src';
@Page({
templateUrl: 'main.html'
})
class E2EPage {
constructor(private nav: NavController, private platform: Platform) {}
presentLoading() {
let loading = Loading.create({
spinner: 'hide',
content: 'Loading...',
duration: 1000
});
this.nav.present(loading);
}
presentLoadingNav() {
let loading = Loading.create({
content: 'Please wait...',
});
this.nav.present(loading);
setTimeout(() => {
this.nav.push(Page2);
setTimeout(() => {
loading.dismiss();
}, 1000);
}, 1000);
}
}
@Page({
template: `
<ion-navbar *navbar>
<ion-title>Page 2</ion-title>
</ion-navbar>
<ion-content padding>Some content</ion-content>
`
})
class Page2 {
constructor(private nav: NavController, private platform: Platform) {}
}
@Page({
template: `
<ion-tabs>
<ion-tab tabTitle="Plain List" tabIcon="star" [root]="root1"></ion-tab>
<ion-tab tabTitle="Schedule" tabIcon="globe" [root]="root2"></ion-tab>
<ion-tab tabTitle="Stopwatch" tabIcon="stopwatch" [root]="root3"></ion-tab>
</ion-tabs>
`
})
export class TabsPage {
private root1 = E2EPage;
private root2 = Page2;
private root3 = E2EPage;
constructor() {
}
}
@App({
template: '<ion-nav [root]="root"></ion-nav>'
})
class E2EApp {
root = TabsPage;
}
| src/components/loading/test/tabs/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/9a86e4bdf89669aac5800fb9f7c0e0d087772fc3 | [
0.9975124597549438,
0.12585769593715668,
0.00016830880485940725,
0.0004452689900062978,
0.32946208119392395
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.