hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 3,
"code_window": [
"\t\t// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?\n",
"\t\treadonly followupPlaceholder?: string;\n",
"\t}\n",
"\n",
"\texport interface ChatAgentSubCommandProvider {\n",
"\n",
"\t\t/**\n",
"\t\t * Returns a list of subCommands that its agent is capable of handling. A subCommand\n",
"\t\t * can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API NAME: w/o Sub just `ChatAgentCommand` etc pp\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 155
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { compareBy } from 'vs/base/common/arrays';
import { findLastMaxBy, findFirstMinBy } from 'vs/base/common/arraysFind';
import { CursorState, PartialCursorState } from 'vs/editor/common/cursorCommon';
import { CursorContext } from 'vs/editor/common/cursor/cursorContext';
import { Cursor } from 'vs/editor/common/cursor/oneCursor';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
export class CursorCollection {
private context: CursorContext;
/**
* `cursors[0]` is the primary cursor, thus `cursors.length >= 1` is always true.
* `cursors.slice(1)` are secondary cursors.
*/
private cursors: Cursor[];
// An index which identifies the last cursor that was added / moved (think Ctrl+drag)
// This index refers to `cursors.slice(1)`, i.e. after removing the primary cursor.
private lastAddedCursorIndex: number;
constructor(context: CursorContext) {
this.context = context;
this.cursors = [new Cursor(context)];
this.lastAddedCursorIndex = 0;
}
public dispose(): void {
for (const cursor of this.cursors) {
cursor.dispose(this.context);
}
}
public startTrackingSelections(): void {
for (const cursor of this.cursors) {
cursor.startTrackingSelection(this.context);
}
}
public stopTrackingSelections(): void {
for (const cursor of this.cursors) {
cursor.stopTrackingSelection(this.context);
}
}
public updateContext(context: CursorContext): void {
this.context = context;
}
public ensureValidState(): void {
for (const cursor of this.cursors) {
cursor.ensureValidState(this.context);
}
}
public readSelectionFromMarkers(): Selection[] {
return this.cursors.map(c => c.readSelectionFromMarkers(this.context));
}
public getAll(): CursorState[] {
return this.cursors.map(c => c.asCursorState());
}
public getViewPositions(): Position[] {
return this.cursors.map(c => c.viewState.position);
}
public getTopMostViewPosition(): Position {
return findFirstMinBy(
this.cursors,
compareBy(c => c.viewState.position, Position.compare)
)!.viewState.position;
}
public getBottomMostViewPosition(): Position {
return findLastMaxBy(
this.cursors,
compareBy(c => c.viewState.position, Position.compare)
)!.viewState.position;
}
public getSelections(): Selection[] {
return this.cursors.map(c => c.modelState.selection);
}
public getViewSelections(): Selection[] {
return this.cursors.map(c => c.viewState.selection);
}
public setSelections(selections: ISelection[]): void {
this.setStates(CursorState.fromModelSelections(selections));
}
public getPrimaryCursor(): CursorState {
return this.cursors[0].asCursorState();
}
public setStates(states: PartialCursorState[] | null): void {
if (states === null) {
return;
}
this.cursors[0].setState(this.context, states[0].modelState, states[0].viewState);
this._setSecondaryStates(states.slice(1));
}
/**
* Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
*/
private _setSecondaryStates(secondaryStates: PartialCursorState[]): void {
const secondaryCursorsLength = this.cursors.length - 1;
const secondaryStatesLength = secondaryStates.length;
if (secondaryCursorsLength < secondaryStatesLength) {
const createCnt = secondaryStatesLength - secondaryCursorsLength;
for (let i = 0; i < createCnt; i++) {
this._addSecondaryCursor();
}
} else if (secondaryCursorsLength > secondaryStatesLength) {
const removeCnt = secondaryCursorsLength - secondaryStatesLength;
for (let i = 0; i < removeCnt; i++) {
this._removeSecondaryCursor(this.cursors.length - 2);
}
}
for (let i = 0; i < secondaryStatesLength; i++) {
this.cursors[i + 1].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState);
}
}
public killSecondaryCursors(): void {
this._setSecondaryStates([]);
}
private _addSecondaryCursor(): void {
this.cursors.push(new Cursor(this.context));
this.lastAddedCursorIndex = this.cursors.length - 1;
}
public getLastAddedCursorIndex(): number {
if (this.cursors.length === 1 || this.lastAddedCursorIndex === 0) {
return 0;
}
return this.lastAddedCursorIndex;
}
private _removeSecondaryCursor(removeIndex: number): void {
if (this.lastAddedCursorIndex >= removeIndex + 1) {
this.lastAddedCursorIndex--;
}
this.cursors[removeIndex + 1].dispose(this.context);
this.cursors.splice(removeIndex + 1, 1);
}
public normalize(): void {
if (this.cursors.length === 1) {
return;
}
const cursors = this.cursors.slice(0);
interface SortedCursor {
index: number;
selection: Selection;
}
const sortedCursors: SortedCursor[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
sortedCursors.push({
index: i,
selection: cursors[i].modelState.selection,
});
}
sortedCursors.sort(compareBy(s => s.selection, Range.compareRangesUsingStarts));
for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
const current = sortedCursors[sortedCursorIndex];
const next = sortedCursors[sortedCursorIndex + 1];
const currentSelection = current.selection;
const nextSelection = next.selection;
if (!this.context.cursorConfig.multiCursorMergeOverlapping) {
continue;
}
let shouldMergeCursors: boolean;
if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
// Merge touching cursors if one of them is collapsed
shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
} else {
// Merge only overlapping cursors (i.e. allow touching ranges)
shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
}
if (shouldMergeCursors) {
const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
const looserIndex = sortedCursors[looserSortedCursorIndex].index;
const winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
const looserSelection = sortedCursors[looserSortedCursorIndex].selection;
const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
if (!looserSelection.equalsSelection(winnerSelection)) {
const resultingRange = looserSelection.plusRange(winnerSelection);
const looserSelectionIsLTR = (looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn);
const winnerSelectionIsLTR = (winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn);
// Give more importance to the last added cursor (think Ctrl-dragging + hitting another cursor)
let resultingSelectionIsLTR: boolean;
if (looserIndex === this.lastAddedCursorIndex) {
resultingSelectionIsLTR = looserSelectionIsLTR;
this.lastAddedCursorIndex = winnerIndex;
} else {
// Winner takes it all
resultingSelectionIsLTR = winnerSelectionIsLTR;
}
let resultingSelection: Selection;
if (resultingSelectionIsLTR) {
resultingSelection = new Selection(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
} else {
resultingSelection = new Selection(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
}
sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
const resultingState = CursorState.fromModelSelection(resultingSelection);
cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
}
for (const sortedCursor of sortedCursors) {
if (sortedCursor.index > looserIndex) {
sortedCursor.index--;
}
}
cursors.splice(looserIndex, 1);
sortedCursors.splice(looserSortedCursorIndex, 1);
this._removeSecondaryCursor(looserIndex - 1);
sortedCursorIndex--;
}
}
}
}
| src/vs/editor/common/cursor/cursorCollection.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0001979466323973611,
0.0001720400177873671,
0.00016603070253040642,
0.00016975718608591706,
0.000006503993517981144
] |
{
"id": 3,
"code_window": [
"\t\t// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?\n",
"\t\treadonly followupPlaceholder?: string;\n",
"\t}\n",
"\n",
"\texport interface ChatAgentSubCommandProvider {\n",
"\n",
"\t\t/**\n",
"\t\t * Returns a list of subCommands that its agent is capable of handling. A subCommand\n",
"\t\t * can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API NAME: w/o Sub just `ChatAgentCommand` etc pp\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 155
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { ETAG_DISABLED, FileOperationError, FileOperationResult, IFileReadLimits, IFileService, IFileStatWithMetadata, IFileStreamContent, IWriteFileOptions, NotModifiedSinceFileOperationError } from 'vs/platform/files/common/files';
import { ISaveOptions, IRevertOptions, SaveReason } from 'vs/workbench/common/editor';
import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { IWorkingCopyBackup, IWorkingCopyBackupMeta, IWorkingCopySaveEvent, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { raceCancellation, TaskSequentializer, timeout } from 'vs/base/common/async';
import { ILogService } from 'vs/platform/log/common/log';
import { assertIsDefined } from 'vs/base/common/types';
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { VSBufferReadableStream } from 'vs/base/common/buffer';
import { IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
import { IWorkingCopyBackupService, IResolvedWorkingCopyBackup } from 'vs/workbench/services/workingCopy/common/workingCopyBackup';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { hash } from 'vs/base/common/hash';
import { isErrorWithActions, toErrorMessage } from 'vs/base/common/errorMessage';
import { IAction, toAction } from 'vs/base/common/actions';
import { isWindows } from 'vs/base/common/platform';
import { IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IElevatedFileService } from 'vs/workbench/services/files/common/elevatedFileService';
import { IResourceWorkingCopy, ResourceWorkingCopy } from 'vs/workbench/services/workingCopy/common/resourceWorkingCopy';
import { IFileWorkingCopy, IFileWorkingCopyModel, IFileWorkingCopyModelFactory } from 'vs/workbench/services/workingCopy/common/fileWorkingCopy';
import { IMarkdownString } from 'vs/base/common/htmlContent';
/**
* Stored file specific working copy model factory.
*/
export interface IStoredFileWorkingCopyModelFactory<M extends IStoredFileWorkingCopyModel> extends IFileWorkingCopyModelFactory<M> { }
/**
* The underlying model of a stored file working copy provides some
* methods for the stored file working copy to function. The model is
* typically only available after the working copy has been
* resolved via it's `resolve()` method.
*/
export interface IStoredFileWorkingCopyModel extends IFileWorkingCopyModel {
readonly onDidChangeContent: Event<IStoredFileWorkingCopyModelContentChangedEvent>;
/**
* A version ID of the model. If a `onDidChangeContent` is fired
* from the model and the last known saved `versionId` matches
* with the `model.versionId`, the stored file working copy will
* discard any dirty state.
*
* A use case is the following:
* - a stored file working copy gets edited and thus dirty
* - the user triggers undo to revert the changes
* - at this point the `versionId` should match the one we had saved
*
* This requires the model to be aware of undo/redo operations.
*/
readonly versionId: unknown;
/**
* Close the current undo-redo element. This offers a way
* to create an undo/redo stop point.
*
* This method may for example be called right before the
* save is triggered so that the user can always undo back
* to the state before saving.
*/
pushStackElement(): void;
/**
* Optionally allows a stored file working copy model to
* implement the `save` method. This allows to implement
* a more efficient save logic compared to the default
* which is to ask the model for a `snapshot` and then
* writing that to the model's resource.
*/
save?(options: IWriteFileOptions, token: CancellationToken): Promise<IFileStatWithMetadata>;
}
export interface IStoredFileWorkingCopyModelContentChangedEvent {
/**
* Flag that indicates that this event was generated while undoing.
*/
readonly isUndoing: boolean;
/**
* Flag that indicates that this event was generated while redoing.
*/
readonly isRedoing: boolean;
}
/**
* A stored file based `IWorkingCopy` is backed by a `URI` from a
* known file system provider. Given this assumption, a lot
* of functionality can be built on top, such as saving in
* a secure way to prevent data loss.
*/
export interface IStoredFileWorkingCopy<M extends IStoredFileWorkingCopyModel> extends IResourceWorkingCopy, IFileWorkingCopy<M> {
/**
* An event for when a stored file working copy was resolved.
*/
readonly onDidResolve: Event<void>;
/**
* An event for when a stored file working copy was saved successfully.
*/
readonly onDidSave: Event<IStoredFileWorkingCopySaveEvent>;
/**
* An event indicating that a stored file working copy save operation failed.
*/
readonly onDidSaveError: Event<void>;
/**
* An event for when the readonly state of the stored file working copy changes.
*/
readonly onDidChangeReadonly: Event<void>;
/**
* Resolves a stored file working copy.
*/
resolve(options?: IStoredFileWorkingCopyResolveOptions): Promise<void>;
/**
* Explicitly sets the working copy to be modified.
*/
markModified(): void;
/**
* Whether the stored file working copy is in the provided `state`
* or not.
*
* @param state the `FileWorkingCopyState` to check on.
*/
hasState(state: StoredFileWorkingCopyState): boolean;
/**
* Allows to join a state change away from the provided `state`.
*
* @param state currently only `FileWorkingCopyState.PENDING_SAVE`
* can be awaited on to resolve.
*/
joinState(state: StoredFileWorkingCopyState.PENDING_SAVE): Promise<void>;
/**
* Whether we have a resolved model or not.
*/
isResolved(): this is IResolvedStoredFileWorkingCopy<M>;
/**
* Whether the stored file working copy is readonly or not.
*/
isReadonly(): boolean | IMarkdownString;
/**
* Asks the stored file working copy to save. If the stored file
* working copy was dirty, it is expected to be non-dirty after
* this operation has finished.
*
* @returns `true` if the operation was successful and `false` otherwise.
*/
save(options?: IStoredFileWorkingCopySaveAsOptions): Promise<boolean>;
}
export interface IResolvedStoredFileWorkingCopy<M extends IStoredFileWorkingCopyModel> extends IStoredFileWorkingCopy<M> {
/**
* A resolved stored file working copy has a resolved model.
*/
readonly model: M;
}
/**
* States the stored file working copy can be in.
*/
export const enum StoredFileWorkingCopyState {
/**
* A stored file working copy is saved.
*/
SAVED,
/**
* A stored file working copy is dirty.
*/
DIRTY,
/**
* A stored file working copy is currently being saved but
* this operation has not completed yet.
*/
PENDING_SAVE,
/**
* A stored file working copy is in conflict mode when changes
* cannot be saved because the underlying file has changed.
* Stored file working copies in conflict mode are always dirty.
*/
CONFLICT,
/**
* A stored file working copy is in orphan state when the underlying
* file has been deleted.
*/
ORPHAN,
/**
* Any error that happens during a save that is not causing
* the `StoredFileWorkingCopyState.CONFLICT` state.
* Stored file working copies in error mode are always dirty.
*/
ERROR
}
export interface IStoredFileWorkingCopySaveOptions extends ISaveOptions {
/**
* Save the stored file working copy with an attempt to unlock it.
*/
readonly writeUnlock?: boolean;
/**
* Save the stored file working copy with elevated privileges.
*
* Note: This may not be supported in all environments.
*/
readonly writeElevated?: boolean;
/**
* Allows to write to a stored file working copy even if it has been
* modified on disk. This should only be triggered from an
* explicit user action.
*/
readonly ignoreModifiedSince?: boolean;
/**
* If set, will bubble up the stored file working copy save error to
* the caller instead of handling it.
*/
readonly ignoreErrorHandler?: boolean;
}
export interface IStoredFileWorkingCopySaveAsOptions extends IStoredFileWorkingCopySaveOptions {
/**
* Optional URI of the resource the text file is saved from if known.
*/
readonly from?: URI;
}
export interface IStoredFileWorkingCopyResolver {
/**
* Resolves the working copy in a safe way from an external
* working copy manager that can make sure multiple parallel
* resolves execute properly.
*/
(options?: IStoredFileWorkingCopyResolveOptions): Promise<void>;
}
export interface IStoredFileWorkingCopyResolveOptions {
/**
* The contents to use for the stored file working copy if known. If not
* provided, the contents will be retrieved from the underlying
* resource or backup if present.
*
* If contents are provided, the stored file working copy will be marked
* as dirty right from the beginning.
*/
readonly contents?: VSBufferReadableStream;
/**
* Go to disk bypassing any cache of the stored file working copy if any.
*/
readonly forceReadFromFile?: boolean;
/**
* If provided, the size of the file will be checked against the limits
* and an error will be thrown if any limit is exceeded.
*/
readonly limits?: IFileReadLimits;
}
/**
* Metadata associated with a stored file working copy backup.
*/
interface IStoredFileWorkingCopyBackupMetaData extends IWorkingCopyBackupMeta {
readonly mtime: number;
readonly ctime: number;
readonly size: number;
readonly etag: string;
readonly orphaned: boolean;
}
export interface IStoredFileWorkingCopySaveEvent extends IWorkingCopySaveEvent {
/**
* The resolved stat from the save operation.
*/
readonly stat: IFileStatWithMetadata;
}
export function isStoredFileWorkingCopySaveEvent(e: IWorkingCopySaveEvent): e is IStoredFileWorkingCopySaveEvent {
const candidate = e as IStoredFileWorkingCopySaveEvent;
return !!candidate.stat;
}
export class StoredFileWorkingCopy<M extends IStoredFileWorkingCopyModel> extends ResourceWorkingCopy implements IStoredFileWorkingCopy<M> {
readonly capabilities: WorkingCopyCapabilities = WorkingCopyCapabilities.None;
private _model: M | undefined = undefined;
get model(): M | undefined { return this._model; }
//#region events
private readonly _onDidChangeContent = this._register(new Emitter<void>());
readonly onDidChangeContent = this._onDidChangeContent.event;
private readonly _onDidResolve = this._register(new Emitter<void>());
readonly onDidResolve = this._onDidResolve.event;
private readonly _onDidChangeDirty = this._register(new Emitter<void>());
readonly onDidChangeDirty = this._onDidChangeDirty.event;
private readonly _onDidSaveError = this._register(new Emitter<void>());
readonly onDidSaveError = this._onDidSaveError.event;
private readonly _onDidSave = this._register(new Emitter<IStoredFileWorkingCopySaveEvent>());
readonly onDidSave = this._onDidSave.event;
private readonly _onDidRevert = this._register(new Emitter<void>());
readonly onDidRevert = this._onDidRevert.event;
private readonly _onDidChangeReadonly = this._register(new Emitter<void>());
readonly onDidChangeReadonly = this._onDidChangeReadonly.event;
//#endregion
constructor(
readonly typeId: string,
resource: URI,
readonly name: string,
private readonly modelFactory: IStoredFileWorkingCopyModelFactory<M>,
private readonly externalResolver: IStoredFileWorkingCopyResolver,
@IFileService fileService: IFileService,
@ILogService private readonly logService: ILogService,
@IWorkingCopyFileService private readonly workingCopyFileService: IWorkingCopyFileService,
@IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService,
@IWorkingCopyBackupService private readonly workingCopyBackupService: IWorkingCopyBackupService,
@IWorkingCopyService workingCopyService: IWorkingCopyService,
@INotificationService private readonly notificationService: INotificationService,
@IWorkingCopyEditorService private readonly workingCopyEditorService: IWorkingCopyEditorService,
@IEditorService private readonly editorService: IEditorService,
@IElevatedFileService private readonly elevatedFileService: IElevatedFileService
) {
super(resource, fileService);
// Make known to working copy service
this._register(workingCopyService.registerWorkingCopy(this));
this.registerListeners();
}
private registerListeners(): void {
this._register(this.filesConfigurationService.onDidChangeReadonly(() => this._onDidChangeReadonly.fire()));
}
//#region Dirty
private dirty = false;
private savedVersionId: unknown;
isDirty(): this is IResolvedStoredFileWorkingCopy<M> {
return this.dirty;
}
markModified(): void {
this.setDirty(true); // stored file working copy tracks modified via dirty
}
private setDirty(dirty: boolean): void {
if (!this.isResolved()) {
return; // only resolved working copies can be marked dirty
}
// Track dirty state and version id
const wasDirty = this.dirty;
this.doSetDirty(dirty);
// Emit as Event if dirty changed
if (dirty !== wasDirty) {
this._onDidChangeDirty.fire();
}
}
private doSetDirty(dirty: boolean): () => void {
const wasDirty = this.dirty;
const wasInConflictMode = this.inConflictMode;
const wasInErrorMode = this.inErrorMode;
const oldSavedVersionId = this.savedVersionId;
if (!dirty) {
this.dirty = false;
this.inConflictMode = false;
this.inErrorMode = false;
// we remember the models alternate version id to remember when the version
// of the model matches with the saved version on disk. we need to keep this
// in order to find out if the model changed back to a saved version (e.g.
// when undoing long enough to reach to a version that is saved and then to
// clear the dirty flag)
if (this.isResolved()) {
this.savedVersionId = this.model.versionId;
}
} else {
this.dirty = true;
}
// Return function to revert this call
return () => {
this.dirty = wasDirty;
this.inConflictMode = wasInConflictMode;
this.inErrorMode = wasInErrorMode;
this.savedVersionId = oldSavedVersionId;
};
}
//#endregion
//#region Resolve
private lastResolvedFileStat: IFileStatWithMetadata | undefined;
isResolved(): this is IResolvedStoredFileWorkingCopy<M> {
return !!this.model;
}
async resolve(options?: IStoredFileWorkingCopyResolveOptions): Promise<void> {
this.trace('resolve() - enter');
// Return early if we are disposed
if (this.isDisposed()) {
this.trace('resolve() - exit - without resolving because file working copy is disposed');
return;
}
// Unless there are explicit contents provided, it is important that we do not
// resolve a working copy that is dirty or is in the process of saving to prevent
// data loss.
if (!options?.contents && (this.dirty || this.saveSequentializer.isRunning())) {
this.trace('resolve() - exit - without resolving because file working copy is dirty or being saved');
return;
}
return this.doResolve(options);
}
private async doResolve(options?: IStoredFileWorkingCopyResolveOptions): Promise<void> {
// First check if we have contents to use for the working copy
if (options?.contents) {
return this.resolveFromBuffer(options.contents);
}
// Second, check if we have a backup to resolve from (only for new working copies)
const isNew = !this.isResolved();
if (isNew) {
const resolvedFromBackup = await this.resolveFromBackup();
if (resolvedFromBackup) {
return;
}
}
// Finally, resolve from file resource
return this.resolveFromFile(options);
}
private async resolveFromBuffer(buffer: VSBufferReadableStream): Promise<void> {
this.trace('resolveFromBuffer()');
// Try to resolve metdata from disk
let mtime: number;
let ctime: number;
let size: number;
let etag: string;
try {
const metadata = await this.fileService.stat(this.resource);
mtime = metadata.mtime;
ctime = metadata.ctime;
size = metadata.size;
etag = metadata.etag;
// Clear orphaned state when resolving was successful
this.setOrphaned(false);
} catch (error) {
// Put some fallback values in error case
mtime = Date.now();
ctime = Date.now();
size = 0;
etag = ETAG_DISABLED;
// Apply orphaned state based on error code
this.setOrphaned(error.fileOperationResult === FileOperationResult.FILE_NOT_FOUND);
}
// Resolve with buffer
return this.resolveFromContent({
resource: this.resource,
name: this.name,
mtime,
ctime,
size,
etag,
value: buffer,
readonly: false,
locked: false
}, true /* dirty (resolved from buffer) */);
}
private async resolveFromBackup(): Promise<boolean> {
// Resolve backup if any
const backup = await this.workingCopyBackupService.resolve<IStoredFileWorkingCopyBackupMetaData>(this);
// Abort if someone else managed to resolve the working copy by now
const isNew = !this.isResolved();
if (!isNew) {
this.trace('resolveFromBackup() - exit - withoutresolving because previously new file working copy got created meanwhile');
return true; // imply that resolving has happened in another operation
}
// Try to resolve from backup if we have any
if (backup) {
await this.doResolveFromBackup(backup);
return true;
}
// Otherwise signal back that resolving did not happen
return false;
}
private async doResolveFromBackup(backup: IResolvedWorkingCopyBackup<IStoredFileWorkingCopyBackupMetaData>): Promise<void> {
this.trace('doResolveFromBackup()');
// Resolve with backup
await this.resolveFromContent({
resource: this.resource,
name: this.name,
mtime: backup.meta ? backup.meta.mtime : Date.now(),
ctime: backup.meta ? backup.meta.ctime : Date.now(),
size: backup.meta ? backup.meta.size : 0,
etag: backup.meta ? backup.meta.etag : ETAG_DISABLED, // etag disabled if unknown!
value: backup.value,
readonly: false,
locked: false
}, true /* dirty (resolved from backup) */);
// Restore orphaned flag based on state
if (backup.meta && backup.meta.orphaned) {
this.setOrphaned(true);
}
}
private async resolveFromFile(options?: IStoredFileWorkingCopyResolveOptions): Promise<void> {
this.trace('resolveFromFile()');
const forceReadFromFile = options?.forceReadFromFile;
// Decide on etag
let etag: string | undefined;
if (forceReadFromFile) {
etag = ETAG_DISABLED; // disable ETag if we enforce to read from disk
} else if (this.lastResolvedFileStat) {
etag = this.lastResolvedFileStat.etag; // otherwise respect etag to support caching
}
// Remember current version before doing any long running operation
// to ensure we are not changing a working copy that was changed
// meanwhile
const currentVersionId = this.versionId;
// Resolve Content
try {
const content = await this.fileService.readFileStream(this.resource, {
etag,
limits: options?.limits
});
// Clear orphaned state when resolving was successful
this.setOrphaned(false);
// Return early if the working copy content has changed
// meanwhile to prevent loosing any changes
if (currentVersionId !== this.versionId) {
this.trace('resolveFromFile() - exit - without resolving because file working copy content changed');
return;
}
await this.resolveFromContent(content, false /* not dirty (resolved from file) */);
} catch (error) {
const result = error.fileOperationResult;
// Apply orphaned state based on error code
this.setOrphaned(result === FileOperationResult.FILE_NOT_FOUND);
// NotModified status is expected and can be handled gracefully
// if we are resolved. We still want to update our last resolved
// stat to e.g. detect changes to the file's readonly state
if (this.isResolved() && result === FileOperationResult.FILE_NOT_MODIFIED_SINCE) {
if (error instanceof NotModifiedSinceFileOperationError) {
this.updateLastResolvedFileStat(error.stat);
}
return;
}
// Unless we are forced to read from the file, ignore when a working copy has
// been resolved once and the file was deleted meanwhile. Since we already have
// the working copy resolved, we can return to this state and update the orphaned
// flag to indicate that this working copy has no version on disk anymore.
if (this.isResolved() && result === FileOperationResult.FILE_NOT_FOUND && !forceReadFromFile) {
return;
}
// Otherwise bubble up the error
throw error;
}
}
private async resolveFromContent(content: IFileStreamContent, dirty: boolean): Promise<void> {
this.trace('resolveFromContent() - enter');
// Return early if we are disposed
if (this.isDisposed()) {
this.trace('resolveFromContent() - exit - because working copy is disposed');
return;
}
// Update our resolved disk stat
this.updateLastResolvedFileStat({
resource: this.resource,
name: content.name,
mtime: content.mtime,
ctime: content.ctime,
size: content.size,
etag: content.etag,
readonly: content.readonly,
locked: content.locked,
isFile: true,
isDirectory: false,
isSymbolicLink: false,
children: undefined
});
// Update existing model if we had been resolved
if (this.isResolved()) {
await this.doUpdateModel(content.value);
}
// Create new model otherwise
else {
await this.doCreateModel(content.value);
}
// Update working copy dirty flag. This is very important to call
// in both cases of dirty or not because it conditionally updates
// the `savedVersionId` to determine the version when to consider
// the working copy as saved again (e.g. when undoing back to the
// saved state)
this.setDirty(!!dirty);
// Emit as event
this._onDidResolve.fire();
}
private async doCreateModel(contents: VSBufferReadableStream): Promise<void> {
this.trace('doCreateModel()');
// Create model and dispose it when we get disposed
this._model = this._register(await this.modelFactory.createModel(this.resource, contents, CancellationToken.None));
// Model listeners
this.installModelListeners(this._model);
}
private ignoreDirtyOnModelContentChange = false;
private async doUpdateModel(contents: VSBufferReadableStream): Promise<void> {
this.trace('doUpdateModel()');
// Update model value in a block that ignores content change events for dirty tracking
this.ignoreDirtyOnModelContentChange = true;
try {
await this.model?.update(contents, CancellationToken.None);
} finally {
this.ignoreDirtyOnModelContentChange = false;
}
}
private installModelListeners(model: M): void {
// See https://github.com/microsoft/vscode/issues/30189
// This code has been extracted to a different method because it caused a memory leak
// where `value` was captured in the content change listener closure scope.
// Content Change
this._register(model.onDidChangeContent(e => this.onModelContentChanged(model, e.isUndoing || e.isRedoing)));
// Lifecycle
this._register(model.onWillDispose(() => this.dispose()));
}
private onModelContentChanged(model: M, isUndoingOrRedoing: boolean): void {
this.trace(`onModelContentChanged() - enter`);
// In any case increment the version id because it tracks the content state of the model at all times
this.versionId++;
this.trace(`onModelContentChanged() - new versionId ${this.versionId}`);
// Remember when the user changed the model through a undo/redo operation.
// We need this information to throttle save participants to fix
// https://github.com/microsoft/vscode/issues/102542
if (isUndoingOrRedoing) {
this.lastContentChangeFromUndoRedo = Date.now();
}
// We mark check for a dirty-state change upon model content change, unless:
// - explicitly instructed to ignore it (e.g. from model.resolve())
// - the model is readonly (in that case we never assume the change was done by the user)
if (!this.ignoreDirtyOnModelContentChange && !this.isReadonly()) {
// The contents changed as a matter of Undo and the version reached matches the saved one
// In this case we clear the dirty flag and emit a SAVED event to indicate this state.
if (model.versionId === this.savedVersionId) {
this.trace('onModelContentChanged() - model content changed back to last saved version');
// Clear flags
const wasDirty = this.dirty;
this.setDirty(false);
// Emit revert event if we were dirty
if (wasDirty) {
this._onDidRevert.fire();
}
}
// Otherwise the content has changed and we signal this as becoming dirty
else {
this.trace('onModelContentChanged() - model content changed and marked as dirty');
// Mark as dirty
this.setDirty(true);
}
}
// Emit as event
this._onDidChangeContent.fire();
}
private async forceResolveFromFile(): Promise<void> {
if (this.isDisposed()) {
return; // return early when the working copy is invalid
}
// We go through the resolver to make
// sure this kind of `resolve` is properly
// running in sequence with any other running
// `resolve` if any, including subsequent runs
// that are triggered right after.
await this.externalResolver({
forceReadFromFile: true
});
}
//#endregion
//#region Backup
get backupDelay(): number | undefined {
return this.model?.configuration?.backupDelay;
}
async backup(token: CancellationToken): Promise<IWorkingCopyBackup> {
// Fill in metadata if we are resolved
let meta: IStoredFileWorkingCopyBackupMetaData | undefined = undefined;
if (this.lastResolvedFileStat) {
meta = {
mtime: this.lastResolvedFileStat.mtime,
ctime: this.lastResolvedFileStat.ctime,
size: this.lastResolvedFileStat.size,
etag: this.lastResolvedFileStat.etag,
orphaned: this.isOrphaned()
};
}
// Fill in content if we are resolved
let content: VSBufferReadableStream | undefined = undefined;
if (this.isResolved()) {
content = await raceCancellation(this.model.snapshot(token), token);
}
return { meta, content };
}
//#endregion
//#region Save
private versionId = 0;
private static readonly UNDO_REDO_SAVE_PARTICIPANTS_AUTO_SAVE_THROTTLE_THRESHOLD = 500;
private lastContentChangeFromUndoRedo: number | undefined = undefined;
private readonly saveSequentializer = new TaskSequentializer();
private ignoreSaveFromSaveParticipants = false;
async save(options: IStoredFileWorkingCopySaveAsOptions = Object.create(null)): Promise<boolean> {
if (!this.isResolved()) {
return false;
}
if (this.isReadonly()) {
this.trace('save() - ignoring request for readonly resource');
return false; // if working copy is readonly we do not attempt to save at all
}
if (
(this.hasState(StoredFileWorkingCopyState.CONFLICT) || this.hasState(StoredFileWorkingCopyState.ERROR)) &&
(options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)
) {
this.trace('save() - ignoring auto save request for file working copy that is in conflict or error');
return false; // if working copy is in save conflict or error, do not save unless save reason is explicit
}
// Actually do save
this.trace('save() - enter');
await this.doSave(options);
this.trace('save() - exit');
return this.hasState(StoredFileWorkingCopyState.SAVED);
}
private async doSave(options: IStoredFileWorkingCopySaveAsOptions): Promise<void> {
if (typeof options.reason !== 'number') {
options.reason = SaveReason.EXPLICIT;
}
let versionId = this.versionId;
this.trace(`doSave(${versionId}) - enter with versionId ${versionId}`);
// Return early if saved from within save participant to break recursion
//
// Scenario: a save participant triggers a save() on the working copy
if (this.ignoreSaveFromSaveParticipants) {
this.trace(`doSave(${versionId}) - exit - refusing to save() recursively from save participant`);
return;
}
// Lookup any running save for this versionId and return it if found
//
// Scenario: user invoked the save action multiple times quickly for the same contents
// while the save was not yet finished to disk
//
if (this.saveSequentializer.isRunning(versionId)) {
this.trace(`doSave(${versionId}) - exit - found a running save for versionId ${versionId}`);
return this.saveSequentializer.running;
}
// Return early if not dirty (unless forced)
//
// Scenario: user invoked save action even though the working copy is not dirty
if (!options.force && !this.dirty) {
this.trace(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.dirty}, this.versionId: ${this.versionId})`);
return;
}
// Return if currently saving by storing this save request as the next save that should happen.
// Never ever must 2 saves execute at the same time because this can lead to dirty writes and race conditions.
//
// Scenario A: auto save was triggered and is currently busy saving to disk. this takes long enough that another auto save
// kicks in.
// Scenario B: save is very slow (e.g. network share) and the user manages to change the working copy and trigger another save
// while the first save has not returned yet.
//
if (this.saveSequentializer.isRunning()) {
this.trace(`doSave(${versionId}) - exit - because busy saving`);
// Indicate to the save sequentializer that we want to
// cancel the running operation so that ours can run
// before the running one finishes.
// Currently this will try to cancel running save
// participants and running snapshots from the
// save operation, but not the actual save which does
// not support cancellation yet.
this.saveSequentializer.cancelRunning();
// Queue this as the upcoming save and return
return this.saveSequentializer.queue(() => this.doSave(options));
}
// Push all edit operations to the undo stack so that the user has a chance to
// Ctrl+Z back to the saved version.
if (this.isResolved()) {
this.model.pushStackElement();
}
const saveCancellation = new CancellationTokenSource();
return this.saveSequentializer.run(versionId, (async () => {
// A save participant can still change the working copy now
// and since we are so close to saving we do not want to trigger
// another auto save or similar, so we block this
// In addition we update our version right after in case it changed
// because of a working copy change
// Save participants can also be skipped through API.
if (this.isResolved() && !options.skipSaveParticipants && this.workingCopyFileService.hasSaveParticipants) {
try {
// Measure the time it took from the last undo/redo operation to this save. If this
// time is below `UNDO_REDO_SAVE_PARTICIPANTS_THROTTLE_THRESHOLD`, we make sure to
// delay the save participant for the remaining time if the reason is auto save.
//
// This fixes the following issue:
// - the user has configured auto save with delay of 100ms or shorter
// - the user has a save participant enabled that modifies the file on each save
// - the user types into the file and the file gets saved
// - the user triggers undo operation
// - this will undo the save participant change but trigger the save participant right after
// - the user has no chance to undo over the save participant
//
// Reported as: https://github.com/microsoft/vscode/issues/102542
if (options.reason === SaveReason.AUTO && typeof this.lastContentChangeFromUndoRedo === 'number') {
const timeFromUndoRedoToSave = Date.now() - this.lastContentChangeFromUndoRedo;
if (timeFromUndoRedoToSave < StoredFileWorkingCopy.UNDO_REDO_SAVE_PARTICIPANTS_AUTO_SAVE_THROTTLE_THRESHOLD) {
await timeout(StoredFileWorkingCopy.UNDO_REDO_SAVE_PARTICIPANTS_AUTO_SAVE_THROTTLE_THRESHOLD - timeFromUndoRedoToSave);
}
}
// Run save participants unless save was cancelled meanwhile
if (!saveCancellation.token.isCancellationRequested) {
this.ignoreSaveFromSaveParticipants = true;
try {
await this.workingCopyFileService.runSaveParticipants(this, { reason: options.reason ?? SaveReason.EXPLICIT, savedFrom: options.from }, saveCancellation.token);
} finally {
this.ignoreSaveFromSaveParticipants = false;
}
}
} catch (error) {
this.logService.error(`[stored file working copy] runSaveParticipants(${versionId}) - resulted in an error: ${error.toString()}`, this.resource.toString(), this.typeId);
}
}
// It is possible that a subsequent save is cancelling this
// running save. As such we return early when we detect that.
if (saveCancellation.token.isCancellationRequested) {
return;
}
// We have to protect against being disposed at this point. It could be that the save() operation
// was triggerd followed by a dispose() operation right after without waiting. Typically we cannot
// be disposed if we are dirty, but if we are not dirty, save() and dispose() can still be triggered
// one after the other without waiting for the save() to complete. If we are disposed(), we risk
// saving contents to disk that are stale (see https://github.com/microsoft/vscode/issues/50942).
// To fix this issue, we will not store the contents to disk when we got disposed.
if (this.isDisposed()) {
return;
}
// We require a resolved working copy from this point on, since we are about to write data to disk.
if (!this.isResolved()) {
return;
}
// update versionId with its new value (if pre-save changes happened)
versionId = this.versionId;
// Clear error flag since we are trying to save again
this.inErrorMode = false;
// Save to Disk. We mark the save operation as currently running with
// the latest versionId because it might have changed from a save
// participant triggering
this.trace(`doSave(${versionId}) - before write()`);
const lastResolvedFileStat = assertIsDefined(this.lastResolvedFileStat);
const resolvedFileWorkingCopy = this;
return this.saveSequentializer.run(versionId, (async () => {
try {
const writeFileOptions: IWriteFileOptions = {
mtime: lastResolvedFileStat.mtime,
etag: (options.ignoreModifiedSince || !this.filesConfigurationService.preventSaveConflicts(lastResolvedFileStat.resource)) ? ETAG_DISABLED : lastResolvedFileStat.etag,
unlock: options.writeUnlock
};
let stat: IFileStatWithMetadata;
// Delegate to working copy model save method if any
if (typeof resolvedFileWorkingCopy.model.save === 'function') {
stat = await resolvedFileWorkingCopy.model.save(writeFileOptions, saveCancellation.token);
}
// Otherwise ask for a snapshot and save via file services
else {
// Snapshot working copy model contents
const snapshot = await raceCancellation(resolvedFileWorkingCopy.model.snapshot(saveCancellation.token), saveCancellation.token);
// It is possible that a subsequent save is cancelling this
// running save. As such we return early when we detect that
// However, we do not pass the token into the file service
// because that is an atomic operation currently without
// cancellation support, so we dispose the cancellation if
// it was not cancelled yet.
if (saveCancellation.token.isCancellationRequested) {
return;
} else {
saveCancellation.dispose();
}
// Write them to disk
if (options?.writeElevated && this.elevatedFileService.isSupported(lastResolvedFileStat.resource)) {
stat = await this.elevatedFileService.writeFileElevated(lastResolvedFileStat.resource, assertIsDefined(snapshot), writeFileOptions);
} else {
stat = await this.fileService.writeFile(lastResolvedFileStat.resource, assertIsDefined(snapshot), writeFileOptions);
}
}
this.handleSaveSuccess(stat, versionId, options);
} catch (error) {
this.handleSaveError(error, versionId, options);
}
})(), () => saveCancellation.cancel());
})(), () => saveCancellation.cancel());
}
private handleSaveSuccess(stat: IFileStatWithMetadata, versionId: number, options: IStoredFileWorkingCopySaveAsOptions): void {
// Updated resolved stat with updated stat
this.updateLastResolvedFileStat(stat);
// Update dirty state unless working copy has changed meanwhile
if (versionId === this.versionId) {
this.trace(`handleSaveSuccess(${versionId}) - setting dirty to false because versionId did not change`);
this.setDirty(false);
} else {
this.trace(`handleSaveSuccess(${versionId}) - not setting dirty to false because versionId did change meanwhile`);
}
// Update orphan state given save was successful
this.setOrphaned(false);
// Emit Save Event
this._onDidSave.fire({ reason: options.reason, stat, source: options.source });
}
private handleSaveError(error: Error, versionId: number, options: IStoredFileWorkingCopySaveAsOptions): void {
(options.ignoreErrorHandler ? this.logService.trace : this.logService.error).apply(this.logService, [`[stored file working copy] handleSaveError(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource.toString(), this.typeId]);
// Return early if the save() call was made asking to
// handle the save error itself.
if (options.ignoreErrorHandler) {
throw error;
}
// In any case of an error, we mark the working copy as dirty to prevent data loss
// It could be possible that the write corrupted the file on disk (e.g. when
// an error happened after truncating the file) and as such we want to preserve
// the working copy contents to prevent data loss.
this.setDirty(true);
// Flag as error state
this.inErrorMode = true;
// Look out for a save conflict
if ((error as FileOperationError).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
this.inConflictMode = true;
}
// Show save error to user for handling
this.doHandleSaveError(error);
// Emit as event
this._onDidSaveError.fire();
}
private doHandleSaveError(error: Error): void {
const fileOperationError = error as FileOperationError;
const primaryActions: IAction[] = [];
let message: string;
// Dirty write prevention
if (fileOperationError.fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
message = localize('staleSaveError', "Failed to save '{0}': The content of the file is newer. Do you want to overwrite the file with your changes?", this.name);
primaryActions.push(toAction({ id: 'fileWorkingCopy.overwrite', label: localize('overwrite', "Overwrite"), run: () => this.save({ ignoreModifiedSince: true }) }));
primaryActions.push(toAction({ id: 'fileWorkingCopy.revert', label: localize('discard', "Discard"), run: () => this.revert() }));
}
// Any other save error
else {
const isWriteLocked = fileOperationError.fileOperationResult === FileOperationResult.FILE_WRITE_LOCKED;
const triedToUnlock = isWriteLocked && (fileOperationError.options as IWriteFileOptions | undefined)?.unlock;
const isPermissionDenied = fileOperationError.fileOperationResult === FileOperationResult.FILE_PERMISSION_DENIED;
const canSaveElevated = this.elevatedFileService.isSupported(this.resource);
// Error with Actions
if (isErrorWithActions(error)) {
primaryActions.push(...error.actions);
}
// Save Elevated
if (canSaveElevated && (isPermissionDenied || triedToUnlock)) {
primaryActions.push(toAction({
id: 'fileWorkingCopy.saveElevated',
label: triedToUnlock ?
isWindows ? localize('overwriteElevated', "Overwrite as Admin...") : localize('overwriteElevatedSudo', "Overwrite as Sudo...") :
isWindows ? localize('saveElevated', "Retry as Admin...") : localize('saveElevatedSudo', "Retry as Sudo..."),
run: () => {
this.save({ writeElevated: true, writeUnlock: triedToUnlock, reason: SaveReason.EXPLICIT });
}
}));
}
// Unlock
else if (isWriteLocked) {
primaryActions.push(toAction({ id: 'fileWorkingCopy.unlock', label: localize('overwrite', "Overwrite"), run: () => this.save({ writeUnlock: true, reason: SaveReason.EXPLICIT }) }));
}
// Retry
else {
primaryActions.push(toAction({ id: 'fileWorkingCopy.retry', label: localize('retry', "Retry"), run: () => this.save({ reason: SaveReason.EXPLICIT }) }));
}
// Save As
primaryActions.push(toAction({
id: 'fileWorkingCopy.saveAs',
label: localize('saveAs', "Save As..."),
run: async () => {
const editor = this.workingCopyEditorService.findEditor(this);
if (editor) {
const result = await this.editorService.save(editor, { saveAs: true, reason: SaveReason.EXPLICIT });
if (!result.success) {
this.doHandleSaveError(error); // show error again given the operation failed
}
}
}
}));
// Discard
primaryActions.push(toAction({ id: 'fileWorkingCopy.revert', label: localize('discard', "Discard"), run: () => this.revert() }));
// Message
if (isWriteLocked) {
if (triedToUnlock && canSaveElevated) {
message = isWindows ?
localize('readonlySaveErrorAdmin', "Failed to save '{0}': File is read-only. Select 'Overwrite as Admin' to retry as administrator.", this.name) :
localize('readonlySaveErrorSudo', "Failed to save '{0}': File is read-only. Select 'Overwrite as Sudo' to retry as superuser.", this.name);
} else {
message = localize('readonlySaveError', "Failed to save '{0}': File is read-only. Select 'Overwrite' to attempt to make it writeable.", this.name);
}
} else if (canSaveElevated && isPermissionDenied) {
message = isWindows ?
localize('permissionDeniedSaveError', "Failed to save '{0}': Insufficient permissions. Select 'Retry as Admin' to retry as administrator.", this.name) :
localize('permissionDeniedSaveErrorSudo', "Failed to save '{0}': Insufficient permissions. Select 'Retry as Sudo' to retry as superuser.", this.name);
} else {
message = localize({ key: 'genericSaveError', comment: ['{0} is the resource that failed to save and {1} the error message'] }, "Failed to save '{0}': {1}", this.name, toErrorMessage(error, false));
}
}
// Show to the user as notification
const handle = this.notificationService.notify({ id: `${hash(this.resource.toString())}`, severity: Severity.Error, message, actions: { primary: primaryActions } });
// Remove automatically when we get saved/reverted
const listener = this._register(Event.once(Event.any(this.onDidSave, this.onDidRevert))(() => handle.close()));
this._register(Event.once(handle.onDidClose)(() => listener.dispose()));
}
private updateLastResolvedFileStat(newFileStat: IFileStatWithMetadata): void {
const oldReadonly = this.isReadonly();
// First resolve - just take
if (!this.lastResolvedFileStat) {
this.lastResolvedFileStat = newFileStat;
}
// Subsequent resolve - make sure that we only assign it if the mtime
// is equal or has advanced.
// This prevents race conditions from resolving and saving. If a save
// comes in late after a revert was called, the mtime could be out of
// sync.
else if (this.lastResolvedFileStat.mtime <= newFileStat.mtime) {
this.lastResolvedFileStat = newFileStat;
}
// Signal that the readonly state changed
if (this.isReadonly() !== oldReadonly) {
this._onDidChangeReadonly.fire();
}
}
//#endregion
//#region Revert
async revert(options?: IRevertOptions): Promise<void> {
if (!this.isResolved() || (!this.dirty && !options?.force)) {
return; // ignore if not resolved or not dirty and not enforced
}
this.trace('revert()');
// Unset flags
const wasDirty = this.dirty;
const undoSetDirty = this.doSetDirty(false);
// Force read from disk unless reverting soft
const softUndo = options?.soft;
if (!softUndo) {
try {
await this.forceResolveFromFile();
} catch (error) {
// FileNotFound means the file got deleted meanwhile, so ignore it
if ((error as FileOperationError).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND) {
// Set flags back to previous values, we are still dirty if revert failed
undoSetDirty();
throw error;
}
}
}
// Emit file change event
this._onDidRevert.fire();
// Emit dirty change event
if (wasDirty) {
this._onDidChangeDirty.fire();
}
}
//#endregion
//#region State
private inConflictMode = false;
private inErrorMode = false;
hasState(state: StoredFileWorkingCopyState): boolean {
switch (state) {
case StoredFileWorkingCopyState.CONFLICT:
return this.inConflictMode;
case StoredFileWorkingCopyState.DIRTY:
return this.dirty;
case StoredFileWorkingCopyState.ERROR:
return this.inErrorMode;
case StoredFileWorkingCopyState.ORPHAN:
return this.isOrphaned();
case StoredFileWorkingCopyState.PENDING_SAVE:
return this.saveSequentializer.isRunning();
case StoredFileWorkingCopyState.SAVED:
return !this.dirty;
}
}
async joinState(state: StoredFileWorkingCopyState.PENDING_SAVE): Promise<void> {
return this.saveSequentializer.running;
}
//#endregion
//#region Utilities
isReadonly(): boolean | IMarkdownString {
return this.filesConfigurationService.isReadonly(this.resource, this.lastResolvedFileStat);
}
private trace(msg: string): void {
this.logService.trace(`[stored file working copy] ${msg}`, this.resource.toString(), this.typeId);
}
//#endregion
//#region Dispose
override dispose(): void {
this.trace('dispose()');
// State
this.inConflictMode = false;
this.inErrorMode = false;
// Free up model for GC
this._model = undefined;
super.dispose();
}
//#endregion
}
| src/vs/workbench/services/workingCopy/common/storedFileWorkingCopy.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00030806302675046027,
0.00017221778398379683,
0.00016291261999867857,
0.00016896228771656752,
0.000014834304238320328
] |
{
"id": 4,
"code_window": [
"\t\t * This provider will be called once after each request to retrieve suggested followup questions.\n",
"\t\t */\n",
"\t\tfollowupProvider?: ChatAgentFollowupProvider<TResult>;\n",
"\n",
"\n",
"\t\t// TODO@\n",
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t// TODO@API\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "replace",
"edit_start_line_idx": 255
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { ExtHostChatProviderShape, IMainContext, MainContext, MainThreadChatProviderShape } from 'vs/workbench/api/common/extHost.protocol';
import * as typeConvert from 'vs/workbench/api/common/extHostTypeConverters';
import type * as vscode from 'vscode';
import { Progress } from 'vs/platform/progress/common/progress';
import { IChatMessage, IChatResponseFragment } from 'vs/workbench/contrib/chat/common/chatProvider';
import { ExtensionIdentifier, ExtensionIdentifierMap, ExtensionIdentifierSet } from 'vs/platform/extensions/common/extensions';
import { AsyncIterableSource } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
type LanguageModelData = {
readonly extension: ExtensionIdentifier;
readonly provider: vscode.ChatResponseProvider;
};
class LanguageModelResponseStream {
readonly stream = new AsyncIterableSource<string>();
constructor(
readonly option: number,
stream?: AsyncIterableSource<string>
) {
this.stream = stream ?? new AsyncIterableSource<string>();
}
}
class LanguageModelRequest {
readonly apiObject: vscode.LanguageModelResponse;
private readonly _responseStreams = new Map<number, LanguageModelResponseStream>();
private readonly _defaultStream = new AsyncIterableSource<string>();
private _isDone: boolean = false;
constructor(
promise: Promise<any>,
readonly cts: CancellationTokenSource
) {
const that = this;
this.apiObject = {
result: promise,
stream: that._defaultStream.asyncIterable,
// responses: AsyncIterable<string>[] // FUTURE responses per N
};
promise.finally(() => {
this._isDone = true;
if (this._responseStreams.size > 0) {
for (const [, value] of this._responseStreams) {
value.stream.resolve();
}
} else {
this._defaultStream.resolve();
}
});
}
handleFragment(fragment: IChatResponseFragment): void {
if (this._isDone) {
return;
}
let res = this._responseStreams.get(fragment.index);
if (!res) {
if (this._responseStreams.size === 0) {
// the first response claims the default response
res = new LanguageModelResponseStream(fragment.index, this._defaultStream);
} else {
res = new LanguageModelResponseStream(fragment.index);
}
this._responseStreams.set(fragment.index, res);
}
res.stream.emitOne(fragment.part);
}
}
export class ExtHostChatProvider implements ExtHostChatProviderShape {
private static _idPool = 1;
private readonly _proxy: MainThreadChatProviderShape;
private readonly _onDidChangeAccess = new Emitter<ExtensionIdentifierSet>();
private readonly _onDidChangeProviders = new Emitter<vscode.LanguageModelChangeEvent>();
readonly onDidChangeProviders = this._onDidChangeProviders.event;
private readonly _languageModels = new Map<number, LanguageModelData>();
private readonly _languageModelIds = new Set<string>(); // these are ALL models, not just the one in this EH
private readonly _accesslist = new ExtensionIdentifierMap<boolean>();
private readonly _pendingRequest = new Map<number, { languageModelId: string; res: LanguageModelRequest }>();
constructor(
mainContext: IMainContext,
private readonly _logService: ILogService,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadChatProvider);
}
dispose(): void {
this._onDidChangeAccess.dispose();
this._onDidChangeProviders.dispose();
}
registerLanguageModel(extension: ExtensionIdentifier, identifier: string, provider: vscode.ChatResponseProvider, metadata: vscode.ChatResponseProviderMetadata): IDisposable {
const handle = ExtHostChatProvider._idPool++;
this._languageModels.set(handle, { extension, provider });
this._proxy.$registerProvider(handle, identifier, { extension, model: metadata.name ?? '' });
return toDisposable(() => {
this._languageModels.delete(handle);
this._proxy.$unregisterProvider(handle);
});
}
async $provideLanguageModelResponse(handle: number, requestId: number, from: ExtensionIdentifier, messages: IChatMessage[], options: { [name: string]: any }, token: CancellationToken): Promise<any> {
const data = this._languageModels.get(handle);
if (!data) {
return;
}
const progress = new Progress<vscode.ChatResponseFragment>(async fragment => {
if (token.isCancellationRequested) {
this._logService.warn(`[CHAT](${data.extension.value}) CANNOT send progress because the REQUEST IS CANCELLED`);
return;
}
this._proxy.$handleProgressChunk(requestId, { index: fragment.index, part: fragment.part });
});
if (data.provider.provideLanguageModelResponse) {
return data.provider.provideLanguageModelResponse(messages.map(typeConvert.ChatMessage.to), options, ExtensionIdentifier.toKey(from), progress, token);
} else {
return data.provider.provideChatResponse(messages.map(typeConvert.ChatMessage.to), options, progress, token);
}
}
//#region --- making request
$updateLanguageModels(data: { added?: string[] | undefined; removed?: string[] | undefined }): void {
const added: string[] = [];
const removed: string[] = [];
if (data.added) {
for (const id of data.added) {
this._languageModelIds.add(id);
added.push(id);
}
}
if (data.removed) {
for (const id of data.removed) {
// clean up
this._languageModelIds.delete(id);
removed.push(id);
// cancel pending requests for this model
for (const [key, value] of this._pendingRequest) {
if (value.languageModelId === id) {
value.res.cts.cancel();
this._pendingRequest.delete(key);
}
}
}
}
this._onDidChangeProviders.fire(Object.freeze({
added: Object.freeze(added),
removed: Object.freeze(removed)
}));
}
getLanguageModelIds(): string[] {
return Array.from(this._languageModelIds);
}
$updateAccesslist(data: { extension: ExtensionIdentifier; enabled: boolean }[]): void {
const updated = new ExtensionIdentifierSet();
for (const { extension, enabled } of data) {
const oldValue = this._accesslist.get(extension);
if (oldValue !== enabled) {
this._accesslist.set(extension, enabled);
updated.add(extension);
}
}
this._onDidChangeAccess.fire(updated);
}
async requestLanguageModelAccess(from: ExtensionIdentifier, languageModelId: string, options?: vscode.LanguageModelAccessOptions): Promise<vscode.LanguageModelAccess> {
// check if the extension is in the access list and allowed to make chat requests
if (this._accesslist.get(from) === false) {
throw new Error('Extension is NOT allowed to make chat requests');
}
const metadata = await this._proxy.$prepareChatAccess(from, languageModelId, options?.justification);
if (!metadata) {
if (!this._accesslist.get(from)) {
throw new Error('Extension is NOT allowed to make chat requests');
}
throw new Error(`Language model '${languageModelId}' NOT found`);
}
const that = this;
return {
get model() {
return metadata.model;
},
get isRevoked() {
return !that._accesslist.get(from) || !that._languageModelIds.has(languageModelId);
},
get onDidChangeAccess() {
const onDidChangeAccess = Event.filter(that._onDidChangeAccess.event, set => set.has(from));
const onDidRemoveLM = Event.filter(that._onDidChangeProviders.event, e => e.removed.includes(languageModelId));
return Event.signal(Event.any(onDidChangeAccess, onDidRemoveLM));
},
makeRequest(messages, options, token) {
if (!that._accesslist.get(from)) {
throw new Error('Access to chat has been revoked');
}
if (!that._languageModelIds.has(languageModelId)) {
throw new Error('Language Model has been removed');
}
const cts = new CancellationTokenSource(token);
const requestId = (Math.random() * 1e6) | 0;
const requestPromise = that._proxy.$fetchResponse(from, languageModelId, requestId, messages.map(typeConvert.ChatMessage.from), options ?? {}, cts.token);
const res = new LanguageModelRequest(requestPromise, cts);
that._pendingRequest.set(requestId, { languageModelId, res });
requestPromise.finally(() => {
that._pendingRequest.delete(requestId);
cts.dispose();
});
return res.apiObject;
},
};
}
async $handleResponseFragment(requestId: number, chunk: IChatResponseFragment): Promise<void> {
const data = this._pendingRequest.get(requestId);//.report(chunk);
if (data) {
data.res.handleFragment(chunk);
}
}
}
| src/vs/workbench/api/common/extHostChatProvider.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0002669796231202781,
0.00018667812400963157,
0.00016452866839244962,
0.0001720435102470219,
0.00002991217843373306
] |
{
"id": 4,
"code_window": [
"\t\t * This provider will be called once after each request to retrieve suggested followup questions.\n",
"\t\t */\n",
"\t\tfollowupProvider?: ChatAgentFollowupProvider<TResult>;\n",
"\n",
"\n",
"\t\t// TODO@\n",
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t// TODO@API\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "replace",
"edit_start_line_idx": 255
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { memoize } from '../utils/memoize';
export class Logger {
@memoize
private get output(): vscode.LogOutputChannel {
return vscode.window.createOutputChannel('TypeScript', { log: true });
}
public get logLevel(): vscode.LogLevel {
return this.output.logLevel;
}
public info(message: string, ...args: any[]): void {
this.output.info(message, ...args);
}
public trace(message: string, ...args: any[]): void {
this.output.trace(message, ...args);
}
public error(message: string, data?: any): void {
// See https://github.com/microsoft/TypeScript/issues/10496
if (data && data.message === 'No content available.') {
return;
}
this.output.error(message, ...(data ? [data] : []));
}
}
| extensions/typescript-language-features/src/logging/logger.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017414020840078592,
0.00016971275908872485,
0.00016585129196755588,
0.00016942973888944834,
0.0000037278923628036864
] |
{
"id": 4,
"code_window": [
"\t\t * This provider will be called once after each request to retrieve suggested followup questions.\n",
"\t\t */\n",
"\t\tfollowupProvider?: ChatAgentFollowupProvider<TResult>;\n",
"\n",
"\n",
"\t\t// TODO@\n",
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t// TODO@API\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "replace",
"edit_start_line_idx": 255
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TestResultState } from 'vs/workbench/contrib/testing/common/testTypes';
export type TreeStateNode = { statusNode: true; state: TestResultState; priority: number };
/**
* List of display priorities for different run states. When tests update,
* the highest-priority state from any of their children will be the state
* reflected in the parent node.
*/
export const statePriority: { [K in TestResultState]: number } = {
[TestResultState.Running]: 6,
[TestResultState.Errored]: 5,
[TestResultState.Failed]: 4,
[TestResultState.Queued]: 3,
[TestResultState.Passed]: 2,
[TestResultState.Unset]: 0,
[TestResultState.Skipped]: 1,
};
export const isFailedState = (s: TestResultState) => s === TestResultState.Errored || s === TestResultState.Failed;
export const isStateWithResult = (s: TestResultState) => s === TestResultState.Errored || s === TestResultState.Failed || s === TestResultState.Passed;
export const stateNodes = Object.entries(statePriority).reduce(
(acc, [stateStr, priority]) => {
const state = Number(stateStr) as TestResultState;
acc[state] = { statusNode: true, state, priority };
return acc;
}, {} as { [K in TestResultState]: TreeStateNode }
);
export const cmpPriority = (a: TestResultState, b: TestResultState) => statePriority[b] - statePriority[a];
export const maxPriority = (...states: TestResultState[]) => {
switch (states.length) {
case 0:
return TestResultState.Unset;
case 1:
return states[0];
case 2:
return statePriority[states[0]] > statePriority[states[1]] ? states[0] : states[1];
default: {
let max = states[0];
for (let i = 1; i < states.length; i++) {
if (statePriority[max] < statePriority[states[i]]) {
max = states[i];
}
}
return max;
}
}
};
export const statesInOrder = Object.keys(statePriority).map(s => Number(s) as TestResultState).sort(cmpPriority);
/**
* Some states are considered terminal; once these are set for a given test run, they
* are not reset back to a non-terminal state, or to a terminal state with lower
* priority.
*/
export const terminalStatePriorities: { [key in TestResultState]?: number } = {
[TestResultState.Passed]: 0,
[TestResultState.Skipped]: 1,
[TestResultState.Failed]: 2,
[TestResultState.Errored]: 3,
};
/**
* Count of the number of tests in each run state.
*/
export type TestStateCount = { [K in TestResultState]: number };
export const makeEmptyCounts = (): TestStateCount => {
// shh! don't tell anyone this is actually an array!
return new Uint32Array(statesInOrder.length) as any as { [K in TestResultState]: number };
};
| src/vs/workbench/contrib/testing/common/testingStates.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017537797975819558,
0.000170823564985767,
0.00016637967200949788,
0.00017054154886864126,
0.000002723860234254971
] |
{
"id": 4,
"code_window": [
"\t\t * This provider will be called once after each request to retrieve suggested followup questions.\n",
"\t\t */\n",
"\t\tfollowupProvider?: ChatAgentFollowupProvider<TResult>;\n",
"\n",
"\n",
"\t\t// TODO@\n",
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t// TODO@API\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "replace",
"edit_start_line_idx": 255
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { assertFn } from 'vs/base/common/assert';
import { BugIndicatingError } from 'vs/base/common/errors';
import { Event } from 'vs/base/common/event';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { derived, IObservable, observableFromEvent, observableValue } from 'vs/base/common/observable';
import { basename, isEqual } from 'vs/base/common/resources';
import Severity from 'vs/base/common/severity';
import { URI } from 'vs/base/common/uri';
import { IModelService } from 'vs/editor/common/services/model';
import { IResolvedTextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService';
import { localize } from 'vs/nls';
import { ConfirmResult, IDialogService, IPromptButton } from 'vs/platform/dialogs/common/dialogs';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IRevertOptions, SaveSourceRegistry } from 'vs/workbench/common/editor';
import { EditorModel } from 'vs/workbench/common/editor/editorModel';
import { MergeEditorInputData } from 'vs/workbench/contrib/mergeEditor/browser/mergeEditorInput';
import { conflictMarkers } from 'vs/workbench/contrib/mergeEditor/browser/mergeMarkers/mergeMarkersController';
import { MergeDiffComputer } from 'vs/workbench/contrib/mergeEditor/browser/model/diffComputer';
import { InputData, MergeEditorModel } from 'vs/workbench/contrib/mergeEditor/browser/model/mergeEditorModel';
import { MergeEditorTelemetry } from 'vs/workbench/contrib/mergeEditor/browser/telemetry';
import { StorageCloseWithConflicts } from 'vs/workbench/contrib/mergeEditor/common/mergeEditor';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ITextFileEditorModel, ITextFileSaveOptions, ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
export interface MergeEditorArgs {
base: URI;
input1: MergeEditorInputData;
input2: MergeEditorInputData;
result: URI;
}
export interface IMergeEditorInputModelFactory {
createInputModel(args: MergeEditorArgs): Promise<IMergeEditorInputModel>;
}
export interface IMergeEditorInputModel extends IDisposable {
readonly resultUri: URI;
readonly model: MergeEditorModel;
readonly isDirty: IObservable<boolean>;
save(options?: ITextFileSaveOptions): Promise<void>;
/**
* If save resets the dirty state, revert must do so too.
*/
revert(options?: IRevertOptions): Promise<void>;
shouldConfirmClose(): boolean;
confirmClose(inputModels: IMergeEditorInputModel[]): Promise<ConfirmResult>;
/**
* Marks the merge as done. The merge editor must be closed afterwards.
*/
accept(): Promise<void>;
}
/* ================ Temp File ================ */
export class TempFileMergeEditorModeFactory implements IMergeEditorInputModelFactory {
constructor(
private readonly _mergeEditorTelemetry: MergeEditorTelemetry,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@ITextModelService private readonly _textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
) {
}
async createInputModel(args: MergeEditorArgs): Promise<IMergeEditorInputModel> {
const store = new DisposableStore();
const [
base,
result,
input1Data,
input2Data,
] = await Promise.all([
this._textModelService.createModelReference(args.base),
this._textModelService.createModelReference(args.result),
toInputData(args.input1, this._textModelService, store),
toInputData(args.input2, this._textModelService, store),
]);
store.add(base);
store.add(result);
const tempResultUri = result.object.textEditorModel.uri.with({ scheme: 'merge-result' });
const temporaryResultModel = this._modelService.createModel(
'',
{
languageId: result.object.textEditorModel.getLanguageId(),
onDidChange: Event.None,
},
tempResultUri,
);
store.add(temporaryResultModel);
const mergeDiffComputer = this._instantiationService.createInstance(MergeDiffComputer);
const model = this._instantiationService.createInstance(
MergeEditorModel,
base.object.textEditorModel,
input1Data,
input2Data,
temporaryResultModel,
mergeDiffComputer,
{
resetResult: true,
},
this._mergeEditorTelemetry,
);
store.add(model);
await model.onInitialized;
return this._instantiationService.createInstance(TempFileMergeEditorInputModel, model, store, result.object, args.result);
}
}
class TempFileMergeEditorInputModel extends EditorModel implements IMergeEditorInputModel {
private readonly savedAltVersionId = observableValue(this, this.model.resultTextModel.getAlternativeVersionId());
private readonly altVersionId = observableFromEvent(
e => this.model.resultTextModel.onDidChangeContent(e),
() =>
/** @description getAlternativeVersionId */ this.model.resultTextModel.getAlternativeVersionId()
);
public readonly isDirty = derived(this, (reader) => this.altVersionId.read(reader) !== this.savedAltVersionId.read(reader));
private finished = false;
constructor(
public readonly model: MergeEditorModel,
private readonly disposable: IDisposable,
private readonly result: IResolvedTextEditorModel,
public readonly resultUri: URI,
@ITextFileService private readonly textFileService: ITextFileService,
@IDialogService private readonly dialogService: IDialogService,
@IEditorService private readonly editorService: IEditorService,
) {
super();
}
override dispose(): void {
this.disposable.dispose();
super.dispose();
}
async accept(): Promise<void> {
const value = await this.model.resultTextModel.getValue();
this.result.textEditorModel.setValue(value);
this.savedAltVersionId.set(this.model.resultTextModel.getAlternativeVersionId(), undefined);
await this.textFileService.save(this.result.textEditorModel.uri);
this.finished = true;
}
private async _discard(): Promise<void> {
await this.textFileService.revert(this.model.resultTextModel.uri);
this.savedAltVersionId.set(this.model.resultTextModel.getAlternativeVersionId(), undefined);
this.finished = true;
}
public shouldConfirmClose(): boolean {
return true;
}
public async confirmClose(inputModels: TempFileMergeEditorInputModel[]): Promise<ConfirmResult> {
assertFn(
() => inputModels.some((m) => m === this)
);
const someDirty = inputModels.some((m) => m.isDirty.get());
let choice: ConfirmResult;
if (someDirty) {
const isMany = inputModels.length > 1;
const message = isMany
? localize('messageN', 'Do you want keep the merge result of {0} files?', inputModels.length)
: localize('message1', 'Do you want keep the merge result of {0}?', basename(inputModels[0].model.resultTextModel.uri));
const hasUnhandledConflicts = inputModels.some((m) => m.model.hasUnhandledConflicts.get());
const buttons: IPromptButton<ConfirmResult>[] = [
{
label: hasUnhandledConflicts ?
localize({ key: 'saveWithConflict', comment: ['&& denotes a mnemonic'] }, "&&Save With Conflicts") :
localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"),
run: () => ConfirmResult.SAVE
},
{
label: localize({ key: 'discard', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
run: () => ConfirmResult.DONT_SAVE
}
];
choice = (await this.dialogService.prompt<ConfirmResult>({
type: Severity.Info,
message,
detail:
hasUnhandledConflicts
? isMany
? localize('detailNConflicts', "The files contain unhandled conflicts. The merge results will be lost if you don't save them.")
: localize('detail1Conflicts', "The file contains unhandled conflicts. The merge result will be lost if you don't save it.")
: isMany
? localize('detailN', "The merge results will be lost if you don't save them.")
: localize('detail1', "The merge result will be lost if you don't save it."),
buttons,
cancelButton: {
run: () => ConfirmResult.CANCEL
}
})).result;
} else {
choice = ConfirmResult.DONT_SAVE;
}
if (choice === ConfirmResult.SAVE) {
// save with conflicts
await Promise.all(inputModels.map(m => m.accept()));
} else if (choice === ConfirmResult.DONT_SAVE) {
// discard changes
await Promise.all(inputModels.map(m => m._discard()));
} else {
// cancel: stay in editor
}
return choice;
}
public async save(options?: ITextFileSaveOptions): Promise<void> {
if (this.finished) {
return;
}
// It does not make sense to save anything in the temp file mode.
// The file stays dirty from the first edit on.
(async () => {
const { confirmed } = await this.dialogService.confirm({
message: localize(
'saveTempFile.message',
"Do you want to accept the merge result?"
),
detail: localize(
'saveTempFile.detail',
"This will write the merge result to the original file and close the merge editor."
),
primaryButton: localize({ key: 'acceptMerge', comment: ['&& denotes a mnemonic'] }, '&&Accept Merge')
});
if (confirmed) {
await this.accept();
const editors = this.editorService.findEditors(this.resultUri).filter(e => e.editor.typeId === 'mergeEditor.Input');
await this.editorService.closeEditors(editors);
}
})();
}
public async revert(options?: IRevertOptions): Promise<void> {
// no op
}
}
/* ================ Workspace ================ */
export class WorkspaceMergeEditorModeFactory implements IMergeEditorInputModelFactory {
constructor(
private readonly _mergeEditorTelemetry: MergeEditorTelemetry,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@ITextModelService private readonly _textModelService: ITextModelService,
@ITextFileService private readonly textFileService: ITextFileService,
) {
}
private static readonly FILE_SAVED_SOURCE = SaveSourceRegistry.registerSource('merge-editor.source', localize('merge-editor.source', "Before Resolving Conflicts In Merge Editor"));
public async createInputModel(args: MergeEditorArgs): Promise<IMergeEditorInputModel> {
const store = new DisposableStore();
let resultTextFileModel = undefined as ITextFileEditorModel | undefined;
const modelListener = store.add(new DisposableStore());
const handleDidCreate = (model: ITextFileEditorModel) => {
if (isEqual(args.result, model.resource)) {
modelListener.clear();
resultTextFileModel = model;
}
};
modelListener.add(this.textFileService.files.onDidCreate(handleDidCreate));
this.textFileService.files.models.forEach(handleDidCreate);
const [
base,
result,
input1Data,
input2Data,
] = await Promise.all([
this._textModelService.createModelReference(args.base),
this._textModelService.createModelReference(args.result),
toInputData(args.input1, this._textModelService, store),
toInputData(args.input2, this._textModelService, store),
]);
store.add(base);
store.add(result);
if (!resultTextFileModel) {
throw new BugIndicatingError();
}
// So that "Don't save" does revert the file
await resultTextFileModel.save({ source: WorkspaceMergeEditorModeFactory.FILE_SAVED_SOURCE });
const lines = resultTextFileModel.textEditorModel!.getLinesContent();
const hasConflictMarkers = lines.some(l => l.startsWith(conflictMarkers.start));
const resetResult = hasConflictMarkers;
const mergeDiffComputer = this._instantiationService.createInstance(MergeDiffComputer);
const model = this._instantiationService.createInstance(
MergeEditorModel,
base.object.textEditorModel,
input1Data,
input2Data,
result.object.textEditorModel,
mergeDiffComputer,
{
resetResult
},
this._mergeEditorTelemetry,
);
store.add(model);
await model.onInitialized;
return this._instantiationService.createInstance(WorkspaceMergeEditorInputModel, model, store, resultTextFileModel, this._mergeEditorTelemetry);
}
}
class WorkspaceMergeEditorInputModel extends EditorModel implements IMergeEditorInputModel {
public readonly isDirty = observableFromEvent(
Event.any(this.resultTextFileModel.onDidChangeDirty, this.resultTextFileModel.onDidSaveError),
() => /** @description isDirty */ this.resultTextFileModel.isDirty()
);
private reported = false;
private readonly dateTimeOpened = new Date();
constructor(
public readonly model: MergeEditorModel,
private readonly disposableStore: DisposableStore,
private readonly resultTextFileModel: ITextFileEditorModel,
private readonly telemetry: MergeEditorTelemetry,
@IDialogService private readonly _dialogService: IDialogService,
@IStorageService private readonly _storageService: IStorageService,
) {
super();
}
public override dispose(): void {
this.disposableStore.dispose();
super.dispose();
this.reportClose(false);
}
private reportClose(accepted: boolean): void {
if (!this.reported) {
const remainingConflictCount = this.model.unhandledConflictsCount.get();
const durationOpenedMs = new Date().getTime() - this.dateTimeOpened.getTime();
this.telemetry.reportMergeEditorClosed({
durationOpenedSecs: durationOpenedMs / 1000,
remainingConflictCount,
accepted,
conflictCount: this.model.conflictCount,
combinableConflictCount: this.model.combinableConflictCount,
conflictsResolvedWithBase: this.model.conflictsResolvedWithBase,
conflictsResolvedWithInput1: this.model.conflictsResolvedWithInput1,
conflictsResolvedWithInput2: this.model.conflictsResolvedWithInput2,
conflictsResolvedWithSmartCombination: this.model.conflictsResolvedWithSmartCombination,
manuallySolvedConflictCountThatEqualNone: this.model.manuallySolvedConflictCountThatEqualNone,
manuallySolvedConflictCountThatEqualSmartCombine: this.model.manuallySolvedConflictCountThatEqualSmartCombine,
manuallySolvedConflictCountThatEqualInput1: this.model.manuallySolvedConflictCountThatEqualInput1,
manuallySolvedConflictCountThatEqualInput2: this.model.manuallySolvedConflictCountThatEqualInput2,
manuallySolvedConflictCountThatEqualNoneAndStartedWithBase: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithBase,
manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1,
manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2,
manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart,
manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart,
});
this.reported = true;
}
}
public async accept(): Promise<void> {
this.reportClose(true);
await this.resultTextFileModel.save();
}
get resultUri(): URI {
return this.resultTextFileModel.resource;
}
async save(options?: ITextFileSaveOptions): Promise<void> {
await this.resultTextFileModel.save(options);
}
/**
* If save resets the dirty state, revert must do so too.
*/
async revert(options?: IRevertOptions): Promise<void> {
await this.resultTextFileModel.revert(options);
}
shouldConfirmClose(): boolean {
// Always confirm
return true;
}
async confirmClose(inputModels: IMergeEditorInputModel[]): Promise<ConfirmResult> {
const isMany = inputModels.length > 1;
const someDirty = inputModels.some(m => m.isDirty.get());
const someUnhandledConflicts = inputModels.some(m => m.model.hasUnhandledConflicts.get());
if (someDirty) {
const message = isMany
? localize('workspace.messageN', 'Do you want to save the changes you made to {0} files?', inputModels.length)
: localize('workspace.message1', 'Do you want to save the changes you made to {0}?', basename(inputModels[0].resultUri));
const { result } = await this._dialogService.prompt<ConfirmResult>({
type: Severity.Info,
message,
detail:
someUnhandledConflicts ?
isMany
? localize('workspace.detailN.unhandled', "The files contain unhandled conflicts. Your changes will be lost if you don't save them.")
: localize('workspace.detail1.unhandled', "The file contains unhandled conflicts. Your changes will be lost if you don't save them.")
: isMany
? localize('workspace.detailN.handled', "Your changes will be lost if you don't save them.")
: localize('workspace.detail1.handled', "Your changes will be lost if you don't save them."),
buttons: [
{
label: someUnhandledConflicts
? localize({ key: 'workspace.saveWithConflict', comment: ['&& denotes a mnemonic'] }, '&&Save with Conflicts')
: localize({ key: 'workspace.save', comment: ['&& denotes a mnemonic'] }, '&&Save'),
run: () => ConfirmResult.SAVE
},
{
label: localize({ key: 'workspace.doNotSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
run: () => ConfirmResult.DONT_SAVE
}
],
cancelButton: {
run: () => ConfirmResult.CANCEL
}
});
return result;
} else if (someUnhandledConflicts && !this._storageService.getBoolean(StorageCloseWithConflicts, StorageScope.PROFILE, false)) {
const { confirmed, checkboxChecked } = await this._dialogService.confirm({
message: isMany
? localize('workspace.messageN.nonDirty', 'Do you want to close {0} merge editors?', inputModels.length)
: localize('workspace.message1.nonDirty', 'Do you want to close the merge editor for {0}?', basename(inputModels[0].resultUri)),
detail: someUnhandledConflicts ?
isMany
? localize('workspace.detailN.unhandled.nonDirty', "The files contain unhandled conflicts.")
: localize('workspace.detail1.unhandled.nonDirty', "The file contains unhandled conflicts.")
: undefined,
primaryButton: someUnhandledConflicts
? localize({ key: 'workspace.closeWithConflicts', comment: ['&& denotes a mnemonic'] }, '&&Close with Conflicts')
: localize({ key: 'workspace.close', comment: ['&& denotes a mnemonic'] }, '&&Close'),
checkbox: { label: localize('noMoreWarn', "Do not ask me again") }
});
if (checkboxChecked) {
this._storageService.store(StorageCloseWithConflicts, true, StorageScope.PROFILE, StorageTarget.USER);
}
return confirmed ? ConfirmResult.SAVE : ConfirmResult.CANCEL;
} else {
// This shouldn't do anything
return ConfirmResult.SAVE;
}
}
}
/* ================= Utils ================== */
async function toInputData(data: MergeEditorInputData, textModelService: ITextModelService, store: DisposableStore): Promise<InputData> {
const ref = await textModelService.createModelReference(data.uri);
store.add(ref);
return {
textModel: ref.object.textEditorModel,
title: data.title,
description: data.description,
detail: data.detail,
};
}
| src/vs/workbench/contrib/mergeEditor/browser/mergeEditorInputModel.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017761060735210776,
0.00017133676738012582,
0.0001667359028942883,
0.00017114050569944084,
0.00000238581719713693
] |
{
"id": 5,
"code_window": [
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n",
"\n",
"\t\t// TODO@API\n",
"\t\t// clear NEVER happens\n",
"\t\t// onDidClearResult(value: TResult): void;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// BETTER\n",
"\t\t// requestResponseStream(callback: (stream: ChatAgentResponseStream) => void, why?: string): void;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 257
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.9628913998603821,
0.026467550545930862,
0.00016304501332342625,
0.0008147828048095107,
0.12573149800300598
] |
{
"id": 5,
"code_window": [
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n",
"\n",
"\t\t// TODO@API\n",
"\t\t// clear NEVER happens\n",
"\t\t// onDidClearResult(value: TResult): void;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// BETTER\n",
"\t\t// requestResponseStream(callback: (stream: ChatAgentResponseStream) => void, why?: string): void;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 257
} | /*---------------------------------------------------------------------------------------------
* 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 { CancellationToken } from 'vs/base/common/cancellation';
import { Disposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { assertSnapshot } from 'vs/base/test/common/snapshot';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
import { Range } from 'vs/editor/common/core/range';
import { ProviderResult } from 'vs/editor/common/languages';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IViewsService } from 'vs/workbench/services/views/common/viewsService';
import { ChatAgentService, IChatAgent, IChatAgentService } from 'vs/workbench/contrib/chat/common/chatAgents';
import { IChatContributionService } from 'vs/workbench/contrib/chat/common/chatContributionService';
import { ISerializableChatData } from 'vs/workbench/contrib/chat/common/chatModel';
import { IChat, IChatProgress, IChatProvider, IChatRequest } from 'vs/workbench/contrib/chat/common/chatService';
import { ChatService } from 'vs/workbench/contrib/chat/common/chatServiceImpl';
import { ChatSlashCommandService, IChatSlashCommandService } from 'vs/workbench/contrib/chat/common/chatSlashCommands';
import { IChatVariablesService } from 'vs/workbench/contrib/chat/common/chatVariables';
import { MockChatVariablesService } from 'vs/workbench/contrib/chat/test/common/mockChatVariables';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { TestContextService, TestExtensionService, TestStorageService } from 'vs/workbench/test/common/workbenchTestServices';
class SimpleTestProvider extends Disposable implements IChatProvider {
private static sessionId = 0;
readonly displayName = 'Test';
constructor(readonly id: string) {
super();
}
async prepareSession(): Promise<IChat> {
return {
id: SimpleTestProvider.sessionId++,
responderUsername: 'test',
requesterUsername: 'test',
};
}
async provideReply(request: IChatRequest, progress: (progress: IChatProgress) => void): Promise<{ session: IChat; followups: never[] }> {
return { session: request.session, followups: [] };
}
}
const chatAgentWithUsedContextId = 'ChatProviderWithUsedContext';
const chatAgentWithUsedContext: IChatAgent = {
id: chatAgentWithUsedContextId,
metadata: {},
async provideSlashCommands(token) {
return [];
},
async invoke(request, progress, history, token) {
progress({
documents: [
{
uri: URI.file('/test/path/to/file'),
version: 3,
ranges: [
new Range(1, 1, 2, 2)
]
}
],
kind: 'usedContext'
});
return {};
},
};
suite('Chat', () => {
const testDisposables = ensureNoDisposablesAreLeakedInTestSuite();
let storageService: IStorageService;
let instantiationService: TestInstantiationService;
let chatAgentService: IChatAgentService;
setup(async () => {
instantiationService = testDisposables.add(new TestInstantiationService(new ServiceCollection(
[IChatVariablesService, new MockChatVariablesService()],
)));
instantiationService.stub(IStorageService, storageService = testDisposables.add(new TestStorageService()));
instantiationService.stub(ILogService, new NullLogService());
instantiationService.stub(ITelemetryService, NullTelemetryService);
instantiationService.stub(IExtensionService, new TestExtensionService());
instantiationService.stub(IContextKeyService, new MockContextKeyService());
instantiationService.stub(IViewsService, new TestExtensionService());
instantiationService.stub(IChatContributionService, new TestExtensionService());
instantiationService.stub(IWorkspaceContextService, new TestContextService());
instantiationService.stub(IChatSlashCommandService, testDisposables.add(instantiationService.createInstance(ChatSlashCommandService)));
chatAgentService = testDisposables.add(instantiationService.createInstance(ChatAgentService));
instantiationService.stub(IChatAgentService, chatAgentService);
const agent = {
id: 'testAgent',
metadata: { isDefault: true },
async invoke(request, progress, history, token) {
return {};
},
} as IChatAgent;
testDisposables.add(chatAgentService.registerAgent(agent));
});
test('retrieveSession', async () => {
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
const provider1 = testDisposables.add(new SimpleTestProvider('provider1'));
const provider2 = testDisposables.add(new SimpleTestProvider('provider2'));
testDisposables.add(testService.registerProvider(provider1));
testDisposables.add(testService.registerProvider(provider2));
const session1 = testDisposables.add(testService.startSession('provider1', CancellationToken.None));
await session1.waitForInitialization();
session1.addRequest({ parts: [], text: 'request 1' }, { message: 'request 1', variables: {} });
const session2 = testDisposables.add(testService.startSession('provider2', CancellationToken.None));
await session2.waitForInitialization();
session2.addRequest({ parts: [], text: 'request 2' }, { message: 'request 2', variables: {} });
storageService.flush();
const testService2 = testDisposables.add(instantiationService.createInstance(ChatService));
testDisposables.add(testService2.registerProvider(provider1));
testDisposables.add(testService2.registerProvider(provider2));
const retrieved1 = testDisposables.add(testService2.getOrRestoreSession(session1.sessionId)!);
await retrieved1.waitForInitialization();
const retrieved2 = testDisposables.add(testService2.getOrRestoreSession(session2.sessionId)!);
await retrieved2.waitForInitialization();
assert.deepStrictEqual(retrieved1.getRequests()[0]?.message.text, 'request 1');
assert.deepStrictEqual(retrieved2.getRequests()[0]?.message.text, 'request 2');
});
test('Handles failed session startup', async () => {
function getFailProvider(providerId: string) {
return new class implements IChatProvider {
readonly id = providerId;
readonly displayName = 'Test';
lastInitialState = undefined;
prepareSession(initialState: any): ProviderResult<any> {
throw new Error('Failed to start session');
}
async provideReply(request: IChatRequest) {
return { session: request.session, followups: [] };
}
};
}
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
const provider1 = getFailProvider('provider1');
testDisposables.add(testService.registerProvider(provider1));
const session1 = testDisposables.add(testService.startSession('provider1', CancellationToken.None));
await assert.rejects(() => session1.waitForInitialization());
});
test('Can\'t register same provider id twice', async () => {
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
const id = 'testProvider';
testDisposables.add(testService.registerProvider({
id,
prepareSession: function (token: CancellationToken): ProviderResult<IChat | undefined> {
throw new Error('Function not implemented.');
}
}));
assert.throws(() => {
testDisposables.add(testService.registerProvider({
id,
prepareSession: function (token: CancellationToken): ProviderResult<IChat | undefined> {
throw new Error('Function not implemented.');
}
}));
}, 'Expected to throw for dupe provider');
});
test('sendRequestToProvider', async () => {
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
testDisposables.add(testService.registerProvider(testDisposables.add(new SimpleTestProvider('testProvider'))));
const model = testDisposables.add(testService.startSession('testProvider', CancellationToken.None));
assert.strictEqual(model.getRequests().length, 0);
const response = await testService.sendRequestToProvider(model.sessionId, { message: 'test request' });
await response?.responseCompletePromise;
assert.strictEqual(model.getRequests().length, 1);
});
test('addCompleteRequest', async () => {
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
testDisposables.add(testService.registerProvider(testDisposables.add(new SimpleTestProvider('testProvider'))));
const model = testDisposables.add(testService.startSession('testProvider', CancellationToken.None));
assert.strictEqual(model.getRequests().length, 0);
await testService.addCompleteRequest(model.sessionId, 'test request', undefined, { message: 'test response' });
assert.strictEqual(model.getRequests().length, 1);
assert.ok(model.getRequests()[0].response);
assert.strictEqual(model.getRequests()[0].response?.response.asString(), 'test response');
});
test('can serialize', async () => {
testDisposables.add(chatAgentService.registerAgent(chatAgentWithUsedContext));
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
testDisposables.add(testService.registerProvider(testDisposables.add(new SimpleTestProvider('testProvider'))));
const model = testDisposables.add(testService.startSession('testProvider', CancellationToken.None));
assert.strictEqual(model.getRequests().length, 0);
await assertSnapshot(model.toExport());
const response = await testService.sendRequest(model.sessionId, `@${chatAgentWithUsedContextId} test request`);
assert(response);
assert.strictEqual(model.getRequests().length, 1);
await assertSnapshot(model.toExport());
});
test('can deserialize', async () => {
let serializedChatData: ISerializableChatData;
testDisposables.add(chatAgentService.registerAgent(chatAgentWithUsedContext));
// create the first service, send request, get response, and serialize the state
{ // serapate block to not leak variables in outer scope
const testService = testDisposables.add(instantiationService.createInstance(ChatService));
testDisposables.add(testService.registerProvider(testDisposables.add(new SimpleTestProvider('testProvider'))));
const chatModel1 = testDisposables.add(testService.startSession('testProvider', CancellationToken.None));
assert.strictEqual(chatModel1.getRequests().length, 0);
const response = await testService.sendRequest(chatModel1.sessionId, `@${chatAgentWithUsedContextId} test request`);
assert(response);
await response.responseCompletePromise;
serializedChatData = chatModel1.toJSON();
}
// try deserializing the state into a new service
const testService2 = testDisposables.add(instantiationService.createInstance(ChatService));
testDisposables.add(testService2.registerProvider(testDisposables.add(new SimpleTestProvider('testProvider'))));
const chatModel2 = testService2.loadSessionFromContent(serializedChatData);
assert(chatModel2);
await assertSnapshot(chatModel2.toExport());
});
});
| src/vs/workbench/contrib/chat/test/common/chatService.test.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.000433658977271989,
0.00019203723059035838,
0.00016300336574204266,
0.00017386811668984592,
0.000053816464060219005
] |
{
"id": 5,
"code_window": [
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n",
"\n",
"\t\t// TODO@API\n",
"\t\t// clear NEVER happens\n",
"\t\t// onDidClearResult(value: TResult): void;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// BETTER\n",
"\t\t// requestResponseStream(callback: (stream: ChatAgentResponseStream) => void, why?: string): void;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 257
} | /*---------------------------------------------------------------------------------------------
* 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/timelinePane';
import { localize, localize2 } from 'vs/nls';
import * as DOM from 'vs/base/browser/dom';
import { IAction, ActionRunner } from 'vs/base/common/actions';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { fromNow } from 'vs/base/common/date';
import { debounce } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore, createMatches } from 'vs/base/common/filters';
import { Iterable } from 'vs/base/common/iterator';
import { DisposableStore, IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { ILabelService } from 'vs/platform/label/common/label';
import { escapeRegExpCharacters } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { IconLabel } from 'vs/base/browser/ui/iconLabel/iconLabel';
import { IListVirtualDelegate, IIdentityProvider, IKeyboardNavigationLabelProvider } from 'vs/base/browser/ui/list/list';
import { ITreeNode, ITreeRenderer, ITreeContextMenuEvent, ITreeElement } from 'vs/base/browser/ui/tree/tree';
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPane';
import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { ContextKeyExpr, IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ITimelineService, TimelineChangeEvent, TimelineItem, TimelineOptions, TimelineProvidersChangeEvent, TimelineRequest, Timeline } from 'vs/workbench/contrib/timeline/common/timeline';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { SideBySideEditor, EditorResourceAccessor } from 'vs/workbench/common/editor';
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ThemeIcon } from 'vs/base/common/themables';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { ActionBar, IActionViewItemProvider } from 'vs/base/browser/ui/actionbar/actionbar';
import { createAndFillInContextMenuActions, createActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IMenuService, MenuId, registerAction2, Action2, MenuRegistry } from 'vs/platform/actions/common/actions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems';
import { ColorScheme } from 'vs/platform/theme/common/theme';
import { Codicon } from 'vs/base/common/codicons';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { API_OPEN_DIFF_EDITOR_COMMAND_ID, API_OPEN_EDITOR_COMMAND_ID } from 'vs/workbench/browser/parts/editor/editorCommands';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import { isString } from 'vs/base/common/types';
import { renderMarkdownAsPlaintext } from 'vs/base/browser/markdownRenderer';
import { IHoverService } from 'vs/platform/hover/browser/hover';
import { IHoverDelegate, IHoverDelegateOptions } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { AriaRole } from 'vs/base/browser/ui/aria/aria';
import { ILocalizedString } from 'vs/platform/action/common/action';
const ItemHeight = 22;
type TreeElement = TimelineItem | LoadMoreCommand;
function isLoadMoreCommand(item: TreeElement | undefined): item is LoadMoreCommand {
return item instanceof LoadMoreCommand;
}
function isTimelineItem(item: TreeElement | undefined): item is TimelineItem {
return !item?.handle.startsWith('vscode-command:') ?? false;
}
function updateRelativeTime(item: TimelineItem, lastRelativeTime: string | undefined): string | undefined {
item.relativeTime = isTimelineItem(item) ? fromNow(item.timestamp) : undefined;
item.relativeTimeFullWord = isTimelineItem(item) ? fromNow(item.timestamp, false, true) : undefined;
if (lastRelativeTime === undefined || item.relativeTime !== lastRelativeTime) {
lastRelativeTime = item.relativeTime;
item.hideRelativeTime = false;
} else {
item.hideRelativeTime = true;
}
return lastRelativeTime;
}
interface TimelineActionContext {
uri: URI | undefined;
item: TreeElement;
}
class TimelineAggregate {
readonly items: TimelineItem[];
readonly source: string;
lastRenderedIndex: number;
constructor(timeline: Timeline) {
this.source = timeline.source;
this.items = timeline.items;
this._cursor = timeline.paging?.cursor;
this.lastRenderedIndex = -1;
}
private _cursor?: string;
get cursor(): string | undefined {
return this._cursor;
}
get more(): boolean {
return this._cursor !== undefined;
}
get newest(): TimelineItem | undefined {
return this.items[0];
}
get oldest(): TimelineItem | undefined {
return this.items[this.items.length - 1];
}
add(timeline: Timeline, options: TimelineOptions) {
let updated = false;
if (timeline.items.length !== 0 && this.items.length !== 0) {
updated = true;
const ids = new Set();
const timestamps = new Set();
for (const item of timeline.items) {
if (item.id === undefined) {
timestamps.add(item.timestamp);
}
else {
ids.add(item.id);
}
}
// Remove any duplicate items
let i = this.items.length;
let item;
while (i--) {
item = this.items[i];
if ((item.id !== undefined && ids.has(item.id)) || timestamps.has(item.timestamp)) {
this.items.splice(i, 1);
}
}
if ((timeline.items[timeline.items.length - 1]?.timestamp ?? 0) >= (this.newest?.timestamp ?? 0)) {
this.items.splice(0, 0, ...timeline.items);
} else {
this.items.push(...timeline.items);
}
} else if (timeline.items.length !== 0) {
updated = true;
this.items.push(...timeline.items);
}
// If we are not requesting more recent items than we have, then update the cursor
if (options.cursor !== undefined || typeof options.limit !== 'object') {
this._cursor = timeline.paging?.cursor;
}
if (updated) {
this.items.sort(
(a, b) =>
(b.timestamp - a.timestamp) ||
(a.source === undefined
? b.source === undefined ? 0 : 1
: b.source === undefined ? -1 : b.source.localeCompare(a.source, undefined, { numeric: true, sensitivity: 'base' }))
);
}
return updated;
}
private _stale = false;
get stale() {
return this._stale;
}
private _requiresReset = false;
get requiresReset(): boolean {
return this._requiresReset;
}
invalidate(requiresReset: boolean) {
this._stale = true;
this._requiresReset = requiresReset;
}
}
class LoadMoreCommand {
readonly handle = 'vscode-command:loadMore';
readonly timestamp = 0;
readonly description = undefined;
readonly tooltip = undefined;
readonly contextValue = undefined;
// Make things easier for duck typing
readonly id = undefined;
readonly icon = undefined;
readonly iconDark = undefined;
readonly source = undefined;
readonly relativeTime = undefined;
readonly relativeTimeFullWord = undefined;
readonly hideRelativeTime = undefined;
constructor(loading: boolean) {
this._loading = loading;
}
private _loading: boolean = false;
get loading(): boolean {
return this._loading;
}
set loading(value: boolean) {
this._loading = value;
}
get ariaLabel() {
return this.label;
}
get label() {
return this.loading ? localize('timeline.loadingMore', "Loading...") : localize('timeline.loadMore', "Load more");
}
get themeIcon(): ThemeIcon | undefined {
return undefined; //this.loading ? { id: 'sync~spin' } : undefined;
}
}
export const TimelineFollowActiveEditorContext = new RawContextKey<boolean>('timelineFollowActiveEditor', true, true);
export const TimelineExcludeSources = new RawContextKey<string>('timelineExcludeSources', '[]', true);
export class TimelinePane extends ViewPane {
static readonly TITLE: ILocalizedString = localize2('timeline', "Timeline");
private $container!: HTMLElement;
private $message!: HTMLDivElement;
private $tree!: HTMLDivElement;
private tree!: WorkbenchObjectTree<TreeElement, FuzzyScore>;
private treeRenderer: TimelineTreeRenderer | undefined;
private commands: TimelinePaneCommands;
private visibilityDisposables: DisposableStore | undefined;
private followActiveEditorContext: IContextKey<boolean>;
private timelineExcludeSourcesContext: IContextKey<string>;
private excludedSources: Set<string>;
private pendingRequests = new Map<string, TimelineRequest>();
private timelinesBySource = new Map<string, TimelineAggregate>();
private uri: URI | undefined;
constructor(
options: IViewPaneOptions,
@IKeybindingService keybindingService: IKeybindingService,
@IContextMenuService contextMenuService: IContextMenuService,
@IContextKeyService contextKeyService: IContextKeyService,
@IConfigurationService configurationService: IConfigurationService,
@IStorageService private readonly storageService: IStorageService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IInstantiationService instantiationService: IInstantiationService,
@IEditorService protected editorService: IEditorService,
@ICommandService protected commandService: ICommandService,
@IProgressService private readonly progressService: IProgressService,
@ITimelineService protected timelineService: ITimelineService,
@IOpenerService openerService: IOpenerService,
@IThemeService themeService: IThemeService,
@ITelemetryService telemetryService: ITelemetryService,
@ILabelService private readonly labelService: ILabelService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IExtensionService private readonly extensionService: IExtensionService,
) {
super({ ...options, titleMenuId: MenuId.TimelineTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.commands = this._register(this.instantiationService.createInstance(TimelinePaneCommands, this));
this.followActiveEditorContext = TimelineFollowActiveEditorContext.bindTo(this.contextKeyService);
this.timelineExcludeSourcesContext = TimelineExcludeSources.bindTo(this.contextKeyService);
const excludedSourcesString = storageService.get('timeline.excludeSources', StorageScope.PROFILE, '[]');
this.timelineExcludeSourcesContext.set(excludedSourcesString);
this.excludedSources = new Set(JSON.parse(excludedSourcesString));
this._register(storageService.onDidChangeValue(StorageScope.PROFILE, 'timeline.excludeSources', this._register(new DisposableStore()))(this.onStorageServiceChanged, this));
this._register(configurationService.onDidChangeConfiguration(this.onConfigurationChanged, this));
this._register(timelineService.onDidChangeProviders(this.onProvidersChanged, this));
this._register(timelineService.onDidChangeTimeline(this.onTimelineChanged, this));
this._register(timelineService.onDidChangeUri(uri => this.setUri(uri), this));
}
private _followActiveEditor: boolean = true;
get followActiveEditor(): boolean {
return this._followActiveEditor;
}
set followActiveEditor(value: boolean) {
if (this._followActiveEditor === value) {
return;
}
this._followActiveEditor = value;
this.followActiveEditorContext.set(value);
this.updateFilename(this._filename);
if (value) {
this.onActiveEditorChanged();
}
}
private _pageOnScroll: boolean | undefined;
get pageOnScroll() {
if (this._pageOnScroll === undefined) {
this._pageOnScroll = this.configurationService.getValue<boolean | null | undefined>('timeline.pageOnScroll') ?? false;
}
return this._pageOnScroll;
}
get pageSize() {
let pageSize = this.configurationService.getValue<number | null | undefined>('timeline.pageSize');
if (pageSize === undefined || pageSize === null) {
// If we are paging when scrolling, then add an extra item to the end to make sure the "Load more" item is out of view
pageSize = Math.max(20, Math.floor((this.tree?.renderHeight ?? 0 / ItemHeight) + (this.pageOnScroll ? 1 : -1)));
}
return pageSize;
}
reset() {
this.loadTimeline(true);
}
setUri(uri: URI) {
this.setUriCore(uri, true);
}
private setUriCore(uri: URI | undefined, disableFollowing: boolean) {
if (disableFollowing) {
this.followActiveEditor = false;
}
this.uri = uri;
this.updateFilename(uri ? this.labelService.getUriBasenameLabel(uri) : undefined);
this.treeRenderer?.setUri(uri);
this.loadTimeline(true);
}
private onStorageServiceChanged() {
const excludedSourcesString = this.storageService.get('timeline.excludeSources', StorageScope.PROFILE, '[]');
this.timelineExcludeSourcesContext.set(excludedSourcesString);
this.excludedSources = new Set(JSON.parse(excludedSourcesString));
const missing = this.timelineService.getSources()
.filter(({ id }) => !this.excludedSources.has(id) && !this.timelinesBySource.has(id));
if (missing.length !== 0) {
this.loadTimeline(true, missing.map(({ id }) => id));
} else {
this.refresh();
}
}
private onConfigurationChanged(e: IConfigurationChangeEvent) {
if (e.affectsConfiguration('timeline.pageOnScroll')) {
this._pageOnScroll = undefined;
}
}
private onActiveEditorChanged() {
if (!this.followActiveEditor || !this.isExpanded()) {
return;
}
const uri = EditorResourceAccessor.getOriginalUri(this.editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
if ((this.uriIdentityService.extUri.isEqual(uri, this.uri) && uri !== undefined) ||
// Fallback to match on fsPath if we are dealing with files or git schemes
(uri?.fsPath === this.uri?.fsPath && (uri?.scheme === Schemas.file || uri?.scheme === 'git') && (this.uri?.scheme === Schemas.file || this.uri?.scheme === 'git'))) {
// If the uri hasn't changed, make sure we have valid caches
for (const source of this.timelineService.getSources()) {
if (this.excludedSources.has(source.id)) {
continue;
}
const timeline = this.timelinesBySource.get(source.id);
if (timeline !== undefined && !timeline.stale) {
continue;
}
if (timeline !== undefined) {
this.updateTimeline(timeline, timeline.requiresReset);
} else {
this.loadTimelineForSource(source.id, uri, true);
}
}
return;
}
this.setUriCore(uri, false);
}
private onProvidersChanged(e: TimelineProvidersChangeEvent) {
if (e.removed) {
for (const source of e.removed) {
this.timelinesBySource.delete(source);
}
this.refresh();
}
if (e.added) {
this.loadTimeline(true, e.added);
}
}
private onTimelineChanged(e: TimelineChangeEvent) {
if (e?.uri === undefined || this.uriIdentityService.extUri.isEqual(e.uri, this.uri)) {
const timeline = this.timelinesBySource.get(e.id);
if (timeline === undefined) {
return;
}
if (this.isBodyVisible()) {
this.updateTimeline(timeline, e.reset);
} else {
timeline.invalidate(e.reset);
}
}
}
private _filename: string | undefined;
updateFilename(filename: string | undefined) {
this._filename = filename;
if (this.followActiveEditor || !filename) {
this.updateTitleDescription(filename);
} else {
this.updateTitleDescription(`${filename} (pinned)`);
}
}
private _message: string | undefined;
get message(): string | undefined {
return this._message;
}
set message(message: string | undefined) {
this._message = message;
this.updateMessage();
}
private updateMessage(): void {
if (this._message !== undefined) {
this.showMessage(this._message);
} else {
this.hideMessage();
}
}
private showMessage(message: string): void {
if (!this.$message) {
return;
}
this.$message.classList.remove('hide');
this.resetMessageElement();
this.$message.textContent = message;
}
private hideMessage(): void {
this.resetMessageElement();
this.$message.classList.add('hide');
}
private resetMessageElement(): void {
DOM.clearNode(this.$message);
}
private _isEmpty = true;
private _maxItemCount = 0;
private _visibleItemCount = 0;
private get hasVisibleItems() {
return this._visibleItemCount > 0;
}
private clear(cancelPending: boolean) {
this._visibleItemCount = 0;
this._maxItemCount = this.pageSize;
this.timelinesBySource.clear();
if (cancelPending) {
for (const { tokenSource } of this.pendingRequests.values()) {
tokenSource.dispose(true);
}
this.pendingRequests.clear();
if (!this.isBodyVisible() && this.tree) {
this.tree.setChildren(null, undefined);
this._isEmpty = true;
}
}
}
private async loadTimeline(reset: boolean, sources?: string[]) {
// If we have no source, we are resetting all sources, so cancel everything in flight and reset caches
if (sources === undefined) {
if (reset) {
this.clear(true);
}
// TODO@eamodio: Are these the right the list of schemes to exclude? Is there a better way?
if (this.uri?.scheme === Schemas.vscodeSettings || this.uri?.scheme === Schemas.webviewPanel || this.uri?.scheme === Schemas.walkThrough) {
this.uri = undefined;
this.clear(false);
this.refresh();
return;
}
if (this._isEmpty && this.uri !== undefined) {
this.setLoadingUriMessage();
}
}
if (this.uri === undefined) {
this.clear(false);
this.refresh();
return;
}
if (!this.isBodyVisible()) {
return;
}
let hasPendingRequests = false;
for (const source of sources ?? this.timelineService.getSources().map(s => s.id)) {
const requested = this.loadTimelineForSource(source, this.uri, reset);
if (requested) {
hasPendingRequests = true;
}
}
if (!hasPendingRequests) {
this.refresh();
} else if (this._isEmpty) {
this.setLoadingUriMessage();
}
}
private loadTimelineForSource(source: string, uri: URI, reset: boolean, options?: TimelineOptions) {
if (this.excludedSources.has(source)) {
return false;
}
const timeline = this.timelinesBySource.get(source);
// If we are paging, and there are no more items or we have enough cached items to cover the next page,
// don't bother querying for more
if (
!reset &&
options?.cursor !== undefined &&
timeline !== undefined &&
(!timeline?.more || timeline.items.length > timeline.lastRenderedIndex + this.pageSize)
) {
return false;
}
if (options === undefined) {
options = { cursor: reset ? undefined : timeline?.cursor, limit: this.pageSize };
}
let request = this.pendingRequests.get(source);
if (request !== undefined) {
options.cursor = request.options.cursor;
// TODO@eamodio deal with concurrent requests better
if (typeof options.limit === 'number') {
if (typeof request.options.limit === 'number') {
options.limit += request.options.limit;
} else {
options.limit = request.options.limit;
}
}
}
request?.tokenSource.dispose(true);
options.cacheResults = true;
options.resetCache = reset;
request = this.timelineService.getTimeline(
source, uri, options, new CancellationTokenSource()
);
if (request === undefined) {
return false;
}
this.pendingRequests.set(source, request);
request.tokenSource.token.onCancellationRequested(() => this.pendingRequests.delete(source));
this.handleRequest(request);
return true;
}
private updateTimeline(timeline: TimelineAggregate, reset: boolean) {
if (reset) {
this.timelinesBySource.delete(timeline.source);
// Override the limit, to re-query for all our existing cached (possibly visible) items to keep visual continuity
const { oldest } = timeline;
this.loadTimelineForSource(timeline.source, this.uri!, true, oldest !== undefined ? { limit: { timestamp: oldest.timestamp, id: oldest.id } } : undefined);
} else {
// Override the limit, to query for any newer items
const { newest } = timeline;
this.loadTimelineForSource(timeline.source, this.uri!, false, newest !== undefined ? { limit: { timestamp: newest.timestamp, id: newest.id } } : { limit: this.pageSize });
}
}
private _pendingRefresh = false;
private async handleRequest(request: TimelineRequest) {
let response: Timeline | undefined;
try {
response = await this.progressService.withProgress({ location: this.id }, () => request.result);
}
finally {
this.pendingRequests.delete(request.source);
}
if (
response === undefined ||
request.tokenSource.token.isCancellationRequested ||
request.uri !== this.uri
) {
if (this.pendingRequests.size === 0 && this._pendingRefresh) {
this.refresh();
}
return;
}
const source = request.source;
let updated = false;
const timeline = this.timelinesBySource.get(source);
if (timeline === undefined) {
this.timelinesBySource.set(source, new TimelineAggregate(response));
updated = true;
}
else {
updated = timeline.add(response, request.options);
}
if (updated) {
this._pendingRefresh = true;
// If we have visible items already and there are other pending requests, debounce for a bit to wait for other requests
if (this.hasVisibleItems && this.pendingRequests.size !== 0) {
this.refreshDebounced();
} else {
this.refresh();
}
} else if (this.pendingRequests.size === 0) {
if (this._pendingRefresh) {
this.refresh();
} else {
this.tree.rerender();
}
}
}
private *getItems(): Generator<ITreeElement<TreeElement>, any, any> {
let more = false;
if (this.uri === undefined || this.timelinesBySource.size === 0) {
this._visibleItemCount = 0;
return;
}
const maxCount = this._maxItemCount;
let count = 0;
if (this.timelinesBySource.size === 1) {
const [source, timeline] = Iterable.first(this.timelinesBySource)!;
timeline.lastRenderedIndex = -1;
if (this.excludedSources.has(source)) {
this._visibleItemCount = 0;
return;
}
if (timeline.items.length !== 0) {
// If we have any items, just say we have one for now -- the real count will be updated below
this._visibleItemCount = 1;
}
more = timeline.more;
let lastRelativeTime: string | undefined;
for (const item of timeline.items) {
item.relativeTime = undefined;
item.hideRelativeTime = undefined;
count++;
if (count > maxCount) {
more = true;
break;
}
lastRelativeTime = updateRelativeTime(item, lastRelativeTime);
yield { element: item };
}
timeline.lastRenderedIndex = count - 1;
}
else {
const sources: { timeline: TimelineAggregate; iterator: IterableIterator<TimelineItem>; nextItem: IteratorResult<TimelineItem, TimelineItem> }[] = [];
let hasAnyItems = false;
let mostRecentEnd = 0;
for (const [source, timeline] of this.timelinesBySource) {
timeline.lastRenderedIndex = -1;
if (this.excludedSources.has(source) || timeline.stale) {
continue;
}
if (timeline.items.length !== 0) {
hasAnyItems = true;
}
if (timeline.more) {
more = true;
const last = timeline.items[Math.min(maxCount, timeline.items.length - 1)];
if (last.timestamp > mostRecentEnd) {
mostRecentEnd = last.timestamp;
}
}
const iterator = timeline.items[Symbol.iterator]();
sources.push({ timeline: timeline, iterator: iterator, nextItem: iterator.next() });
}
this._visibleItemCount = hasAnyItems ? 1 : 0;
function getNextMostRecentSource() {
return sources
.filter(source => !source.nextItem.done)
.reduce((previous, current) => (previous === undefined || current.nextItem.value.timestamp >= previous.nextItem.value.timestamp) ? current : previous, undefined!);
}
let lastRelativeTime: string | undefined;
let nextSource;
while (nextSource = getNextMostRecentSource()) {
nextSource.timeline.lastRenderedIndex++;
const item = nextSource.nextItem.value;
item.relativeTime = undefined;
item.hideRelativeTime = undefined;
if (item.timestamp >= mostRecentEnd) {
count++;
if (count > maxCount) {
more = true;
break;
}
lastRelativeTime = updateRelativeTime(item, lastRelativeTime);
yield { element: item };
}
nextSource.nextItem = nextSource.iterator.next();
}
}
this._visibleItemCount = count;
if (count > 0) {
if (more) {
yield {
element: new LoadMoreCommand(this.pendingRequests.size !== 0)
};
} else if (this.pendingRequests.size !== 0) {
yield {
element: new LoadMoreCommand(true)
};
}
}
}
private refresh() {
if (!this.isBodyVisible()) {
return;
}
this.tree.setChildren(null, this.getItems() as any);
this._isEmpty = !this.hasVisibleItems;
if (this.uri === undefined) {
this.updateFilename(undefined);
this.message = localize('timeline.editorCannotProvideTimeline', "The active editor cannot provide timeline information.");
} else if (this._isEmpty) {
if (this.pendingRequests.size !== 0) {
this.setLoadingUriMessage();
} else {
this.updateFilename(this.labelService.getUriBasenameLabel(this.uri));
const scmProviderCount = this.contextKeyService.getContextKeyValue<number>('scm.providerCount');
if (this.timelineService.getSources().filter(({ id }) => !this.excludedSources.has(id)).length === 0) {
this.message = localize('timeline.noTimelineSourcesEnabled', "All timeline sources have been filtered out.");
} else {
if (this.configurationService.getValue('workbench.localHistory.enabled') && !this.excludedSources.has('timeline.localHistory')) {
this.message = localize('timeline.noLocalHistoryYet', "Local History will track recent changes as you save them unless the file has been excluded or is too large.");
} else if (this.excludedSources.size > 0) {
this.message = localize('timeline.noTimelineInfoFromEnabledSources', "No filtered timeline information was provided.");
} else {
this.message = localize('timeline.noTimelineInfo', "No timeline information was provided.");
}
}
if (!scmProviderCount || scmProviderCount === 0) {
this.message += ' ' + localize('timeline.noSCM', "Source Control has not been configured.");
}
}
} else {
this.updateFilename(this.labelService.getUriBasenameLabel(this.uri));
this.message = undefined;
}
this._pendingRefresh = false;
}
@debounce(500)
private refreshDebounced() {
this.refresh();
}
override focus(): void {
super.focus();
this.tree.domFocus();
}
override setExpanded(expanded: boolean): boolean {
const changed = super.setExpanded(expanded);
if (changed && this.isBodyVisible()) {
if (!this.followActiveEditor) {
this.setUriCore(this.uri, true);
} else {
this.onActiveEditorChanged();
}
}
return changed;
}
override setVisible(visible: boolean): void {
if (visible) {
this.extensionService.activateByEvent('onView:timeline');
this.visibilityDisposables = new DisposableStore();
this.editorService.onDidActiveEditorChange(this.onActiveEditorChanged, this, this.visibilityDisposables);
// Refresh the view on focus to update the relative timestamps
this.onDidFocus(() => this.refreshDebounced(), this, this.visibilityDisposables);
super.setVisible(visible);
this.onActiveEditorChanged();
} else {
this.visibilityDisposables?.dispose();
super.setVisible(visible);
}
}
protected override layoutBody(height: number, width: number): void {
super.layoutBody(height, width);
this.tree.layout(height, width);
}
protected override renderHeaderTitle(container: HTMLElement): void {
super.renderHeaderTitle(container, this.title);
container.classList.add('timeline-view');
}
protected override renderBody(container: HTMLElement): void {
super.renderBody(container);
this.$container = container;
container.classList.add('tree-explorer-viewlet-tree-view', 'timeline-tree-view');
this.$message = DOM.append(this.$container, DOM.$('.message'));
this.$message.classList.add('timeline-subtle');
this.message = localize('timeline.editorCannotProvideTimeline', "The active editor cannot provide timeline information.");
this.$tree = document.createElement('div');
this.$tree.classList.add('customview-tree', 'file-icon-themable-tree', 'hide-arrows');
// this.treeElement.classList.add('show-file-icons');
container.appendChild(this.$tree);
this.treeRenderer = this.instantiationService.createInstance(TimelineTreeRenderer, this.commands);
this.treeRenderer.onDidScrollToEnd(item => {
if (this.pageOnScroll) {
this.loadMore(item);
}
});
this.tree = <WorkbenchObjectTree<TreeElement, FuzzyScore>>this.instantiationService.createInstance(WorkbenchObjectTree, 'TimelinePane',
this.$tree, new TimelineListVirtualDelegate(), [this.treeRenderer], {
identityProvider: new TimelineIdentityProvider(),
accessibilityProvider: {
getAriaLabel(element: TreeElement): string {
if (isLoadMoreCommand(element)) {
return element.ariaLabel;
}
return element.accessibilityInformation ? element.accessibilityInformation.label : localize('timeline.aria.item', "{0}: {1}", element.relativeTimeFullWord ?? '', element.label);
},
getRole(element: TreeElement): AriaRole {
if (isLoadMoreCommand(element)) {
return 'treeitem';
}
return element.accessibilityInformation && element.accessibilityInformation.role ? element.accessibilityInformation.role : 'treeitem';
},
getWidgetAriaLabel(): string {
return localize('timeline', "Timeline");
}
},
keyboardNavigationLabelProvider: new TimelineKeyboardNavigationLabelProvider(),
multipleSelectionSupport: false,
overrideStyles: {
listBackground: this.getBackgroundColor()
}
});
this._register(this.tree.onContextMenu(e => this.onContextMenu(this.commands, e)));
this._register(this.tree.onDidChangeSelection(e => this.ensureValidItems()));
this._register(this.tree.onDidOpen(e => {
if (!e.browserEvent || !this.ensureValidItems()) {
return;
}
const selection = this.tree.getSelection();
let item;
if (selection.length === 1) {
item = selection[0];
}
if (item === null) {
return;
}
if (isTimelineItem(item)) {
if (item.command) {
let args = item.command.arguments ?? [];
if (item.command.id === API_OPEN_EDITOR_COMMAND_ID || item.command.id === API_OPEN_DIFF_EDITOR_COMMAND_ID) {
// Some commands owned by us should receive the
// `IOpenEvent` as context to open properly
args = [...args, e];
}
this.commandService.executeCommand(item.command.id, ...args);
}
}
else if (isLoadMoreCommand(item)) {
this.loadMore(item);
}
}));
}
private loadMore(item: LoadMoreCommand) {
if (item.loading) {
return;
}
item.loading = true;
this.tree.rerender(item);
if (this.pendingRequests.size !== 0) {
return;
}
this._maxItemCount = this._visibleItemCount + this.pageSize;
this.loadTimeline(false);
}
ensureValidItems() {
// If we don't have any non-excluded timelines, clear the tree and show the loading message
if (!this.hasVisibleItems || !this.timelineService.getSources().some(({ id }) => !this.excludedSources.has(id) && this.timelinesBySource.has(id))) {
this.tree.setChildren(null, undefined);
this._isEmpty = true;
this.setLoadingUriMessage();
return false;
}
return true;
}
setLoadingUriMessage() {
const file = this.uri && this.labelService.getUriBasenameLabel(this.uri);
this.updateFilename(file);
this.message = file ? localize('timeline.loading', "Loading timeline for {0}...", file) : '';
}
private onContextMenu(commands: TimelinePaneCommands, treeEvent: ITreeContextMenuEvent<TreeElement | null>): void {
const item = treeEvent.element;
if (item === null) {
return;
}
const event: UIEvent = treeEvent.browserEvent;
event.preventDefault();
event.stopPropagation();
if (!this.ensureValidItems()) {
return;
}
this.tree.setFocus([item]);
const actions = commands.getItemContextActions(item);
if (!actions.length) {
return;
}
this.contextMenuService.showContextMenu({
getAnchor: () => treeEvent.anchor,
getActions: () => actions,
getActionViewItem: (action) => {
const keybinding = this.keybindingService.lookupKeybinding(action.id);
if (keybinding) {
return new ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel() });
}
return undefined;
},
onHide: (wasCancelled?: boolean) => {
if (wasCancelled) {
this.tree.domFocus();
}
},
getActionsContext: (): TimelineActionContext => ({ uri: this.uri, item: item }),
actionRunner: new TimelineActionRunner()
});
}
}
class TimelineElementTemplate implements IDisposable {
static readonly id = 'TimelineElementTemplate';
readonly actionBar: ActionBar;
readonly icon: HTMLElement;
readonly iconLabel: IconLabel;
readonly timestamp: HTMLSpanElement;
constructor(
container: HTMLElement,
actionViewItemProvider: IActionViewItemProvider,
hoverDelegate: IHoverDelegate,
) {
container.classList.add('custom-view-tree-node-item');
this.icon = DOM.append(container, DOM.$('.custom-view-tree-node-item-icon'));
this.iconLabel = new IconLabel(container, { supportHighlights: true, supportIcons: true, hoverDelegate: hoverDelegate });
const timestampContainer = DOM.append(this.iconLabel.element, DOM.$('.timeline-timestamp-container'));
this.timestamp = DOM.append(timestampContainer, DOM.$('span.timeline-timestamp'));
const actionsContainer = DOM.append(this.iconLabel.element, DOM.$('.actions'));
this.actionBar = new ActionBar(actionsContainer, { actionViewItemProvider: actionViewItemProvider });
}
dispose() {
this.iconLabel.dispose();
this.actionBar.dispose();
}
reset() {
this.icon.className = '';
this.icon.style.backgroundImage = '';
this.actionBar.clear();
}
}
export class TimelineIdentityProvider implements IIdentityProvider<TreeElement> {
getId(item: TreeElement): { toString(): string } {
return item.handle;
}
}
class TimelineActionRunner extends ActionRunner {
protected override async runAction(action: IAction, { uri, item }: TimelineActionContext): Promise<void> {
if (!isTimelineItem(item)) {
// TODO@eamodio do we need to do anything else?
await action.run();
return;
}
await action.run(
{
$mid: MarshalledId.TimelineActionContext,
handle: item.handle,
source: item.source,
uri: uri
},
uri,
item.source,
);
}
}
export class TimelineKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<TreeElement> {
getKeyboardNavigationLabel(element: TreeElement): { toString(): string } {
return element.label;
}
}
export class TimelineListVirtualDelegate implements IListVirtualDelegate<TreeElement> {
getHeight(_element: TreeElement): number {
return ItemHeight;
}
getTemplateId(element: TreeElement): string {
return TimelineElementTemplate.id;
}
}
class TimelineTreeRenderer implements ITreeRenderer<TreeElement, FuzzyScore, TimelineElementTemplate> {
private readonly _onDidScrollToEnd = new Emitter<LoadMoreCommand>();
readonly onDidScrollToEnd: Event<LoadMoreCommand> = this._onDidScrollToEnd.event;
readonly templateId: string = TimelineElementTemplate.id;
private _hoverDelegate: IHoverDelegate;
private actionViewItemProvider: IActionViewItemProvider;
constructor(
private readonly commands: TimelinePaneCommands,
@IInstantiationService protected readonly instantiationService: IInstantiationService,
@IThemeService private themeService: IThemeService,
@IHoverService private readonly hoverService: IHoverService,
@IConfigurationService private readonly configurationService: IConfigurationService,
) {
this.actionViewItemProvider = createActionViewItem.bind(undefined, this.instantiationService);
this._hoverDelegate = {
showHover: (options: IHoverDelegateOptions) => this.hoverService.showHover(options),
delay: <number>this.configurationService.getValue('workbench.hover.delay')
};
}
private uri: URI | undefined;
setUri(uri: URI | undefined) {
this.uri = uri;
}
renderTemplate(container: HTMLElement): TimelineElementTemplate {
return new TimelineElementTemplate(container, this.actionViewItemProvider, this._hoverDelegate);
}
renderElement(
node: ITreeNode<TreeElement, FuzzyScore>,
index: number,
template: TimelineElementTemplate,
height: number | undefined
): void {
template.reset();
const { element: item } = node;
const theme = this.themeService.getColorTheme();
const icon = theme.type === ColorScheme.LIGHT ? item.icon : item.iconDark;
const iconUrl = icon ? URI.revive(icon) : null;
if (iconUrl) {
template.icon.className = 'custom-view-tree-node-item-icon';
template.icon.style.backgroundImage = DOM.asCSSUrl(iconUrl);
template.icon.style.color = '';
} else if (item.themeIcon) {
template.icon.className = `custom-view-tree-node-item-icon ${ThemeIcon.asClassName(item.themeIcon)}`;
if (item.themeIcon.color) {
template.icon.style.color = theme.getColor(item.themeIcon.color.id)?.toString() ?? '';
} else {
template.icon.style.color = '';
}
template.icon.style.backgroundImage = '';
} else {
template.icon.className = 'custom-view-tree-node-item-icon';
template.icon.style.backgroundImage = '';
template.icon.style.color = '';
}
const tooltip = item.tooltip
? isString(item.tooltip)
? item.tooltip
: { markdown: item.tooltip, markdownNotSupportedFallback: renderMarkdownAsPlaintext(item.tooltip) }
: undefined;
template.iconLabel.setLabel(item.label, item.description, {
title: tooltip,
matches: createMatches(node.filterData)
});
template.timestamp.textContent = item.relativeTime ?? '';
template.timestamp.ariaLabel = item.relativeTimeFullWord ?? '';
template.timestamp.parentElement!.classList.toggle('timeline-timestamp--duplicate', isTimelineItem(item) && item.hideRelativeTime);
template.actionBar.context = { uri: this.uri, item: item } as TimelineActionContext;
template.actionBar.actionRunner = new TimelineActionRunner();
template.actionBar.push(this.commands.getItemActions(item), { icon: true, label: false });
// If we are rendering the load more item, we've scrolled to the end, so trigger an event
if (isLoadMoreCommand(item)) {
setTimeout(() => this._onDidScrollToEnd.fire(item), 0);
}
}
disposeTemplate(template: TimelineElementTemplate): void {
template.dispose();
}
}
const timelineRefresh = registerIcon('timeline-refresh', Codicon.refresh, localize('timelineRefresh', 'Icon for the refresh timeline action.'));
const timelinePin = registerIcon('timeline-pin', Codicon.pin, localize('timelinePin', 'Icon for the pin timeline action.'));
const timelineUnpin = registerIcon('timeline-unpin', Codicon.pinned, localize('timelineUnpin', 'Icon for the unpin timeline action.'));
class TimelinePaneCommands extends Disposable {
private sourceDisposables: DisposableStore;
constructor(
private readonly pane: TimelinePane,
@ITimelineService private readonly timelineService: ITimelineService,
@IStorageService private readonly storageService: IStorageService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IMenuService private readonly menuService: IMenuService,
) {
super();
this._register(this.sourceDisposables = new DisposableStore());
this._register(registerAction2(class extends Action2 {
constructor() {
super({
id: 'timeline.refresh',
title: localize2('refresh', "Refresh"),
icon: timelineRefresh,
category: localize2('timeline', "Timeline"),
menu: {
id: MenuId.TimelineTitle,
group: 'navigation',
order: 99,
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
pane.reset();
}
}));
this._register(CommandsRegistry.registerCommand('timeline.toggleFollowActiveEditor',
(accessor: ServicesAccessor, ...args: any[]) => pane.followActiveEditor = !pane.followActiveEditor
));
this._register(MenuRegistry.appendMenuItem(MenuId.TimelineTitle, ({
command: {
id: 'timeline.toggleFollowActiveEditor',
title: localize2('timeline.toggleFollowActiveEditorCommand.follow', 'Pin the Current Timeline'),
icon: timelinePin,
category: localize2('timeline', "Timeline"),
},
group: 'navigation',
order: 98,
when: TimelineFollowActiveEditorContext
})));
this._register(MenuRegistry.appendMenuItem(MenuId.TimelineTitle, ({
command: {
id: 'timeline.toggleFollowActiveEditor',
title: localize2('timeline.toggleFollowActiveEditorCommand.unfollow', 'Unpin the Current Timeline'),
icon: timelineUnpin,
category: localize2('timeline', "Timeline"),
},
group: 'navigation',
order: 98,
when: TimelineFollowActiveEditorContext.toNegated()
})));
this._register(timelineService.onDidChangeProviders(() => this.updateTimelineSourceFilters()));
this.updateTimelineSourceFilters();
}
getItemActions(element: TreeElement): IAction[] {
return this.getActions(MenuId.TimelineItemContext, { key: 'timelineItem', value: element.contextValue }).primary;
}
getItemContextActions(element: TreeElement): IAction[] {
return this.getActions(MenuId.TimelineItemContext, { key: 'timelineItem', value: element.contextValue }).secondary;
}
private getActions(menuId: MenuId, context: { key: string; value?: string }): { primary: IAction[]; secondary: IAction[] } {
const contextKeyService = this.contextKeyService.createOverlay([
['view', this.pane.id],
[context.key, context.value],
]);
const menu = this.menuService.createMenu(menuId, contextKeyService);
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInContextMenuActions(menu, { shouldForwardArgs: true }, result, 'inline');
menu.dispose();
return result;
}
private updateTimelineSourceFilters() {
this.sourceDisposables.clear();
const excluded = new Set(JSON.parse(this.storageService.get('timeline.excludeSources', StorageScope.PROFILE, '[]')));
for (const source of this.timelineService.getSources()) {
this.sourceDisposables.add(registerAction2(class extends Action2 {
constructor() {
super({
id: `timeline.toggleExcludeSource:${source.id}`,
title: source.label,
menu: {
id: MenuId.TimelineFilterSubMenu,
group: 'navigation',
},
toggled: ContextKeyExpr.regex(`timelineExcludeSources`, new RegExp(`\\b${escapeRegExpCharacters(source.id)}\\b`)).negate()
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
if (excluded.has(source.id)) {
excluded.delete(source.id);
} else {
excluded.add(source.id);
}
const storageService = accessor.get(IStorageService);
storageService.store('timeline.excludeSources', JSON.stringify([...excluded.keys()]), StorageScope.PROFILE, StorageTarget.USER);
}
}));
}
}
}
| src/vs/workbench/contrib/timeline/browser/timelinePane.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0007925957906991243,
0.000178799222339876,
0.00016363858594559133,
0.00016945114475674927,
0.00006471618689829484
] |
{
"id": 5,
"code_window": [
"\t\t// notify(request: ChatResponsePart, reference: string): boolean;\n",
"\n",
"\t\t// TODO@API\n",
"\t\t// clear NEVER happens\n",
"\t\t// onDidClearResult(value: TResult): void;\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t// BETTER\n",
"\t\t// requestResponseStream(callback: (stream: ChatAgentResponseStream) => void, why?: string): void;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 257
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .quick-input-list .quick-input-list-entry.has-actions:hover .quick-input-list-entry-action-bar .action-label.dirty-workspace::before {
content: "\ea76"; /* Close icon flips between black dot and "X" for dirty workspaces */
}
.monaco-workbench .screencast-mouse {
position: absolute;
border-width: 2px;
border-style: solid;
border-radius: 50%;
z-index: 100000;
content: ' ';
pointer-events: none;
display: none;
}
.monaco-workbench .screencast-keyboard {
position: absolute;
background-color: rgba(0, 0, 0 ,0.5);
width: 100%;
left: 0;
z-index: 100000;
pointer-events: none;
color: #eee;
line-height: 1.75em;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.monaco-workbench:not(.reduce-motion) .screencast-keyboard {
transition: opacity 0.3s ease-out;
}
.monaco-workbench .screencast-keyboard:empty {
opacity: 0;
}
.monaco-workbench .screencast-keyboard > .key {
padding: 0 8px;
box-shadow: inset 0 -3px 0 hsla(0,0%,73%,.4);
margin-right: 6px;
border: 1px solid hsla(0,0%,80%,.4);
border-radius: 5px;
background-color: rgba(255, 255, 255, 0.05);
}
.monaco-workbench .screencast-keyboard > .title {
font-weight: 600;
}
| src/vs/workbench/browser/actions/media/actions.css | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017403563833795488,
0.00017111616034526378,
0.0001688245974946767,
0.00017113133799284697,
0.0000017961358480533818
] |
{
"id": 6,
"code_window": [
"\t\tdocuments: ChatAgentDocumentContext[];\n",
"\t}\n",
"\n",
"\texport type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;\n",
"\n",
"\texport namespace chat {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API Remove a different type of `request` so that they can\n",
"\t// evolve at their own pace\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 550
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.9984874725341797,
0.0349096953868866,
0.0001637470704736188,
0.0008225219789892435,
0.17594823241233826
] |
{
"id": 6,
"code_window": [
"\t\tdocuments: ChatAgentDocumentContext[];\n",
"\t}\n",
"\n",
"\texport type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;\n",
"\n",
"\texport namespace chat {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API Remove a different type of `request` so that they can\n",
"\t// evolve at their own pace\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 550
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { join } from 'path';
import { Application, StatusBarElement, Logger } from '../../../../automation';
import { installAllHandlers } from '../../utils';
export function setup(logger: Logger) {
describe('Statusbar', () => {
// Shared before/after handling
installAllHandlers(logger);
it('verifies presence of all default status bar elements', async function () {
const app = this.app as Application;
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.BRANCH_STATUS);
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.SYNC_STATUS);
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.PROBLEMS_STATUS);
await app.workbench.quickaccess.openFile(join(app.workspacePathOrFolder, 'readme.md'));
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.ENCODING_STATUS);
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.EOL_STATUS);
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.INDENTATION_STATUS);
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.LANGUAGE_STATUS);
await app.workbench.statusbar.waitForStatusbarElement(StatusBarElement.SELECTION_STATUS);
});
it(`verifies that 'quick input' opens when clicking on status bar elements`, async function () {
const app = this.app as Application;
await app.workbench.statusbar.clickOn(StatusBarElement.BRANCH_STATUS);
await app.workbench.quickinput.waitForQuickInputOpened();
await app.workbench.quickinput.closeQuickInput();
await app.workbench.quickaccess.openFile(join(app.workspacePathOrFolder, 'readme.md'));
await app.workbench.statusbar.clickOn(StatusBarElement.INDENTATION_STATUS);
await app.workbench.quickinput.waitForQuickInputOpened();
await app.workbench.quickinput.closeQuickInput();
await app.workbench.statusbar.clickOn(StatusBarElement.ENCODING_STATUS);
await app.workbench.quickinput.waitForQuickInputOpened();
await app.workbench.quickinput.closeQuickInput();
await app.workbench.statusbar.clickOn(StatusBarElement.EOL_STATUS);
await app.workbench.quickinput.waitForQuickInputOpened();
await app.workbench.quickinput.closeQuickInput();
await app.workbench.statusbar.clickOn(StatusBarElement.LANGUAGE_STATUS);
await app.workbench.quickinput.waitForQuickInputOpened();
await app.workbench.quickinput.closeQuickInput();
});
it(`verifies that 'Problems View' appears when clicking on 'Problems' status element`, async function () {
const app = this.app as Application;
await app.workbench.statusbar.clickOn(StatusBarElement.PROBLEMS_STATUS);
await app.workbench.problems.waitForProblemsView();
});
it(`verifies if changing EOL is reflected in the status bar`, async function () {
const app = this.app as Application;
await app.workbench.quickaccess.openFile(join(app.workspacePathOrFolder, 'readme.md'));
await app.workbench.statusbar.clickOn(StatusBarElement.EOL_STATUS);
await app.workbench.quickinput.selectQuickInputElement(1);
await app.workbench.statusbar.waitForEOL('CRLF');
});
});
}
| test/smoke/src/areas/statusbar/statusbar.test.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017655378906056285,
0.00016985574620775878,
0.0001629138714633882,
0.00016843434423208237,
0.000004602577973855659
] |
{
"id": 6,
"code_window": [
"\t\tdocuments: ChatAgentDocumentContext[];\n",
"\t}\n",
"\n",
"\texport type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;\n",
"\n",
"\texport namespace chat {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API Remove a different type of `request` so that they can\n",
"\t// evolve at their own pace\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 550
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { FileOperationError, FileOperationResult, IFileService } from 'vs/platform/files/common/files';
import { ILogService } from 'vs/platform/log/common/log';
import { IProfileResource, IProfileResourceChildTreeItem, IProfileResourceInitializer, IProfileResourceTreeItem, IUserDataProfileService } from 'vs/workbench/services/userDataProfile/common/userDataProfile';
import { platform, Platform } from 'vs/base/common/platform';
import { ITreeItemCheckboxState, TreeItemCollapsibleState } from 'vs/workbench/common/views';
import { IUserDataProfile, ProfileResourceType } from 'vs/platform/userDataProfile/common/userDataProfile';
import { API_OPEN_EDITOR_COMMAND_ID } from 'vs/workbench/browser/parts/editor/editorCommands';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { localize } from 'vs/nls';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
interface IKeybindingsResourceContent {
platform: Platform;
keybindings: string | null;
}
export class KeybindingsResourceInitializer implements IProfileResourceInitializer {
constructor(
@IUserDataProfileService private readonly userDataProfileService: IUserDataProfileService,
@IFileService private readonly fileService: IFileService,
@ILogService private readonly logService: ILogService,
) {
}
async initialize(content: string): Promise<void> {
const keybindingsContent: IKeybindingsResourceContent = JSON.parse(content);
if (keybindingsContent.keybindings === null) {
this.logService.info(`Initializing Profile: No keybindings to apply...`);
return;
}
await this.fileService.writeFile(this.userDataProfileService.currentProfile.keybindingsResource, VSBuffer.fromString(keybindingsContent.keybindings));
}
}
export class KeybindingsResource implements IProfileResource {
constructor(
@IFileService private readonly fileService: IFileService,
@ILogService private readonly logService: ILogService,
) {
}
async getContent(profile: IUserDataProfile): Promise<string> {
const keybindingsContent = await this.getKeybindingsResourceContent(profile);
return JSON.stringify(keybindingsContent);
}
async getKeybindingsResourceContent(profile: IUserDataProfile): Promise<IKeybindingsResourceContent> {
const keybindings = await this.getKeybindingsContent(profile);
return { keybindings, platform };
}
async apply(content: string, profile: IUserDataProfile): Promise<void> {
const keybindingsContent: IKeybindingsResourceContent = JSON.parse(content);
if (keybindingsContent.keybindings === null) {
this.logService.info(`Importing Profile (${profile.name}): No keybindings to apply...`);
return;
}
await this.fileService.writeFile(profile.keybindingsResource, VSBuffer.fromString(keybindingsContent.keybindings));
}
private async getKeybindingsContent(profile: IUserDataProfile): Promise<string | null> {
try {
const content = await this.fileService.readFile(profile.keybindingsResource);
return content.value.toString();
} catch (error) {
// File not found
if (error instanceof FileOperationError && error.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
return null;
} else {
throw error;
}
}
}
}
export class KeybindingsResourceTreeItem implements IProfileResourceTreeItem {
readonly type = ProfileResourceType.Keybindings;
readonly handle = ProfileResourceType.Keybindings;
readonly label = { label: localize('keybindings', "Keyboard Shortcuts") };
readonly collapsibleState = TreeItemCollapsibleState.Expanded;
checkbox: ITreeItemCheckboxState | undefined;
constructor(
private readonly profile: IUserDataProfile,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) { }
isFromDefaultProfile(): boolean {
return !this.profile.isDefault && !!this.profile.useDefaultFlags?.keybindings;
}
async getChildren(): Promise<IProfileResourceChildTreeItem[]> {
return [{
handle: this.profile.keybindingsResource.toString(),
resourceUri: this.profile.keybindingsResource,
collapsibleState: TreeItemCollapsibleState.None,
parent: this,
accessibilityInformation: {
label: this.uriIdentityService.extUri.basename(this.profile.settingsResource)
},
command: {
id: API_OPEN_EDITOR_COMMAND_ID,
title: '',
arguments: [this.profile.keybindingsResource, undefined, undefined]
}
}];
}
async hasContent(): Promise<boolean> {
const keybindingsContent = await this.instantiationService.createInstance(KeybindingsResource).getKeybindingsResourceContent(this.profile);
return keybindingsContent.keybindings !== null;
}
async getContent(): Promise<string> {
return this.instantiationService.createInstance(KeybindingsResource).getContent(this.profile);
}
}
| src/vs/workbench/services/userDataProfile/browser/keybindingsResource.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017638603458181024,
0.00017171142098959535,
0.00016617799701634794,
0.00017108471365645528,
0.000002972208449136815
] |
{
"id": 6,
"code_window": [
"\t\tdocuments: ChatAgentDocumentContext[];\n",
"\t}\n",
"\n",
"\texport type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;\n",
"\n",
"\texport namespace chat {\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API Remove a different type of `request` so that they can\n",
"\t// evolve at their own pace\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 550
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "marked",
"repositoryUrl": "https://github.com/markedjs/marked",
"commitHash": "7e2ef307846427650114591f9257b5545868e928"
}
},
"license": "MIT",
"version": "4.1.0"
}
],
"version": 1
}
| src/vs/base/common/marked/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017618382116779685,
0.0001759327860781923,
0.00017568175098858774,
0.0001759327860781923,
2.5103508960455656e-7
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\t/**\n",
"\t * The detail level of this chat variable value.\n",
"\t */\n",
"\texport enum ChatVariableLevel {\n",
"\t\tShort = 1,\n",
"\t\tMedium = 2,\n",
"\t\tFull = 3\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API maybe for round2\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 575
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.9991434812545776,
0.03336158022284508,
0.0001652065257076174,
0.0006085106870159507,
0.1762043833732605
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\t/**\n",
"\t * The detail level of this chat variable value.\n",
"\t */\n",
"\texport enum ChatVariableLevel {\n",
"\t\tShort = 1,\n",
"\t\tMedium = 2,\n",
"\t\tFull = 3\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API maybe for round2\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 575
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Disposable } from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { MainContext, ExtHostDocumentContentProvidersShape, MainThreadDocumentContentProvidersShape, IMainContext } from './extHost.protocol';
import { ExtHostDocumentsAndEditors } from './extHostDocumentsAndEditors';
import { Schemas } from 'vs/base/common/network';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { splitLines } from 'vs/base/common/strings';
export class ExtHostDocumentContentProvider implements ExtHostDocumentContentProvidersShape {
private static _handlePool = 0;
private readonly _documentContentProviders = new Map<number, vscode.TextDocumentContentProvider>();
private readonly _proxy: MainThreadDocumentContentProvidersShape;
constructor(
mainContext: IMainContext,
private readonly _documentsAndEditors: ExtHostDocumentsAndEditors,
private readonly _logService: ILogService,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadDocumentContentProviders);
}
registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider): vscode.Disposable {
// todo@remote
// check with scheme from fs-providers!
if (Object.keys(Schemas).indexOf(scheme) >= 0) {
throw new Error(`scheme '${scheme}' already registered`);
}
const handle = ExtHostDocumentContentProvider._handlePool++;
this._documentContentProviders.set(handle, provider);
this._proxy.$registerTextContentProvider(handle, scheme);
let subscription: IDisposable | undefined;
if (typeof provider.onDidChange === 'function') {
let lastEvent: Promise<void> | undefined;
subscription = provider.onDidChange(async uri => {
if (uri.scheme !== scheme) {
this._logService.warn(`Provider for scheme '${scheme}' is firing event for schema '${uri.scheme}' which will be IGNORED`);
return;
}
if (!this._documentsAndEditors.getDocument(uri)) {
// ignore event if document isn't open
return;
}
if (lastEvent) {
await lastEvent;
}
const thisEvent = this.$provideTextDocumentContent(handle, uri)
.then(async value => {
if (!value && typeof value !== 'string') {
return;
}
const document = this._documentsAndEditors.getDocument(uri);
if (!document) {
// disposed in the meantime
return;
}
// create lines and compare
const lines = splitLines(value);
// broadcast event when content changed
if (!document.equalLines(lines)) {
return this._proxy.$onVirtualDocumentChange(uri, value);
}
})
.catch(onUnexpectedError)
.finally(() => {
if (lastEvent === thisEvent) {
lastEvent = undefined;
}
});
lastEvent = thisEvent;
});
}
return new Disposable(() => {
if (this._documentContentProviders.delete(handle)) {
this._proxy.$unregisterTextContentProvider(handle);
}
if (subscription) {
subscription.dispose();
subscription = undefined;
}
});
}
$provideTextDocumentContent(handle: number, uri: UriComponents): Promise<string | null | undefined> {
const provider = this._documentContentProviders.get(handle);
if (!provider) {
return Promise.reject(new Error(`unsupported uri-scheme: ${uri.scheme}`));
}
return Promise.resolve(provider.provideTextDocumentContent(URI.revive(uri), CancellationToken.None));
}
}
| src/vs/workbench/api/common/extHostDocumentContentProviders.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0001760645827744156,
0.0001693697995506227,
0.00016528625565115362,
0.00016876599693205208,
0.0000033209967114089523
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\t/**\n",
"\t * The detail level of this chat variable value.\n",
"\t */\n",
"\texport enum ChatVariableLevel {\n",
"\t\tShort = 1,\n",
"\t\tMedium = 2,\n",
"\t\tFull = 3\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API maybe for round2\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 575
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('vscode-grammar-updater');
updateGrammar.update('jlelong/vscode-latex-basics', 'syntaxes/Bibtex.tmLanguage.json', 'syntaxes/Bibtex.tmLanguage.json', undefined, 'main');
updateGrammar.update('jlelong/vscode-latex-basics', 'syntaxes/LaTeX.tmLanguage.json', 'syntaxes/LaTeX.tmLanguage.json', undefined, 'main');
updateGrammar.update('jlelong/vscode-latex-basics', 'syntaxes/TeX.tmLanguage.json', 'syntaxes/TeX.tmLanguage.json', undefined, 'main');
updateGrammar.update('jlelong/vscode-latex-basics', 'syntaxes/cpp-grammar-bailout.tmLanguage.json', 'syntaxes/cpp-grammar-bailout.tmLanguage.json', undefined, 'main');
updateGrammar.update('jlelong/vscode-latex-basics', 'syntaxes/markdown-latex-combined.tmLanguage.json', 'syntaxes/markdown-latex-combined.tmLanguage.json', undefined, 'main');
| extensions/latex/build/update-grammars.js | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.000172161337104626,
0.00017086806474253535,
0.0001695747923804447,
0.00017086806474253535,
0.0000012932723620906472
] |
{
"id": 7,
"code_window": [
"\t}\n",
"\n",
"\t/**\n",
"\t * The detail level of this chat variable value.\n",
"\t */\n",
"\texport enum ChatVariableLevel {\n",
"\t\tShort = 1,\n",
"\t\tMedium = 2,\n",
"\t\tFull = 3\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t// TODO@API maybe for round2\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatAgents2.d.ts",
"type": "add",
"edit_start_line_idx": 575
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-grid-view {
position: relative;
overflow: hidden;
width: 100%;
height: 100%;
}
.monaco-grid-branch-node {
width: 100%;
height: 100%;
} | src/vs/base/browser/ui/grid/gridview.css | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017310254042968154,
0.0001727469207253307,
0.0001723913155728951,
0.0001727469207253307,
3.5561242839321494e-7
] |
{
"id": 8,
"code_window": [
"\t\t *\n",
"\t\t * @param messages\n",
"\t\t * @param options\n",
"\t\t */\n",
"\t\tmakeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n",
"\t}\n",
"\n",
"\texport interface LanguageModelAccessOptions {\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tmakeChatRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.01025596633553505,
0.0009023004095070064,
0.00016462251369375736,
0.000365306215826422,
0.001744543551467359
] |
{
"id": 8,
"code_window": [
"\t\t *\n",
"\t\t * @param messages\n",
"\t\t * @param options\n",
"\t\t */\n",
"\t\tmakeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n",
"\t}\n",
"\n",
"\texport interface LanguageModelAccessOptions {\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tmakeChatRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 51
} | {
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out",
"typeRoots": [
"node_modules/@types"
]
},
"include": [
"src/**/*",
"../../src/vscode-dts/vscode.d.ts"
]
}
| extensions/extension-editing/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0001755497942212969,
0.00017464414122514427,
0.00017373850278090686,
0.00017464414122514427,
9.056457201950252e-7
] |
{
"id": 8,
"code_window": [
"\t\t *\n",
"\t\t * @param messages\n",
"\t\t * @param options\n",
"\t\t */\n",
"\t\tmakeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n",
"\t}\n",
"\n",
"\texport interface LanguageModelAccessOptions {\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tmakeChatRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Delayer } from 'vs/base/common/async';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, EditorCommand, EditorContributionInstantiation, MultiEditorAction, registerEditorAction, registerEditorCommand, registerEditorContribution, registerMultiEditorAction, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { overviewRulerRangeHighlight } from 'vs/editor/common/core/editorColorRegistry';
import { IRange } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { OverviewRulerLane } from 'vs/editor/common/model';
import { CONTEXT_FIND_INPUT_FOCUSED, CONTEXT_FIND_WIDGET_VISIBLE, CONTEXT_REPLACE_INPUT_FOCUSED, FindModelBoundToEditorModel, FIND_IDS, ToggleCaseSensitiveKeybinding, TogglePreserveCaseKeybinding, ToggleRegexKeybinding, ToggleSearchScopeKeybinding, ToggleWholeWordKeybinding } from 'vs/editor/contrib/find/browser/findModel';
import { FindOptionsWidget } from 'vs/editor/contrib/find/browser/findOptionsWidget';
import { FindReplaceState, FindReplaceStateChangedEvent, INewFindReplaceState } from 'vs/editor/contrib/find/browser/findState';
import { FindWidget, IFindController } from 'vs/editor/contrib/find/browser/findWidget';
import * as nls from 'vs/nls';
import { MenuId } from 'vs/platform/actions/common/actions';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ContextKeyExpr, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IThemeService, themeColorFromId } from 'vs/platform/theme/common/themeService';
import { Selection } from 'vs/editor/common/core/selection';
const SEARCH_STRING_MAX_LENGTH = 524288;
export function getSelectionSearchString(editor: ICodeEditor, seedSearchStringFromSelection: 'single' | 'multiple' = 'single', seedSearchStringFromNonEmptySelection: boolean = false): string | null {
if (!editor.hasModel()) {
return null;
}
const selection = editor.getSelection();
// if selection spans multiple lines, default search string to empty
if ((seedSearchStringFromSelection === 'single' && selection.startLineNumber === selection.endLineNumber)
|| seedSearchStringFromSelection === 'multiple') {
if (selection.isEmpty()) {
const wordAtPosition = editor.getConfiguredWordAtPosition(selection.getStartPosition());
if (wordAtPosition && (false === seedSearchStringFromNonEmptySelection)) {
return wordAtPosition.word;
}
} else {
if (editor.getModel().getValueLengthInRange(selection) < SEARCH_STRING_MAX_LENGTH) {
return editor.getModel().getValueInRange(selection);
}
}
}
return null;
}
export const enum FindStartFocusAction {
NoFocusChange,
FocusFindInput,
FocusReplaceInput
}
export interface IFindStartOptions {
forceRevealReplace: boolean;
seedSearchStringFromSelection: 'none' | 'single' | 'multiple';
seedSearchStringFromNonEmptySelection: boolean;
seedSearchStringFromGlobalClipboard: boolean;
shouldFocus: FindStartFocusAction;
shouldAnimate: boolean;
updateSearchScope: boolean;
loop: boolean;
}
export interface IFindStartArguments {
searchString?: string;
replaceString?: string;
isRegex?: boolean;
matchWholeWord?: boolean;
isCaseSensitive?: boolean;
preserveCase?: boolean;
findInSelection?: boolean;
}
export class CommonFindController extends Disposable implements IEditorContribution {
public static readonly ID = 'editor.contrib.findController';
protected _editor: ICodeEditor;
private readonly _findWidgetVisible: IContextKey<boolean>;
protected _state: FindReplaceState;
protected _updateHistoryDelayer: Delayer<void>;
private _model: FindModelBoundToEditorModel | null;
protected readonly _storageService: IStorageService;
private readonly _clipboardService: IClipboardService;
protected readonly _contextKeyService: IContextKeyService;
protected readonly _notificationService: INotificationService;
get editor() {
return this._editor;
}
public static get(editor: ICodeEditor): CommonFindController | null {
return editor.getContribution<CommonFindController>(CommonFindController.ID);
}
constructor(
editor: ICodeEditor,
@IContextKeyService contextKeyService: IContextKeyService,
@IStorageService storageService: IStorageService,
@IClipboardService clipboardService: IClipboardService,
@INotificationService notificationService: INotificationService
) {
super();
this._editor = editor;
this._findWidgetVisible = CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
this._contextKeyService = contextKeyService;
this._storageService = storageService;
this._clipboardService = clipboardService;
this._notificationService = notificationService;
this._updateHistoryDelayer = new Delayer<void>(500);
this._state = this._register(new FindReplaceState());
this.loadQueryState();
this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
this._model = null;
this._register(this._editor.onDidChangeModel(() => {
const shouldRestartFind = (this._editor.getModel() && this._state.isRevealed);
this.disposeModel();
this._state.change({
searchScope: null,
matchCase: this._storageService.getBoolean('editor.matchCase', StorageScope.WORKSPACE, false),
wholeWord: this._storageService.getBoolean('editor.wholeWord', StorageScope.WORKSPACE, false),
isRegex: this._storageService.getBoolean('editor.isRegex', StorageScope.WORKSPACE, false),
preserveCase: this._storageService.getBoolean('editor.preserveCase', StorageScope.WORKSPACE, false)
}, false);
if (shouldRestartFind) {
this._start({
forceRevealReplace: false,
seedSearchStringFromSelection: 'none',
seedSearchStringFromNonEmptySelection: false,
seedSearchStringFromGlobalClipboard: false,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: false,
updateSearchScope: false,
loop: this._editor.getOption(EditorOption.find).loop
});
}
}));
}
public override dispose(): void {
this.disposeModel();
super.dispose();
}
private disposeModel(): void {
if (this._model) {
this._model.dispose();
this._model = null;
}
}
private _onStateChanged(e: FindReplaceStateChangedEvent): void {
this.saveQueryState(e);
if (e.isRevealed) {
if (this._state.isRevealed) {
this._findWidgetVisible.set(true);
} else {
this._findWidgetVisible.reset();
this.disposeModel();
}
}
if (e.searchString) {
this.setGlobalBufferTerm(this._state.searchString);
}
}
private saveQueryState(e: FindReplaceStateChangedEvent) {
if (e.isRegex) {
this._storageService.store('editor.isRegex', this._state.actualIsRegex, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
if (e.wholeWord) {
this._storageService.store('editor.wholeWord', this._state.actualWholeWord, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
if (e.matchCase) {
this._storageService.store('editor.matchCase', this._state.actualMatchCase, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
if (e.preserveCase) {
this._storageService.store('editor.preserveCase', this._state.actualPreserveCase, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
}
private loadQueryState() {
this._state.change({
matchCase: this._storageService.getBoolean('editor.matchCase', StorageScope.WORKSPACE, this._state.matchCase),
wholeWord: this._storageService.getBoolean('editor.wholeWord', StorageScope.WORKSPACE, this._state.wholeWord),
isRegex: this._storageService.getBoolean('editor.isRegex', StorageScope.WORKSPACE, this._state.isRegex),
preserveCase: this._storageService.getBoolean('editor.preserveCase', StorageScope.WORKSPACE, this._state.preserveCase)
}, false);
}
public isFindInputFocused(): boolean {
return !!CONTEXT_FIND_INPUT_FOCUSED.getValue(this._contextKeyService);
}
public getState(): FindReplaceState {
return this._state;
}
public closeFindWidget(): void {
this._state.change({
isRevealed: false,
searchScope: null
}, false);
this._editor.focus();
}
public toggleCaseSensitive(): void {
this._state.change({ matchCase: !this._state.matchCase }, false);
if (!this._state.isRevealed) {
this.highlightFindOptions();
}
}
public toggleWholeWords(): void {
this._state.change({ wholeWord: !this._state.wholeWord }, false);
if (!this._state.isRevealed) {
this.highlightFindOptions();
}
}
public toggleRegex(): void {
this._state.change({ isRegex: !this._state.isRegex }, false);
if (!this._state.isRevealed) {
this.highlightFindOptions();
}
}
public togglePreserveCase(): void {
this._state.change({ preserveCase: !this._state.preserveCase }, false);
if (!this._state.isRevealed) {
this.highlightFindOptions();
}
}
public toggleSearchScope(): void {
if (this._state.searchScope) {
this._state.change({ searchScope: null }, true);
} else {
if (this._editor.hasModel()) {
let selections = this._editor.getSelections();
selections = selections.map(selection => {
if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
selection = selection.setEndPosition(
selection.endLineNumber - 1,
this._editor.getModel()!.getLineMaxColumn(selection.endLineNumber - 1)
);
}
if (!selection.isEmpty()) {
return selection;
}
return null;
}).filter((element): element is Selection => !!element);
if (selections.length) {
this._state.change({ searchScope: selections }, true);
}
}
}
}
public setSearchString(searchString: string): void {
if (this._state.isRegex) {
searchString = strings.escapeRegExpCharacters(searchString);
}
this._state.change({ searchString: searchString }, false);
}
public highlightFindOptions(ignoreWhenVisible: boolean = false): void {
// overwritten in subclass
}
protected async _start(opts: IFindStartOptions, newState?: INewFindReplaceState): Promise<void> {
this.disposeModel();
if (!this._editor.hasModel()) {
// cannot do anything with an editor that doesn't have a model...
return;
}
const stateChanges: INewFindReplaceState = {
...newState,
isRevealed: true
};
if (opts.seedSearchStringFromSelection === 'single') {
const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
if (selectionSearchString) {
if (this._state.isRegex) {
stateChanges.searchString = strings.escapeRegExpCharacters(selectionSearchString);
} else {
stateChanges.searchString = selectionSearchString;
}
}
} else if (opts.seedSearchStringFromSelection === 'multiple' && !opts.updateSearchScope) {
const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection);
if (selectionSearchString) {
stateChanges.searchString = selectionSearchString;
}
}
if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
const selectionSearchString = await this.getGlobalBufferTerm();
if (!this._editor.hasModel()) {
// the editor has lost its model in the meantime
return;
}
if (selectionSearchString) {
stateChanges.searchString = selectionSearchString;
}
}
// Overwrite isReplaceRevealed
if (opts.forceRevealReplace || stateChanges.isReplaceRevealed) {
stateChanges.isReplaceRevealed = true;
} else if (!this._findWidgetVisible.get()) {
stateChanges.isReplaceRevealed = false;
}
if (opts.updateSearchScope) {
const currentSelections = this._editor.getSelections();
if (currentSelections.some(selection => !selection.isEmpty())) {
stateChanges.searchScope = currentSelections;
}
}
stateChanges.loop = opts.loop;
this._state.change(stateChanges, false);
if (!this._model) {
this._model = new FindModelBoundToEditorModel(this._editor, this._state);
}
}
public start(opts: IFindStartOptions, newState?: INewFindReplaceState): Promise<void> {
return this._start(opts, newState);
}
public moveToNextMatch(): boolean {
if (this._model) {
this._model.moveToNextMatch();
return true;
}
return false;
}
public moveToPrevMatch(): boolean {
if (this._model) {
this._model.moveToPrevMatch();
return true;
}
return false;
}
public goToMatch(index: number): boolean {
if (this._model) {
this._model.moveToMatch(index);
return true;
}
return false;
}
public replace(): boolean {
if (this._model) {
this._model.replace();
return true;
}
return false;
}
public replaceAll(): boolean {
if (this._model) {
if (this._editor.getModel()?.isTooLargeForHeapOperation()) {
this._notificationService.warn(nls.localize('too.large.for.replaceall', "The file is too large to perform a replace all operation."));
return false;
}
this._model.replaceAll();
return true;
}
return false;
}
public selectAllMatches(): boolean {
if (this._model) {
this._model.selectAllMatches();
this._editor.focus();
return true;
}
return false;
}
public async getGlobalBufferTerm(): Promise<string> {
if (this._editor.getOption(EditorOption.find).globalFindClipboard
&& this._editor.hasModel()
&& !this._editor.getModel().isTooLargeForSyncing()
) {
return this._clipboardService.readFindText();
}
return '';
}
public setGlobalBufferTerm(text: string): void {
if (this._editor.getOption(EditorOption.find).globalFindClipboard
&& this._editor.hasModel()
&& !this._editor.getModel().isTooLargeForSyncing()
) {
// intentionally not awaited
this._clipboardService.writeFindText(text);
}
}
}
export class FindController extends CommonFindController implements IFindController {
private _widget: FindWidget | null;
private _findOptionsWidget: FindOptionsWidget | null;
constructor(
editor: ICodeEditor,
@IContextViewService private readonly _contextViewService: IContextViewService,
@IContextKeyService _contextKeyService: IContextKeyService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@IThemeService private readonly _themeService: IThemeService,
@INotificationService notificationService: INotificationService,
@IStorageService _storageService: IStorageService,
@IClipboardService clipboardService: IClipboardService,
) {
super(editor, _contextKeyService, _storageService, clipboardService, notificationService);
this._widget = null;
this._findOptionsWidget = null;
}
protected override async _start(opts: IFindStartOptions, newState?: INewFindReplaceState): Promise<void> {
if (!this._widget) {
this._createFindWidget();
}
const selection = this._editor.getSelection();
let updateSearchScope = false;
switch (this._editor.getOption(EditorOption.find).autoFindInSelection) {
case 'always':
updateSearchScope = true;
break;
case 'never':
updateSearchScope = false;
break;
case 'multiline': {
const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
updateSearchScope = isSelectionMultipleLine;
break;
}
default:
break;
}
opts.updateSearchScope = opts.updateSearchScope || updateSearchScope;
await super._start(opts, newState);
if (this._widget) {
if (opts.shouldFocus === FindStartFocusAction.FocusReplaceInput) {
this._widget.focusReplaceInput();
} else if (opts.shouldFocus === FindStartFocusAction.FocusFindInput) {
this._widget.focusFindInput();
}
}
}
public override highlightFindOptions(ignoreWhenVisible: boolean = false): void {
if (!this._widget) {
this._createFindWidget();
}
if (this._state.isRevealed && !ignoreWhenVisible) {
this._widget!.highlightFindOptions();
} else {
this._findOptionsWidget!.highlightFindOptions();
}
}
private _createFindWidget() {
this._widget = this._register(new FindWidget(this._editor, this, this._state, this._contextViewService, this._keybindingService, this._contextKeyService, this._themeService, this._storageService, this._notificationService));
this._findOptionsWidget = this._register(new FindOptionsWidget(this._editor, this._state, this._keybindingService));
}
saveViewState(): any {
return this._widget?.getViewState();
}
restoreViewState(state: any): void {
this._widget?.setViewState(state);
}
}
export const StartFindAction = registerMultiEditorAction(new MultiEditorAction({
id: FIND_IDS.StartFindAction,
label: nls.localize('startFindAction', "Find"),
alias: 'Find',
precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has('editorIsOpen')),
kbOpts: {
kbExpr: null,
primary: KeyMod.CtrlCmd | KeyCode.KeyF,
weight: KeybindingWeight.EditorContrib
},
menuOpts: {
menuId: MenuId.MenubarEditMenu,
group: '3_find',
title: nls.localize({ key: 'miFind', comment: ['&& denotes a mnemonic'] }, "&&Find"),
order: 1
}
}));
StartFindAction.addImplementation(0, (accessor: ServicesAccessor, editor: ICodeEditor, args: any): boolean | Promise<void> => {
const controller = CommonFindController.get(editor);
if (!controller) {
return false;
}
return controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: editor.getOption(EditorOption.find).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(EditorOption.find).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: editor.getOption(EditorOption.find).globalFindClipboard,
shouldFocus: FindStartFocusAction.FocusFindInput,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(EditorOption.find).loop
});
});
const findArgDescription = {
description: 'Open a new In-Editor Find Widget.',
args: [{
name: 'Open a new In-Editor Find Widget args',
schema: {
properties: {
searchString: { type: 'string' },
replaceString: { type: 'string' },
isRegex: { type: 'boolean' },
matchWholeWord: { type: 'boolean' },
isCaseSensitive: { type: 'boolean' },
preserveCase: { type: 'boolean' },
findInSelection: { type: 'boolean' },
}
}
}]
} as const;
export class StartFindWithArgsAction extends EditorAction {
constructor() {
super({
id: FIND_IDS.StartFindWithArgs,
label: nls.localize('startFindWithArgsAction', "Find With Arguments"),
alias: 'Find With Arguments',
precondition: undefined,
kbOpts: {
kbExpr: null,
primary: 0,
weight: KeybindingWeight.EditorContrib
},
metadata: findArgDescription
});
}
public async run(accessor: ServicesAccessor | null, editor: ICodeEditor, args?: IFindStartArguments): Promise<void> {
const controller = CommonFindController.get(editor);
if (controller) {
const newState: INewFindReplaceState = args ? {
searchString: args.searchString,
replaceString: args.replaceString,
isReplaceRevealed: args.replaceString !== undefined,
isRegex: args.isRegex,
// isRegexOverride: args.regexOverride,
wholeWord: args.matchWholeWord,
// wholeWordOverride: args.wholeWordOverride,
matchCase: args.isCaseSensitive,
// matchCaseOverride: args.matchCaseOverride,
preserveCase: args.preserveCase,
// preserveCaseOverride: args.preserveCaseOverride,
} : {};
await controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(EditorOption.find).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(EditorOption.find).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: true,
shouldFocus: FindStartFocusAction.FocusFindInput,
shouldAnimate: true,
updateSearchScope: args?.findInSelection || false,
loop: editor.getOption(EditorOption.find).loop
}, newState);
controller.setGlobalBufferTerm(controller.getState().searchString);
}
}
}
export class StartFindWithSelectionAction extends EditorAction {
constructor() {
super({
id: FIND_IDS.StartFindWithSelection,
label: nls.localize('startFindWithSelectionAction', "Find With Selection"),
alias: 'Find With Selection',
precondition: undefined,
kbOpts: {
kbExpr: null,
primary: 0,
mac: {
primary: KeyMod.CtrlCmd | KeyCode.KeyE,
},
weight: KeybindingWeight.EditorContrib
}
});
}
public async run(accessor: ServicesAccessor | null, editor: ICodeEditor): Promise<void> {
const controller = CommonFindController.get(editor);
if (controller) {
await controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: 'multiple',
seedSearchStringFromNonEmptySelection: false,
seedSearchStringFromGlobalClipboard: false,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(EditorOption.find).loop
});
controller.setGlobalBufferTerm(controller.getState().searchString);
}
}
}
export abstract class MatchFindAction extends EditorAction {
public async run(accessor: ServicesAccessor | null, editor: ICodeEditor): Promise<void> {
const controller = CommonFindController.get(editor);
if (controller && !this._run(controller)) {
await controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(EditorOption.find).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(EditorOption.find).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: true,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(EditorOption.find).loop
});
this._run(controller);
}
}
protected abstract _run(controller: CommonFindController): boolean;
}
export class NextMatchFindAction extends MatchFindAction {
constructor() {
super({
id: FIND_IDS.NextMatchFindAction,
label: nls.localize('findNextMatchAction', "Find Next"),
alias: 'Find Next',
precondition: undefined,
kbOpts: [{
kbExpr: EditorContextKeys.focus,
primary: KeyCode.F3,
mac: { primary: KeyMod.CtrlCmd | KeyCode.KeyG, secondary: [KeyCode.F3] },
weight: KeybindingWeight.EditorContrib
}, {
kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
primary: KeyCode.Enter,
weight: KeybindingWeight.EditorContrib
}]
});
}
protected _run(controller: CommonFindController): boolean {
const result = controller.moveToNextMatch();
if (result) {
controller.editor.pushUndoStop();
return true;
}
return false;
}
}
export class PreviousMatchFindAction extends MatchFindAction {
constructor() {
super({
id: FIND_IDS.PreviousMatchFindAction,
label: nls.localize('findPreviousMatchAction', "Find Previous"),
alias: 'Find Previous',
precondition: undefined,
kbOpts: [{
kbExpr: EditorContextKeys.focus,
primary: KeyMod.Shift | KeyCode.F3,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyG, secondary: [KeyMod.Shift | KeyCode.F3] },
weight: KeybindingWeight.EditorContrib
}, {
kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
primary: KeyMod.Shift | KeyCode.Enter,
weight: KeybindingWeight.EditorContrib
}
]
});
}
protected _run(controller: CommonFindController): boolean {
return controller.moveToPrevMatch();
}
}
export class MoveToMatchFindAction extends EditorAction {
private _highlightDecorations: string[] = [];
constructor() {
super({
id: FIND_IDS.GoToMatchFindAction,
label: nls.localize('findMatchAction.goToMatch', "Go to Match..."),
alias: 'Go to Match...',
precondition: CONTEXT_FIND_WIDGET_VISIBLE
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void | Promise<void> {
const controller = CommonFindController.get(editor);
if (!controller) {
return;
}
const matchesCount = controller.getState().matchesCount;
if (matchesCount < 1) {
const notificationService = accessor.get(INotificationService);
notificationService.notify({
severity: Severity.Warning,
message: nls.localize('findMatchAction.noResults', "No matches. Try searching for something else.")
});
return;
}
const quickInputService = accessor.get(IQuickInputService);
const inputBox = quickInputService.createInputBox();
inputBox.placeholder = nls.localize('findMatchAction.inputPlaceHolder', "Type a number to go to a specific match (between 1 and {0})", matchesCount);
const toFindMatchIndex = (value: string): number | undefined => {
const index = parseInt(value);
if (isNaN(index)) {
return undefined;
}
const matchCount = controller.getState().matchesCount;
if (index > 0 && index <= matchCount) {
return index - 1; // zero based
} else if (index < 0 && index >= -matchCount) {
return matchCount + index;
}
return undefined;
};
const updatePickerAndEditor = (value: string) => {
const index = toFindMatchIndex(value);
if (typeof index === 'number') {
// valid
inputBox.validationMessage = undefined;
controller.goToMatch(index);
const currentMatch = controller.getState().currentMatch;
if (currentMatch) {
this.addDecorations(editor, currentMatch);
}
} else {
inputBox.validationMessage = nls.localize('findMatchAction.inputValidationMessage', "Please type a number between 1 and {0}", controller.getState().matchesCount);
this.clearDecorations(editor);
}
};
inputBox.onDidChangeValue(value => {
updatePickerAndEditor(value);
});
inputBox.onDidAccept(() => {
const index = toFindMatchIndex(inputBox.value);
if (typeof index === 'number') {
controller.goToMatch(index);
inputBox.hide();
} else {
inputBox.validationMessage = nls.localize('findMatchAction.inputValidationMessage', "Please type a number between 1 and {0}", controller.getState().matchesCount);
}
});
inputBox.onDidHide(() => {
this.clearDecorations(editor);
inputBox.dispose();
});
inputBox.show();
}
private clearDecorations(editor: ICodeEditor): void {
editor.changeDecorations(changeAccessor => {
this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, []);
});
}
private addDecorations(editor: ICodeEditor, range: IRange): void {
editor.changeDecorations(changeAccessor => {
this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, [
{
range,
options: {
description: 'find-match-quick-access-range-highlight',
className: 'rangeHighlight',
isWholeLine: true
}
},
{
range,
options: {
description: 'find-match-quick-access-range-highlight-overview',
overviewRuler: {
color: themeColorFromId(overviewRulerRangeHighlight),
position: OverviewRulerLane.Full
}
}
}
]);
});
}
}
export abstract class SelectionMatchFindAction extends EditorAction {
public async run(accessor: ServicesAccessor | null, editor: ICodeEditor): Promise<void> {
const controller = CommonFindController.get(editor);
if (!controller) {
return;
}
const selectionSearchString = getSelectionSearchString(editor, 'single', false);
if (selectionSearchString) {
controller.setSearchString(selectionSearchString);
}
if (!this._run(controller)) {
await controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: 'none',
seedSearchStringFromNonEmptySelection: false,
seedSearchStringFromGlobalClipboard: false,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(EditorOption.find).loop
});
this._run(controller);
}
}
protected abstract _run(controller: CommonFindController): boolean;
}
export class NextSelectionMatchFindAction extends SelectionMatchFindAction {
constructor() {
super({
id: FIND_IDS.NextSelectionMatchFindAction,
label: nls.localize('nextSelectionMatchFindAction', "Find Next Selection"),
alias: 'Find Next Selection',
precondition: undefined,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyCode.F3,
weight: KeybindingWeight.EditorContrib
}
});
}
protected _run(controller: CommonFindController): boolean {
return controller.moveToNextMatch();
}
}
export class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
constructor() {
super({
id: FIND_IDS.PreviousSelectionMatchFindAction,
label: nls.localize('previousSelectionMatchFindAction', "Find Previous Selection"),
alias: 'Find Previous Selection',
precondition: undefined,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.F3,
weight: KeybindingWeight.EditorContrib
}
});
}
protected _run(controller: CommonFindController): boolean {
return controller.moveToPrevMatch();
}
}
export const StartFindReplaceAction = registerMultiEditorAction(new MultiEditorAction({
id: FIND_IDS.StartFindReplaceAction,
label: nls.localize('startReplace', "Replace"),
alias: 'Replace',
precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has('editorIsOpen')),
kbOpts: {
kbExpr: null,
primary: KeyMod.CtrlCmd | KeyCode.KeyH,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyF },
weight: KeybindingWeight.EditorContrib
},
menuOpts: {
menuId: MenuId.MenubarEditMenu,
group: '3_find',
title: nls.localize({ key: 'miReplace', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
order: 2
}
}));
StartFindReplaceAction.addImplementation(0, (accessor: ServicesAccessor, editor: ICodeEditor, args: any): boolean | Promise<void> => {
if (!editor.hasModel() || editor.getOption(EditorOption.readOnly)) {
return false;
}
const controller = CommonFindController.get(editor);
if (!controller) {
return false;
}
const currentSelection = editor.getSelection();
const findInputFocused = controller.isFindInputFocused();
// we only seed search string from selection when the current selection is single line and not empty,
// + the find input is not focused
const seedSearchStringFromSelection = !currentSelection.isEmpty()
&& currentSelection.startLineNumber === currentSelection.endLineNumber
&& (editor.getOption(EditorOption.find).seedSearchStringFromSelection !== 'never')
&& !findInputFocused;
/*
* if the existing search string in find widget is empty and we don't seed search string from selection, it means the Find Input is still empty, so we should focus the Find Input instead of Replace Input.
* findInputFocused true -> seedSearchStringFromSelection false, FocusReplaceInput
* findInputFocused false, seedSearchStringFromSelection true FocusReplaceInput
* findInputFocused false seedSearchStringFromSelection false FocusFindInput
*/
const shouldFocus = (findInputFocused || seedSearchStringFromSelection) ?
FindStartFocusAction.FocusReplaceInput : FindStartFocusAction.FocusFindInput;
return controller.start({
forceRevealReplace: true,
seedSearchStringFromSelection: seedSearchStringFromSelection ? 'single' : 'none',
seedSearchStringFromNonEmptySelection: editor.getOption(EditorOption.find).seedSearchStringFromSelection === 'selection',
seedSearchStringFromGlobalClipboard: editor.getOption(EditorOption.find).seedSearchStringFromSelection !== 'never',
shouldFocus: shouldFocus,
shouldAnimate: true,
updateSearchScope: false,
loop: editor.getOption(EditorOption.find).loop
});
});
registerEditorContribution(CommonFindController.ID, FindController, EditorContributionInstantiation.Eager); // eager because it uses `saveViewState`/`restoreViewState`
registerEditorAction(StartFindWithArgsAction);
registerEditorAction(StartFindWithSelectionAction);
registerEditorAction(NextMatchFindAction);
registerEditorAction(PreviousMatchFindAction);
registerEditorAction(MoveToMatchFindAction);
registerEditorAction(NextSelectionMatchFindAction);
registerEditorAction(PreviousSelectionMatchFindAction);
const FindCommand = EditorCommand.bindToContribution<CommonFindController>(CommonFindController.get);
registerEditorCommand(new FindCommand({
id: FIND_IDS.CloseFindWidgetCommand,
precondition: CONTEXT_FIND_WIDGET_VISIBLE,
handler: x => x.closeFindWidget(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not('isComposing')),
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ToggleCaseSensitiveCommand,
precondition: undefined,
handler: x => x.toggleCaseSensitive(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: ToggleCaseSensitiveKeybinding.primary,
mac: ToggleCaseSensitiveKeybinding.mac,
win: ToggleCaseSensitiveKeybinding.win,
linux: ToggleCaseSensitiveKeybinding.linux
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ToggleWholeWordCommand,
precondition: undefined,
handler: x => x.toggleWholeWords(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: ToggleWholeWordKeybinding.primary,
mac: ToggleWholeWordKeybinding.mac,
win: ToggleWholeWordKeybinding.win,
linux: ToggleWholeWordKeybinding.linux
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ToggleRegexCommand,
precondition: undefined,
handler: x => x.toggleRegex(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: ToggleRegexKeybinding.primary,
mac: ToggleRegexKeybinding.mac,
win: ToggleRegexKeybinding.win,
linux: ToggleRegexKeybinding.linux
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ToggleSearchScopeCommand,
precondition: undefined,
handler: x => x.toggleSearchScope(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: ToggleSearchScopeKeybinding.primary,
mac: ToggleSearchScopeKeybinding.mac,
win: ToggleSearchScopeKeybinding.win,
linux: ToggleSearchScopeKeybinding.linux
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.TogglePreserveCaseCommand,
precondition: undefined,
handler: x => x.togglePreserveCase(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: TogglePreserveCaseKeybinding.primary,
mac: TogglePreserveCaseKeybinding.mac,
win: TogglePreserveCaseKeybinding.win,
linux: TogglePreserveCaseKeybinding.linux
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ReplaceOneAction,
precondition: CONTEXT_FIND_WIDGET_VISIBLE,
handler: x => x.replace(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Digit1
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ReplaceOneAction,
precondition: CONTEXT_FIND_WIDGET_VISIBLE,
handler: x => x.replace(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
primary: KeyCode.Enter
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ReplaceAllAction,
precondition: CONTEXT_FIND_WIDGET_VISIBLE,
handler: x => x.replaceAll(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Enter
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.ReplaceAllAction,
precondition: CONTEXT_FIND_WIDGET_VISIBLE,
handler: x => x.replaceAll(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
primary: undefined,
mac: {
primary: KeyMod.CtrlCmd | KeyCode.Enter,
}
}
}));
registerEditorCommand(new FindCommand({
id: FIND_IDS.SelectAllMatchesAction,
precondition: CONTEXT_FIND_WIDGET_VISIBLE,
handler: x => x.selectAllMatches(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 5,
kbExpr: EditorContextKeys.focus,
primary: KeyMod.Alt | KeyCode.Enter
}
}));
| src/vs/editor/contrib/find/browser/findController.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00018073541286867112,
0.00017338231555186212,
0.00016515108291059732,
0.00017412618035450578,
0.000002929219817815465
] |
{
"id": 8,
"code_window": [
"\t\t *\n",
"\t\t * @param messages\n",
"\t\t * @param options\n",
"\t\t */\n",
"\t\tmakeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n",
"\t}\n",
"\n",
"\texport interface LanguageModelAccessOptions {\n",
"\t\t/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tmakeChatRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* File icons in trees */
.file-icon-themable-tree.align-icons-and-twisties .monaco-tl-twistie:not(.force-twistie):not(.collapsible),
.file-icon-themable-tree .align-icon-with-twisty .monaco-tl-twistie:not(.force-twistie):not(.collapsible),
.file-icon-themable-tree.hide-arrows .monaco-tl-twistie:not(.force-twistie),
.file-icon-themable-tree .monaco-tl-twistie.force-no-twistie {
background-image: none !important;
width: 0 !important;
padding-right: 0 !important;
visibility: hidden;
}
/* Misc */
.file-icon-themable-tree .monaco-list-row .content .monaco-highlighted-label .highlight,
.monaco-tl-contents .monaco-highlighted-label .highlight {
color: unset !important;
background-color: var(--vscode-list-filterMatchBackground);
outline: 1px dotted var(--vscode-list-filterMatchBorder);
outline-offset: -1px;
}
.monaco-workbench .tree-explorer-viewlet-tree-view {
height: 100%;
}
.monaco-workbench .tree-explorer-viewlet-tree-view .message {
display: flex;
padding: 4px 12px 4px 18px;
user-select: text;
-webkit-user-select: text;
}
.monaco-workbench .tree-explorer-viewlet-tree-view .message p {
margin-top: 0px;
margin-bottom: 0px;
padding-bottom: 4px;
}
.monaco-workbench .tree-explorer-viewlet-tree-view .message ul {
padding-left: 24px;
}
.monaco-workbench .tree-explorer-viewlet-tree-view .message a {
color: var(--vscode-textLink-foreground);
}
.monaco-workbench .tree-explorer-viewlet-tree-view .message.hide {
display: none;
}
.monaco-workbench .tree-explorer-viewlet-tree-view .customview-tree {
height: 100%;
}
.monaco-workbench .tree-explorer-viewlet-tree-view .customview-tree.hide {
display: none;
}
.monaco-workbench .pane > .pane-body > .welcome-view {
width: 100%;
height: 100%;
box-sizing: border-box;
display: flex;
flex-direction: column;
}
.monaco-workbench .pane > .pane-body:not(.welcome) > .welcome-view,
.monaco-workbench .pane > .pane-body.welcome > :not(.welcome-view) {
display: none;
}
.monaco-workbench .pane > .pane-body .welcome-view-content {
display: flex;
flex-direction: column;
padding: 0 20px 1em 20px;
box-sizing: border-box;
align-items: center;
}
.monaco-workbench .pane > .pane-body .welcome-view-content > .button-container {
width: 100%;
max-width: 300px;
}
.monaco-workbench:not(.reduce-motion) .pane > .pane-body .welcome-view-content > .button-container {
transition: 0.2s max-width ease-out;
}
.monaco-workbench .pane > .pane-body .welcome-view-content.wide > .button-container {
max-width: 100%;
}
.monaco-workbench .pane > .pane-body .welcome-view-content > .button-container > .monaco-button {
max-width: 300px;
}
.monaco-workbench .pane > .pane-body .welcome-view-content > p {
width: 100%;
}
.monaco-workbench .pane > .pane-body .welcome-view-content > * {
margin-block-start: 1em;
margin-block-end: 0;
margin-inline-start: 0px;
margin-inline-end: 0px;
}
.customview-tree .monaco-list-row .monaco-tl-contents.align-icon-with-twisty::before {
display: none;
}
.customview-tree .monaco-list-row .monaco-tl-contents:not(.align-icon-with-twisty)::before {
display: inline-block;
}
.customview-tree .monaco-list .monaco-list-row {
padding-right: 12px;
padding-left: 0px;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item {
display: flex;
height: 22px;
line-height: 22px;
flex: 1;
text-overflow: ellipsis;
overflow: hidden;
flex-wrap: nowrap;
padding-left: 3px;
}
.customview-tree .monaco-list .monaco-list-row.selected .custom-view-tree-node-item .custom-view-tree-node-item-checkbox {
background-color: var(--vscode-checkbox-selectBackground);
border: 1px solid var(--vscode-checkbox-selectBorder);
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .custom-view-tree-node-item-checkbox {
width: 16px;
height: 16px;
margin: 3px 6px 3px 0px;
padding: 0px;
border: 1px solid var(--vscode-checkbox-border);
opacity: 1;
background-color: var(--vscode-checkbox-background);
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .custom-view-tree-node-item-checkbox.codicon {
font-size: 13px;
line-height: 15px;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .monaco-inputbox {
line-height: normal;
flex: 1;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .custom-view-tree-node-item-resourceLabel {
flex: 1;
text-overflow: ellipsis;
overflow: hidden;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .monaco-icon-label-container::after {
content: '';
display: block;
}
.timeline-tree-view .monaco-list .monaco-list-row .custom-view-tree-node-item > .custom-view-tree-node-item-icon,
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item > .custom-view-tree-node-item-resourceLabel > .custom-view-tree-node-item-icon {
background-size: 16px;
background-position: left center;
background-repeat: no-repeat;
padding-right: 6px;
width: 16px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item > .custom-view-tree-node-item-resourceLabel > .custom-view-tree-node-item-icon.disabled {
opacity: 0.6;
}
/* makes spinning icons square */
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item > .custom-view-tree-node-item-resourceLabel > .custom-view-tree-node-item-icon.codicon.codicon-modifier-spin {
padding-left: 6px;
margin-left: -6px;
}
.customview-tree .monaco-list .monaco-list-row.selected .custom-view-tree-node-item > .custom-view-tree-node-item-resourceLabel > .custom-view-tree-node-item-icon.codicon {
color: currentColor !important;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .custom-view-tree-node-item-resourceLabel .monaco-icon-label-container > .monaco-icon-name-container {
flex: 1;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .custom-view-tree-node-item-resourceLabel::after {
padding-right: 0px;
margin-right: 4px;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .actions {
display: none;
}
.customview-tree .monaco-list .monaco-list-row .custom-view-tree-node-item .actions .action-label {
padding: 2px;
}
.customview-tree .monaco-list .monaco-list-row:hover .custom-view-tree-node-item .actions,
.customview-tree .monaco-list .monaco-list-row.selected .custom-view-tree-node-item .actions,
.customview-tree .monaco-list .monaco-list-row.focused .custom-view-tree-node-item .actions {
display: block;
}
/* filter view pane */
.monaco-workbench .auxiliarybar.pane-composite-part > .title.has-composite-bar > .title-actions .monaco-action-bar .action-item.viewpane-filter-container {
max-width: inherit;
}
.viewpane-filter-container {
cursor: default;
display: flex;
}
.viewpane-filter-container.grow {
flex: 1;
}
.viewpane-filter-container > .viewpane-filter {
display: flex;
align-items: center;
flex: 1;
position: relative;
}
.viewpane-filter-container > .viewpane-filter .monaco-inputbox {
height: 24px;
font-size: 12px;
flex: 1;
}
.pane-header .viewpane-filter-container > .viewpane-filter .monaco-inputbox .monaco-inputbox {
height: 20px;
line-height: 18px;
}
.monaco-workbench.vs .viewpane-filter-container > .viewpane-filter .monaco-inputbox {
height: 25px;
}
.viewpane-filter-container > .viewpane-filter > .viewpane-filter-controls {
position: absolute;
top: 0px;
bottom: 0;
right: 0px;
display: flex;
align-items: center;
}
.viewpane-filter-container > .viewpane-filter > .viewpane-filter-controls > .viewpane-filter-badge {
margin: 4px 0px;
padding: 0px 8px;
border-radius: 2px;
}
.viewpane-filter > .viewpane-filter-controls > .viewpane-filter-badge.hidden,
.viewpane-filter.small > .viewpane-filter-controls > .viewpane-filter-badge {
display: none;
}
.viewpane-filter > .viewpane-filter-controls > .monaco-action-bar .action-item .action-label.codicon.filter {
padding: 2px;
}
.panel > .title .monaco-action-bar .action-item.viewpane-filter-container {
max-width: 400px;
min-width: 150px;
margin-right: 10px;
}
.pane-body .viewpane-filter-container:not(:empty) {
flex: 1;
margin: 10px 20px;
height: initial;
}
.pane-body .viewpane-filter-container > .viewpane-filter > .viewpane-filter-controls .monaco-action-bar .action-item {
margin-right: 4px;
}
.viewpane-filter > .viewpane-filter-controls .monaco-action-bar .action-label.codicon.codicon-filter.checked {
border-color: var(--vscode-inputOption-activeBorder);
color: var(--vscode-inputOption-activeForeground);
background-color: var(--vscode-inputOption-activeBackground);
}
| src/vs/workbench/browser/parts/views/media/views.css | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017653494433034211,
0.00017312454292550683,
0.00017041637329384685,
0.0001727918570395559,
0.000001800300879040151
] |
{
"id": 9,
"code_window": [
"\t\t/**\n",
"\t\t * Request access to a language model.\n",
"\t\t *\n",
"\t\t * *Note* that this function will throw an error when the user didn't grant access\n",
"\t\t *\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t * - *Note 1:* This function will throw an error when the user didn't grant access or when the\n",
"\t\t * requested language model is not available.\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.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.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
export interface LanguageModelResponse {
/**
* The overall result of the request which represents failure or success
* but _not_ the actual response or responses
*/
// TODO@API define this type!
result: Thenable<unknown>;
stream: AsyncIterable<string>;
}
/**
* Represents access to using a language model. Access can be revoked at any time and extension
* must check if the access is {@link LanguageModelAccess.isRevoked still valid} before using it.
*/
export interface LanguageModelAccess {
/**
* Whether the access to the language model has been revoked.
*/
readonly isRevoked: boolean;
/**
* An event that is fired when the access the language model has has been revoked or re-granted.
*/
readonly onDidChangeAccess: Event<void>;
/**
* The name of the model.
*
* It is expected that the model name can be used to lookup properties like token limits or what
* `options` are available.
*/
readonly model: string;
/**
* Make a request to the language model.
*
* *Note:* This will throw an error if access has been revoked.
*
* @param messages
* @param options
*/
makeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;
}
export interface LanguageModelAccessOptions {
/**
* A human-readable message that explains why access to a language model is needed and what feature is enabled by it.
*/
justification?: string;
}
/**
* An event describing the change in the set of available language models.
*/
export interface LanguageModelChangeEvent {
/**
* Added language models.
*/
readonly added: readonly string[];
/**
* Removed language models.
*/
readonly removed: readonly string[];
}
//@API DEFINE the namespace for this: env, lm, ai?
export namespace chat {
/**
* Request access to a language model.
*
* *Note* that this function will throw an error when the user didn't grant access
*
* @param id The id of the language model, e.g `copilot`
* @returns A thenable that resolves to a language model access object, rejects is access wasn't granted
*/
export function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;
/**
* The identifiers of all language models that are currently available.
*/
export const languageModels: readonly string[];
/**
* An event that is fired when the set of available language models changes.
*/
//@API is this really needed?
export const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;
}
}
| src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.000655840733088553,
0.0002484901051502675,
0.00016510165005456656,
0.000203719871933572,
0.00013501138892024755
] |
{
"id": 9,
"code_window": [
"\t\t/**\n",
"\t\t * Request access to a language model.\n",
"\t\t *\n",
"\t\t * *Note* that this function will throw an error when the user didn't grant access\n",
"\t\t *\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t * - *Note 1:* This function will throw an error when the user didn't grant access or when the\n",
"\t\t * requested language model is not available.\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 81
} | {
"displayName": "Git",
"description": "Git SCM Integration",
"command.continueInLocalClone": "Clone Repository Locally and Open on Desktop...",
"command.continueInLocalClone.qualifiedName": "Continue Working in New Local Clone",
"command.clone": "Clone",
"command.cloneRecursive": "Clone (Recursive)",
"command.init": "Initialize Repository",
"command.openRepository": "Open Repository",
"command.reopenClosedRepositories": "Reopen Closed Repositories...",
"command.close": "Close Repository",
"command.closeOtherRepositories": "Close Other Repositories",
"command.refresh": "Refresh",
"command.openChange": "Open Changes",
"command.openAllChanges": "Open All Changes",
"command.openFile": "Open File",
"command.openHEADFile": "Open File (HEAD)",
"command.stage": "Stage Changes",
"command.stageAll": "Stage All Changes",
"command.stageAllTracked": "Stage All Tracked Changes",
"command.stageAllUntracked": "Stage All Untracked Changes",
"command.stageAllMerge": "Stage All Merge Changes",
"command.stageSelectedRanges": "Stage Selected Ranges",
"command.revertSelectedRanges": "Revert Selected Ranges",
"command.stageChange": "Stage Change",
"command.revertChange": "Revert Change",
"command.unstage": "Unstage Changes",
"command.unstageAll": "Unstage All Changes",
"command.unstageSelectedRanges": "Unstage Selected Ranges",
"command.rename": "Rename",
"command.clean": "Discard Changes",
"command.cleanAll": "Discard All Changes",
"command.cleanAllTracked": "Discard All Tracked Changes",
"command.cleanAllUntracked": "Discard All Untracked Changes",
"command.closeAllDiffEditors": "Close All Diff Editors",
"command.commit": "Commit",
"command.commitAmend": "Commit (Amend)",
"command.commitSigned": "Commit (Signed Off)",
"command.commitStaged": "Commit Staged",
"command.commitEmpty": "Commit Empty",
"command.commitStagedSigned": "Commit Staged (Signed Off)",
"command.commitStagedAmend": "Commit Staged (Amend)",
"command.commitAll": "Commit All",
"command.commitAllSigned": "Commit All (Signed Off)",
"command.commitAllAmend": "Commit All (Amend)",
"command.commitNoVerify": "Commit (No Verify)",
"command.commitStagedNoVerify": "Commit Staged (No Verify)",
"command.commitEmptyNoVerify": "Commit Empty (No Verify)",
"command.commitStagedSignedNoVerify": "Commit Staged (Signed Off, No Verify)",
"command.commitAmendNoVerify": "Commit (Amend, No Verify)",
"command.commitSignedNoVerify": "Commit (Signed Off, No Verify)",
"command.commitStagedAmendNoVerify": "Commit Staged (Amend, No Verify)",
"command.commitAllNoVerify": "Commit All (No Verify)",
"command.commitAllSignedNoVerify": "Commit All (Signed Off, No Verify)",
"command.commitAllAmendNoVerify": "Commit All (Amend, No Verify)",
"command.commitMessageAccept": "Accept Commit Message",
"command.commitMessageDiscard": "Discard Commit Message",
"command.restoreCommitTemplate": "Restore Commit Template",
"command.undoCommit": "Undo Last Commit",
"command.checkout": "Checkout to...",
"command.checkoutDetached": "Checkout to (Detached)...",
"command.branch": "Create Branch...",
"command.branchFrom": "Create Branch From...",
"command.deleteBranch": "Delete Branch...",
"command.renameBranch": "Rename Branch...",
"command.cherryPick": "Cherry Pick...",
"command.merge": "Merge...",
"command.mergeAbort": "Abort Merge",
"command.rebase": "Rebase Branch...",
"command.createTag": "Create Tag",
"command.deleteTag": "Delete Tag...",
"command.deleteRemoteTag": "Delete Remote Tag...",
"command.fetch": "Fetch",
"command.fetchPrune": "Fetch (Prune)",
"command.fetchAll": "Fetch From All Remotes",
"command.pull": "Pull",
"command.pullRebase": "Pull (Rebase)",
"command.pullFrom": "Pull from...",
"command.push": "Push",
"command.pushForce": "Push (Force)",
"command.pushTo": "Push to...",
"command.pushToForce": "Push to... (Force)",
"command.pushFollowTags": "Push (Follow Tags)",
"command.pushFollowTagsForce": "Push (Follow Tags, Force)",
"command.pushTags": "Push Tags",
"command.addRemote": "Add Remote...",
"command.removeRemote": "Remove Remote",
"command.sync": "Sync",
"command.syncRebase": "Sync (Rebase)",
"command.publish": "Publish Branch...",
"command.showOutput": "Show Git Output",
"command.ignore": "Add to .gitignore",
"command.revealInExplorer": "Reveal in Explorer View",
"command.revealFileInOS.linux": "Open Containing Folder",
"command.revealFileInOS.mac": "Reveal in Finder",
"command.revealFileInOS.windows": "Reveal in File Explorer",
"command.rebaseAbort": "Abort Rebase",
"command.stashIncludeUntracked": "Stash (Include Untracked)",
"command.stash": "Stash",
"command.stashStaged": "Stash Staged",
"command.stashPop": "Pop Stash...",
"command.stashPopLatest": "Pop Latest Stash",
"command.stashPopEditor": "Pop Stash",
"command.stashApply": "Apply Stash...",
"command.stashApplyLatest": "Apply Latest Stash",
"command.stashApplyEditor": "Apply Stash",
"command.stashDrop": "Drop Stash...",
"command.stashDropAll": "Drop All Stashes...",
"command.stashDropEditor": "Drop Stash",
"command.stashView": "View Stash...",
"command.timelineOpenDiff": "Open Changes",
"command.timelineCopyCommitId": "Copy Commit ID",
"command.timelineCopyCommitMessage": "Copy Commit Message",
"command.timelineSelectForCompare": "Select for Compare",
"command.timelineCompareWithSelected": "Compare with Selected",
"command.manageUnsafeRepositories": "Manage Unsafe Repositories",
"command.openRepositoriesInParentFolders": "Open Repositories In Parent Folders",
"command.viewAllChanges": "View All Changes",
"command.viewCommit": "View Commit",
"command.api.getRepositories": "Get Repositories",
"command.api.getRepositoryState": "Get Repository State",
"command.api.getRemoteSources": "Get Remote Sources",
"command.git.acceptMerge": "Complete Merge",
"command.git.openMergeEditor": "Resolve in Merge Editor",
"command.git.runGitMerge": "Compute Conflicts With Git",
"command.git.runGitMergeDiff3": "Compute Conflicts With Git (Diff3)",
"config.enabled": "Whether Git is enabled.",
"config.path": "Path and filename of the git executable, e.g. `C:\\Program Files\\Git\\bin\\git.exe` (Windows). This can also be an array of string values containing multiple paths to look up.",
"config.autoRepositoryDetection": "Configures when repositories should be automatically detected.",
"config.autoRepositoryDetection.true": "Scan for both subfolders of the current opened folder and parent folders of open files.",
"config.autoRepositoryDetection.false": "Disable automatic repository scanning.",
"config.autoRepositoryDetection.subFolders": "Scan for subfolders of the currently opened folder.",
"config.autoRepositoryDetection.openEditors": "Scan for parent folders of open files.",
"config.autorefresh": "Whether auto refreshing is enabled.",
"config.autofetch": "When set to true, commits will automatically be fetched from the default remote of the current Git repository. Setting to `all` will fetch from all remotes.",
"config.autofetchPeriod": "Duration in seconds between each automatic git fetch, when `#git.autofetch#` is enabled.",
"config.confirmSync": "Confirm before synchronizing Git repositories.",
"config.countBadge": "Controls the Git count badge.",
"config.countBadge.all": "Count all changes.",
"config.countBadge.tracked": "Count only tracked changes.",
"config.countBadge.off": "Turn off counter.",
"config.checkoutType": "Controls what type of Git refs are listed when running `Checkout to...`.",
"config.checkoutType.local": "Local branches",
"config.checkoutType.tags": "Tags",
"config.checkoutType.remote": "Remote branches",
"config.defaultBranchName": "The name of the default branch (example: main, trunk, development) when initializing a new Git repository. When set to empty, the default branch name configured in Git will be used. **Note:** Requires Git version `2.28.0` or later.",
"config.branchPrefix": "Prefix used when creating a new branch.",
"config.branchProtection": "List of protected branches. By default, a prompt is shown before changes are committed to a protected branch. The prompt can be controlled using the `#git.branchProtectionPrompt#` setting.",
"config.branchProtectionPrompt": "Controls whether a prompt is being shown before changes are committed to a protected branch.",
"config.branchProtectionPrompt.alwaysCommit": "Always commit changes to the protected branch.",
"config.branchProtectionPrompt.alwaysCommitToNewBranch": "Always commit changes to a new branch.",
"config.branchProtectionPrompt.alwaysPrompt": "Always prompt before changes are committed to a protected branch.",
"config.branchRandomNameDictionary": "List of dictionaries used for the randomly generated branch name. Each value represents the dictionary used to generate the segment of the branch name. Supported dictionaries: `adjectives`, `animals`, `colors` and `numbers`.",
"config.branchRandomNameDictionary.adjectives": "A random adjective",
"config.branchRandomNameDictionary.animals": "A random animal name",
"config.branchRandomNameDictionary.colors": "A random color name",
"config.branchRandomNameDictionary.numbers": "A random number between 100 and 999",
"config.branchRandomNameEnable": "Controls whether a random name is generated when creating a new branch.",
"config.branchValidationRegex": "A regular expression to validate new branch names.",
"config.branchWhitespaceChar": "The character to replace whitespace in new branch names, and to separate segments of a randomly generated branch name.",
"config.ignoreLegacyWarning": "Ignores the legacy Git warning.",
"config.ignoreMissingGitWarning": "Ignores the warning when Git is missing.",
"config.ignoreWindowsGit27Warning": "Ignores the warning when Git 2.25 - 2.26 is installed on Windows.",
"config.ignoreLimitWarning": "Ignores the warning when there are too many changes in a repository.",
"config.ignoreRebaseWarning": "Ignores the warning when it looks like the branch might have been rebased when pulling.",
"config.defaultCloneDirectory": "The default location to clone a Git repository.",
"config.useEditorAsCommitInput": "Controls whether a full text editor will be used to author commit messages, whenever no message is provided in the commit input box.",
"config.verboseCommit": "Enable verbose output when `#git.useEditorAsCommitInput#` is enabled.",
"config.enableSmartCommit": "Commit all changes when there are no staged changes.",
"config.smartCommitChanges": "Control which changes are automatically staged by Smart Commit.",
"config.smartCommitChanges.all": "Automatically stage all changes.",
"config.smartCommitChanges.tracked": "Automatically stage tracked changes only.",
"config.suggestSmartCommit": "Suggests to enable smart commit (commit all changes when there are no staged changes).",
"config.enableCommitSigning": "Enables commit signing with GPG, X.509, or SSH.",
"config.discardAllScope": "Controls what changes are discarded by the `Discard all changes` command. `all` discards all changes. `tracked` discards only tracked files. `prompt` shows a prompt dialog every time the action is run.",
"config.decorations.enabled": "Controls whether Git contributes colors and badges to the Explorer and the Open Editors view.",
"config.enableStatusBarSync": "Controls whether the Git Sync command appears in the status bar.",
"config.followTagsWhenSync": "Push all annotated tags when running the sync command.",
"config.promptToSaveFilesBeforeStash": "Controls whether Git should check for unsaved files before stashing changes.",
"config.promptToSaveFilesBeforeStash.always": "Check for any unsaved files.",
"config.promptToSaveFilesBeforeStash.staged": "Check only for unsaved staged files.",
"config.promptToSaveFilesBeforeStash.never": "Disable this check.",
"config.promptToSaveFilesBeforeCommit": "Controls whether Git should check for unsaved files before committing.",
"config.promptToSaveFilesBeforeCommit.always": "Check for any unsaved files.",
"config.promptToSaveFilesBeforeCommit.staged": "Check only for unsaved staged files.",
"config.promptToSaveFilesBeforeCommit.never": "Disable this check.",
"config.postCommitCommand": "Run a git command after a successful commit.",
"config.postCommitCommand.none": "Don't run any command after a commit.",
"config.postCommitCommand.push": "Run 'git push' after a successful commit.",
"config.postCommitCommand.sync": "Run 'git pull' and 'git push' after a successful commit.",
"config.rememberPostCommitCommand": "Remember the last git command that ran after a commit.",
"config.openAfterClone": "Controls whether to open a repository automatically after cloning.",
"config.openAfterClone.always": "Always open in current window.",
"config.openAfterClone.alwaysNewWindow": "Always open in a new window.",
"config.openAfterClone.whenNoFolderOpen": "Only open in current window when no folder is opened.",
"config.openAfterClone.prompt": "Always prompt for action.",
"config.showInlineOpenFileAction": "Controls whether to show an inline Open File action in the Git changes view.",
"config.showPushSuccessNotification": "Controls whether to show a notification when a push is successful.",
"config.inputValidation": "Controls when to show commit message input validation.",
"config.inputValidationLength": "Controls the commit message length threshold for showing a warning.",
"config.inputValidationSubjectLength": "Controls the commit message subject length threshold for showing a warning. Unset it to inherit the value of `#git.inputValidationLength#`.",
"config.detectSubmodules": "Controls whether to automatically detect Git submodules.",
"config.detectSubmodulesLimit": "Controls the limit of Git submodules detected.",
"config.alwaysShowStagedChangesResourceGroup": "Always show the Staged Changes resource group.",
"config.alwaysSignOff": "Controls the signoff flag for all commits.",
"config.ignoreSubmodules": "Ignore modifications to submodules in the file tree.",
"config.ignoredRepositories": "List of Git repositories to ignore.",
"config.scanRepositories": "List of paths to search for Git repositories in.",
"config.commandsToLog": {
"message": "List of git commands (ex: commit, push) that would have their `stdout` logged to the [git output](command:git.showOutput). If the git command has a client-side hook configured, the client-side hook's `stdout` will also be logged to the [git output](command:git.showOutput).",
"comment": [
"{Locked='](command:git.showOutput'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"config.showProgress": "Controls whether Git actions should show progress.",
"config.rebaseWhenSync": "Force Git to use rebase when running the sync command.",
"config.confirmEmptyCommits": "Always confirm the creation of empty commits for the 'Git: Commit Empty' command.",
"config.fetchOnPull": "When enabled, fetch all branches when pulling. Otherwise, fetch just the current one.",
"config.pullBeforeCheckout": "Controls whether a branch that does not have outgoing commits is fast-forwarded before it is checked out.",
"config.pullTags": "Fetch all tags when pulling.",
"config.pruneOnFetch": "Prune when fetching.",
"config.autoStash": "Stash any changes before pulling and restore them after successful pull.",
"config.allowForcePush": "Controls whether force push (with or without lease) is enabled.",
"config.useForcePushWithLease": "Controls whether force pushing uses the safer force-with-lease variant.",
"config.useForcePushIfIncludes": "Controls whether force pushing uses the safer force-if-includes variant. Note: This setting requires the `#git.useForcePushWithLease#` setting to be enabled, and Git version `2.30.0` or later.",
"config.confirmForcePush": "Controls whether to ask for confirmation before force-pushing.",
"config.allowNoVerifyCommit": "Controls whether commits without running pre-commit and commit-msg hooks are allowed.",
"config.confirmNoVerifyCommit": "Controls whether to ask for confirmation before committing without verification.",
"config.closeDiffOnOperation": "Controls whether the diff editor should be automatically closed when changes are stashed, committed, discarded, staged, or unstaged.",
"config.openDiffOnClick": "Controls whether the diff editor should be opened when clicking a change. Otherwise the regular editor will be opened.",
"config.supportCancellation": "Controls whether a notification comes up when running the Sync action, which allows the user to cancel the operation.",
"config.branchSortOrder": "Controls the sort order for branches.",
"config.untrackedChanges": "Controls how untracked changes behave.",
"config.untrackedChanges.mixed": "All changes, tracked and untracked, appear together and behave equally.",
"config.untrackedChanges.separate": "Untracked changes appear separately in the Source Control view. They are also excluded from several actions.",
"config.untrackedChanges.hidden": "Untracked changes are hidden and excluded from several actions.",
"config.requireGitUserConfig": "Controls whether to require explicit Git user configuration or allow Git to guess if missing.",
"config.showCommitInput": "Controls whether to show the commit input in the Git source control panel.",
"config.terminalAuthentication": "Controls whether to enable VS Code to be the authentication handler for Git processes spawned in the Integrated Terminal. Note: Terminals need to be restarted to pick up a change in this setting.",
"config.terminalGitEditor": "Controls whether to enable VS Code to be the Git editor for Git processes spawned in the integrated terminal. Note: Terminals need to be restarted to pick up a change in this setting.",
"config.timeline.showAuthor": "Controls whether to show the commit author in the Timeline view.",
"config.timeline.showUncommitted": "Controls whether to show uncommitted changes in the Timeline view.",
"config.timeline.date": "Controls which date to use for items in the Timeline view.",
"config.timeline.date.committed": "Use the committed date",
"config.timeline.date.authored": "Use the authored date",
"config.useCommitInputAsStashMessage": "Controls whether to use the message from the commit input box as the default stash message.",
"config.showActionButton": "Controls whether an action button is shown in the Source Control view.",
"config.showActionButton.commit": "Show an action button to commit changes when the local branch has modified files ready to be committed.",
"config.showActionButton.publish": "Show an action button to publish the local branch when it does not have a tracking remote branch.",
"config.showActionButton.sync": "Show an action button to synchronize changes when the local branch is either ahead or behind the remote branch.",
"config.statusLimit": "Controls how to limit the number of changes that can be parsed from Git status command. Can be set to 0 for no limit.",
"config.experimental.installGuide": "Experimental improvements for the Git setup flow.",
"config.repositoryScanIgnoredFolders": "List of folders that are ignored while scanning for Git repositories when `#git.autoRepositoryDetection#` is set to `true` or `subFolders`.",
"config.repositoryScanMaxDepth": "Controls the depth used when scanning workspace folders for Git repositories when `#git.autoRepositoryDetection#` is set to `true` or `subFolders`. Can be set to `-1` for no limit.",
"config.useIntegratedAskPass": "Controls whether GIT_ASKPASS should be overwritten to use the integrated version.",
"config.mergeEditor": "Open the merge editor for files that are currently under conflict.",
"config.optimisticUpdate": "Controls whether to optimistically update the state of the Source Control view after running git commands.",
"config.openRepositoryInParentFolders": "Control whether a repository in parent folders of workspaces or open files should be opened.",
"config.openRepositoryInParentFolders.always": "Always open a repository in parent folders of workspaces or open files.",
"config.openRepositoryInParentFolders.never": "Never open a repository in parent folders of workspaces or open files.",
"config.openRepositoryInParentFolders.prompt": "Prompt before opening a repository the parent folders of workspaces or open files.",
"config.publishBeforeContinueOn": "Controls whether to publish unpublished Git state when using Continue Working On from a Git repository.",
"config.publishBeforeContinueOn.always": "Always publish unpublished Git state when using Continue Working On from a Git repository",
"config.publishBeforeContinueOn.never": "Never publish unpublished Git state when using Continue Working On from a Git repository",
"config.publishBeforeContinueOn.prompt": "Prompt to publish unpublished Git state when using Continue Working On from a Git repository",
"config.similarityThreshold": "Controls the threshold of the similarity index (the amount of additions/deletions compared to the file's size) for changes in a pair of added/deleted files to be considered a rename. **Note:** Requires Git version `2.18.0` or later.",
"submenu.explorer": "Git",
"submenu.commit": "Commit",
"submenu.commit.amend": "Amend",
"submenu.commit.signoff": "Sign Off",
"submenu.changes": "Changes",
"submenu.pullpush": "Pull, Push",
"submenu.branch": "Branch",
"submenu.remotes": "Remote",
"submenu.stash": "Stash",
"submenu.tags": "Tags",
"colors.added": "Color for added resources.",
"colors.modified": "Color for modified resources.",
"colors.stageModified": "Color for modified resources which have been staged.",
"colors.stageDeleted": "Color for deleted resources which have been staged.",
"colors.deleted": "Color for deleted resources.",
"colors.renamed": "Color for renamed or copied resources.",
"colors.untracked": "Color for untracked resources.",
"colors.ignored": "Color for ignored resources.",
"colors.conflict": "Color for resources with conflicts.",
"colors.submodule": "Color for submodule resources.",
"view.workbench.scm.missing.windows": {
"message": "[Download Git for Windows](https://git-scm.com/download/win)\nAfter installing, please [reload](command:workbench.action.reloadWindow) (or [troubleshoot](command:git.showOutput)). Additional source control providers can be installed [from the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22).",
"comment": [
"{Locked='](command:workbench.action.reloadWindow'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.missing.mac": {
"message": "[Download Git for macOS](https://git-scm.com/download/mac)\nAfter installing, please [reload](command:workbench.action.reloadWindow) (or [troubleshoot](command:git.showOutput)). Additional source control providers can be installed [from the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22).",
"comment": [
"{Locked='](command:workbench.action.reloadWindow'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.missing.linux": {
"message": "Source control depends on Git being installed.\n[Download Git for Linux](https://git-scm.com/download/linux)\nAfter installing, please [reload](command:workbench.action.reloadWindow) (or [troubleshoot](command:git.showOutput)). Additional source control providers can be installed [from the Marketplace](command:workbench.extensions.search?%22%40category%3A%5C%22scm%20providers%5C%22%22).",
"comment": [
"{Locked='](command:workbench.action.reloadWindow'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.missing": "Install Git, a popular source control system, to track code changes and collaborate with others. Learn more in our [Git guides](https://aka.ms/vscode-scm).",
"view.workbench.scm.disabled": {
"message": "If you would like to use Git features, please enable Git in your [settings](command:workbench.action.openSettings?%5B%22git.enabled%22%5D).\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:workbench.action.openSettings?%5B%22git.enabled%22%5D'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.empty": {
"message": "In order to use Git features, you can open a folder containing a Git repository or clone from a URL.\n[Open Folder](command:vscode.openFolder)\n[Clone Repository](command:git.clone)\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:vscode.openFolder'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.folder": {
"message": "The folder currently open doesn't have a Git repository. You can initialize a repository which will enable source control features powered by Git.\n[Initialize Repository](command:git.init?%5Btrue%5D)\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.init?%5Btrue%5D'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.workspace": {
"message": "The workspace currently open doesn't have any folders containing Git repositories. You can initialize a repository on a folder which will enable source control features powered by Git.\n[Initialize Repository](command:git.init)\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.init'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.emptyWorkspace": {
"message": "The workspace currently open doesn't have any folders containing Git repositories.\n[Add Folder to Workspace](command:workbench.action.addRootFolder)\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:workbench.action.addRootFolder'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.scanFolderForRepositories": {
"message": "Scanning folder for Git repositories..."
},
"view.workbench.scm.scanWorkspaceForRepositories": {
"message": "Scanning workspace for Git repositories..."
},
"view.workbench.scm.repositoryInParentFolders": {
"message": "A Git repository was found in the parent folders of the workspace or the open file(s).\n[Open Repository](command:git.openRepositoriesInParentFolders)\nUse the [git.openRepositoryInParentFolders](command:workbench.action.openSettings?%5B%22git.openRepositoryInParentFolders%22%5D) setting to control whether Git repositories in parent folders of workspaces or open files are opened. To learn more [read our docs](https://aka.ms/vscode-git-repository-in-parent-folders).",
"comment": [
"{Locked='](command:git.openRepositoriesInParentFolders'}",
"{Locked='](command:workbench.action.openSettings?%5B%22git.openRepositoryInParentFolders%22%5D'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.repositoriesInParentFolders": {
"message": "Git repositories were found in the parent folders of the workspace or the open file(s).\n[Open Repository](command:git.openRepositoriesInParentFolders)\nUse the [git.openRepositoryInParentFolders](command:workbench.action.openSettings?%5B%22git.openRepositoryInParentFolders%22%5D) setting to control whether Git repositories in parent folders of workspace or open files are opened. To learn more [read our docs](https://aka.ms/vscode-git-repository-in-parent-folders).",
"comment": [
"{Locked='](command:git.openRepositoriesInParentFolders'}",
"{Locked='](command:workbench.action.openSettings?%5B%22git.openRepositoryInParentFolders%22%5D'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.unsafeRepository": {
"message": "The detected Git repository is potentially unsafe as the folder is owned by someone other than the current user.\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).",
"comment": [
"{Locked='](command:git.manageUnsafeRepositories'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.unsafeRepositories": {
"message": "The detected Git repositories are potentially unsafe as the folders are owned by someone other than the current user.\n[Manage Unsafe Repositories](command:git.manageUnsafeRepositories)\nTo learn more about unsafe repositories [read our docs](https://aka.ms/vscode-git-unsafe-repository).",
"comment": [
"{Locked='](command:git.manageUnsafeRepositories'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.closedRepository": {
"message": "A Git repository was found that was previously closed.\n[Reopen Closed Repository](command:git.reopenClosedRepositories)\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.reopenClosedRepositories'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.scm.closedRepositories": {
"message": "Git repositories were found that were previously closed.\n[Reopen Closed Repositories](command:git.reopenClosedRepositories)\nTo learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm).",
"comment": [
"{Locked='](command:git.reopenClosedRepositories'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.cloneRepository": {
"message": "You can clone a repository locally.\n[Clone Repository](command:git.clone 'Clone a repository once the Git extension has activated')",
"comment": [
"{Locked='](command:git.clone'}",
"Do not translate the 'command:*' part inside of the '(..)'. It is an internal command syntax for VS Code",
"Please make sure there is no space between the right bracket and left parenthesis: ]( this is an internal syntax for links"
]
},
"view.workbench.learnMore": "To learn more about how to use Git and source control in VS Code [read our docs](https://aka.ms/vscode-scm)."
}
| extensions/git/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00026709315716288984,
0.0001697156112641096,
0.00016454810975119472,
0.00016624847194179893,
0.000015801930203451775
] |
{
"id": 9,
"code_window": [
"\t\t/**\n",
"\t\t * Request access to a language model.\n",
"\t\t *\n",
"\t\t * *Note* that this function will throw an error when the user didn't grant access\n",
"\t\t *\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t * - *Note 1:* This function will throw an error when the user didn't grant access or when the\n",
"\t\t * requested language model is not available.\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.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 * as vscode from 'vscode';
import { LanguageClient, LanguageClientOptions } from 'vscode-languageclient/browser';
import { MdLanguageClient, startClient } from './client/client';
import { activateShared } from './extension.shared';
import { VsCodeOutputLogger } from './logging';
import { IMdParser, MarkdownItEngine } from './markdownEngine';
import { getMarkdownExtensionContributions } from './markdownExtensions';
import { githubSlugifier } from './slugify';
export async function activate(context: vscode.ExtensionContext) {
const contributions = getMarkdownExtensionContributions(context);
context.subscriptions.push(contributions);
const logger = new VsCodeOutputLogger();
context.subscriptions.push(logger);
const engine = new MarkdownItEngine(contributions, githubSlugifier, logger);
const client = await startServer(context, engine);
context.subscriptions.push(client);
activateShared(context, client, engine, logger, contributions);
}
function startServer(context: vscode.ExtensionContext, parser: IMdParser): Promise<MdLanguageClient> {
const serverMain = vscode.Uri.joinPath(context.extensionUri, 'server/dist/browser/workerMain.js');
const worker = new Worker(serverMain.toString());
worker.postMessage({ i10lLocation: vscode.l10n.uri?.toString() ?? '' });
return startClient((id: string, name: string, clientOptions: LanguageClientOptions) => {
return new LanguageClient(id, name, clientOptions, worker);
}, parser);
}
| extensions/markdown-language-features/src/extension.browser.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00016914958541747183,
0.00016825713100843132,
0.00016736044199205935,
0.0001682592264842242,
7.145770268834895e-7
] |
{
"id": 9,
"code_window": [
"\t\t/**\n",
"\t\t * Request access to a language model.\n",
"\t\t *\n",
"\t\t * *Note* that this function will throw an error when the user didn't grant access\n",
"\t\t *\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\t * - *Note 1:* This function will throw an error when the user didn't grant access or when the\n",
"\t\t * requested language model is not available.\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 81
} | #!/usr/bin/env sh
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
set -e
# Do not remove this check.
# Provides a way to skip the server requirements check from
# outside the install flow. A system process can create this
# file before the server is downloaded and installed.
#
# This check is duplicated between code-server-linux.sh and here
# since remote container calls into this script directly quite early
# before the usual server startup flow.
if [ -f "/tmp/vscode-skip-server-requirements-check" ]; then
echo "!!! WARNING: Skipping server pre-requisite check !!!"
echo "!!! Server stability is not guaranteed. Proceed at your own risk. !!!"
exit 0
fi
ARCH=$(uname -m)
found_required_glibc=0
found_required_glibcxx=0
# Extract the ID value from /etc/os-release
if [ -f /etc/os-release ]; then
OS_ID="$(cat /etc/os-release | grep -Eo 'ID=([^"]+)' | sed -n '1s/ID=//p')"
if [ "$OS_ID" = "nixos" ]; then
echo "Warning: NixOS detected, skipping GLIBC check"
exit 0
fi
fi
# Based on https://github.com/bminor/glibc/blob/520b1df08de68a3de328b65a25b86300a7ddf512/elf/cache.c#L162-L245
case $ARCH in
x86_64) LDCONFIG_ARCH="x86-64";;
armv7l | armv8l) LDCONFIG_ARCH="hard-float";;
arm64 | aarch64)
BITNESS=$(getconf LONG_BIT)
if [ "$BITNESS" = "32" ]; then
# Can have 32-bit userland on 64-bit kernel
LDCONFIG_ARCH="hard-float"
else
LDCONFIG_ARCH="AArch64"
fi
;;
esac
if [ "$OS_ID" != "alpine" ]; then
if [ -f /sbin/ldconfig ]; then
# Look up path
libstdcpp_paths=$(/sbin/ldconfig -p | grep 'libstdc++.so.6')
if [ "$(echo "$libstdcpp_paths" | wc -l)" -gt 1 ]; then
libstdcpp_path=$(echo "$libstdcpp_paths" | grep "$LDCONFIG_ARCH" | awk '{print $NF}')
else
libstdcpp_path=$(echo "$libstdcpp_paths" | awk '{print $NF}')
fi
elif [ -f /usr/lib/libstdc++.so.6 ]; then
# Typical path
libstdcpp_path='/usr/lib/libstdc++.so.6'
elif [ -f /usr/lib64/libstdc++.so.6 ]; then
# Typical path
libstdcpp_path='/usr/lib64/libstdc++.so.6'
else
echo "Warning: Can't find libstdc++.so or ldconfig, can't verify libstdc++ version"
fi
while [ -n "$libstdcpp_path" ]; do
# Extracts the version number from the path, e.g. libstdc++.so.6.0.22 -> 6.0.22
# which is then compared based on the fact that release versioning and symbol versioning
# are aligned for libstdc++. Refs https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html
# (i-e) GLIBCXX_3.4.<release> is provided by libstdc++.so.6.y.<release>
libstdcpp_path_line=$(echo "$libstdcpp_path" | head -n1)
libstdcpp_real_path=$(readlink -f "$libstdcpp_path_line")
libstdcpp_version=$(grep -ao 'GLIBCXX_[0-9]*\.[0-9]*\.[0-9]*' "$libstdcpp_real_path" | sort -V | tail -1)
libstdcpp_version_number=$(echo "$libstdcpp_version" | sed 's/GLIBCXX_//')
if [ "$(printf '%s\n' "3.4.24" "$libstdcpp_version_number" | sort -V | head -n1)" = "3.4.24" ]; then
found_required_glibcxx=1
break
fi
libstdcpp_path=$(echo "$libstdcpp_path" | tail -n +2) # remove first line
done
else
echo "Warning: alpine distro detected, skipping GLIBCXX check"
found_required_glibcxx=1
fi
if [ "$found_required_glibcxx" = "0" ]; then
echo "Warning: Missing GLIBCXX >= 3.4.25! from $libstdcpp_real_path"
fi
if [ "$OS_ID" = "alpine" ]; then
MUSL_RTLDLIST="/lib/ld-musl-aarch64.so.1 /lib/ld-musl-x86_64.so.1"
for rtld in ${MUSL_RTLDLIST}; do
if [ -x $rtld ]; then
musl_version=$("$rtld" --version 2>&1 | grep "Version" | awk '{print $NF}')
break
fi
done
if [ "$(printf '%s\n' "1.2.3" "$musl_version" | sort -V | head -n1)" != "1.2.3" ]; then
echo "Error: Unsupported alpine distribution. Please refer to our supported distro section https://aka.ms/vscode-remote/linux for additional information."
exit 99
fi
found_required_glibc=1
elif [ -z "$(ldd --version 2>&1 | grep 'musl libc')" ]; then
if [ -f /sbin/ldconfig ]; then
# Look up path
libc_paths=$(/sbin/ldconfig -p | grep 'libc.so.6')
if [ "$(echo "$libc_paths" | wc -l)" -gt 1 ]; then
libc_path=$(echo "$libc_paths" | grep "$LDCONFIG_ARCH" | awk '{print $NF}')
else
libc_path=$(echo "$libc_paths" | awk '{print $NF}')
fi
elif [ -f /usr/lib/libc.so.6 ]; then
# Typical path
libc_path='/usr/lib/libc.so.6'
elif [ -f /usr/lib64/libc.so.6 ]; then
# Typical path
libc_path='/usr/lib64/libc.so.6'
else
echo "Warning: Can't find libc.so or ldconfig, can't verify libc version"
fi
while [ -n "$libc_path" ]; do
# Rather than trusting the output of ldd --version (which is not always accurate)
# we instead use the version of the cached libc.so.6 file itself.
libc_path_line=$(echo "$libc_path" | head -n1)
libc_real_path=$(readlink -f "$libc_path_line")
libc_version=$(cat "$libc_real_path" | sed -n 's/.*release version \([0-9]\+\.[0-9]\+\).*/\1/p')
if [ "$(printf '%s\n' "2.28" "$libc_version" | sort -V | head -n1)" = "2.28" ]; then
found_required_glibc=1
break
fi
libc_path=$(echo "$libc_path" | tail -n +2) # remove first line
done
if [ "$found_required_glibc" = "0" ]; then
echo "Warning: Missing GLIBC >= 2.28! from $libc_real_path"
fi
else
echo "Warning: musl detected, skipping GLIBC check"
found_required_glibc=1
fi
if [ "$found_required_glibc" = "0" ] || [ "$found_required_glibcxx" = "0" ]; then
echo "Error: Missing required dependencies. Please refer to our FAQ https://aka.ms/vscode-remote/faq/old-linux for additional information."
# Custom exit code based on https://tldp.org/LDP/abs/html/exitcodes.html
#exit 99
fi
| resources/server/bin/helpers/check-requirements-linux.sh | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00021093733084853739,
0.00016958733613137156,
0.00016456381126772612,
0.00016647815937176347,
0.000010845400538528338
] |
{
"id": 10,
"code_window": [
"\t\t *\n",
"\t\t * @param id The id of the language model, e.g `copilot`\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects is access wasn't granted\n",
"\t\t */\n",
"\t\texport function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;\n",
"\n",
"\t\t/**\n",
"\t\t * The identifiers of all language models that are currently available.\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t * - *Note 2:* It is OK to hold on to the returned access object and use it later, but extensions\n",
"\t\t * should check {@link LanguageModelAccess.isRevoked} before using it.\n",
"\t\t *\n",
"\t\t * @param id The id of the language model, see {@link languageModels} for valid values.\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects if access wasn't granted\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* One request/response pair in chat history.
*/
export interface ChatAgentHistoryEntry {
/**
* The request that was sent to the chat agent.
*/
// TODO@API make this optional? Allow for response without request?
request: ChatAgentRequest;
/**
* The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
*/
response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
/**
* The result that was received from the chat agent.
*/
result: ChatAgentResult2;
}
// TODO@API class
// export interface ChatAgentResponse {
// /**
// * The content that was received from the chat agent. Only the progress parts that represent actual content (not metadata) are represented.
// */
// response: (ChatAgentContentProgress | ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart)[];
// /**
// * The result that was received from the chat agent.
// */
// result: ChatAgentResult2;
// }
export interface ChatAgentContext {
/**
* All of the chat messages so far in the current chat session.
*/
history: ChatAgentHistoryEntry[];
// TODO@API have "turns"
// history2: (ChatAgentRequest | ChatAgentResponse)[];
}
/**
* Represents an error result from a chat request.
*/
export interface ChatAgentErrorDetails {
/**
* An error message that is shown to the user.
*/
message: string;
/**
* If partial markdown content was sent over the `progress` callback before the response terminated, then this flag
* can be set to true and it will be rendered with incomplete markdown features patched up.
*
* For example, if the response terminated after sending part of a triple-backtick code block, then the editor will
* render it as a complete code block.
*/
responseIsIncomplete?: boolean;
/**
* If set to true, the response will be partly blurred out.
*/
responseIsFiltered?: boolean;
}
/**
* The result of a chat request.
*/
export interface ChatAgentResult2 {
/**
* If the request resulted in an error, this property defines the error details.
*/
errorDetails?: ChatAgentErrorDetails;
// TODO@API
// add CATCH-all signature [name:string]: string|boolean|number instead of `T extends...`
// readonly metadata: { readonly [key: string]: any };
}
/**
* Represents the type of user feedback received.
*/
export enum ChatAgentResultFeedbackKind {
/**
* The user marked the result as helpful.
*/
Unhelpful = 0,
/**
* The user marked the result as unhelpful.
*/
Helpful = 1,
}
/**
* Represents user feedback for a result.
*/
export interface ChatAgentResult2Feedback<TResult extends ChatAgentResult2> {
/**
* This instance of ChatAgentResult2 is the same instance that was returned from the chat agent,
* and it can be extended with arbitrary properties if needed.
*/
readonly result: TResult;
/**
* The kind of feedback that was received.
*/
readonly kind: ChatAgentResultFeedbackKind;
}
export interface ChatAgentSubCommand {
/**
* A short name by which this command is referred to in the UI, e.g. `fix` or
* `explain` for commands that fix an issue or explain code.
*
* **Note**: The name should be unique among the subCommands provided by this agent.
*/
readonly name: string;
/**
* Human-readable description explaining what this command does.
*/
readonly description: string;
/**
* When the user clicks this subCommand in `/help`, this text will be submitted to this subCommand
*/
readonly sampleRequest?: string;
/**
* Whether executing the command puts the
* chat into a persistent mode, where the
* subCommand is prepended to the chat input.
*/
readonly shouldRepopulate?: boolean;
/**
* Placeholder text to render in the chat input
* when the subCommand has been repopulated.
* Has no effect if `shouldRepopulate` is `false`.
*/
// TODO@API merge this with shouldRepopulate? so that invalid state cannot be represented?
readonly followupPlaceholder?: string;
}
export interface ChatAgentSubCommandProvider {
/**
* Returns a list of subCommands that its agent is capable of handling. A subCommand
* can be selected by the user and will then be passed to the {@link ChatAgentHandler handler}
* via the {@link ChatAgentRequest.subCommand subCommand} property.
*
*
* @param token A cancellation token.
* @returns A list of subCommands. The lack of a result can be signaled by returning `undefined`, `null`, or
* an empty array.
*/
provideSubCommands(token: CancellationToken): ProviderResult<ChatAgentSubCommand[]>;
}
// TODO@API This should become a progress type, and use vscode.Command
// TODO@API what's the when-property for? how about not returning it in the first place?
export interface ChatAgentCommandFollowup {
commandId: string;
args?: any[];
title: string; // supports codicon strings
when?: string;
}
/**
* A followup question suggested by the model.
*/
export interface ChatAgentReplyFollowup {
/**
* The message to send to the chat.
*/
message: string;
/**
* A tooltip to show when hovering over the followup.
*/
tooltip?: string;
/**
* A title to show the user, when it is different than the message.
*/
title?: string;
}
export type ChatAgentFollowup = ChatAgentCommandFollowup | ChatAgentReplyFollowup;
/**
* Will be invoked once after each request to get suggested followup questions to show the user. The user can click the followup to send it to the chat.
*/
export interface ChatAgentFollowupProvider<TResult extends ChatAgentResult2> {
/**
*
* @param result The same instance of the result object that was returned by the chat agent, and it can be extended with arbitrary properties if needed.
* @param token A cancellation token.
*/
provideFollowups(result: TResult, token: CancellationToken): ProviderResult<ChatAgentFollowup[]>;
}
export interface ChatAgent2<TResult extends ChatAgentResult2> {
/**
* The short name by which this agent is referred to in the UI, e.g `workspace`.
*/
readonly name: string;
/**
* The full name of this agent.
*/
fullName: string;
/**
* A human-readable description explaining what this agent does.
*/
description: string;
/**
* Icon for the agent shown in UI.
*/
iconPath?: Uri | {
/**
* The icon path for the light theme.
*/
light: Uri;
/**
* The icon path for the dark theme.
*/
dark: Uri;
} | ThemeIcon;
/**
* This provider will be called to retrieve the agent's subCommands.
*/
subCommandProvider?: ChatAgentSubCommandProvider;
/**
* This provider will be called once after each request to retrieve suggested followup questions.
*/
followupProvider?: ChatAgentFollowupProvider<TResult>;
// TODO@
// notify(request: ChatResponsePart, reference: string): boolean;
// TODO@API
// clear NEVER happens
// onDidClearResult(value: TResult): void;
/**
* When the user clicks this agent in `/help`, this text will be submitted to this subCommand
*/
sampleRequest?: string;
/**
* An event that fires whenever feedback for a result is received, e.g. when a user up- or down-votes
* a result.
*
* The passed {@link ChatAgentResult2Feedback.result result} is guaranteed to be the same instance that was
* previously returned from this chat agent.
*/
onDidReceiveFeedback: Event<ChatAgentResult2Feedback<TResult>>;
/**
* Dispose this agent and free resources
*/
dispose(): void;
}
export interface ChatAgentRequest {
/**
* The prompt entered by the user. The {@link ChatAgent2.name name} of the agent or the {@link ChatAgentSubCommand.name subCommand}
* are not part of the prompt.
*
* @see {@link ChatAgentRequest.subCommand}
*/
prompt: string;
/**
* The ID of the chat agent to which this request was directed.
*/
agentId: string;
/**
* The name of the {@link ChatAgentSubCommand subCommand} that was selected for this request.
*/
subCommand?: string;
variables: Record<string, ChatVariableValue[]>;
// TODO@API argumented prompt, reverse order!
// variables2: { start:number, length:number, values: ChatVariableValue[]}[]
}
export interface ChatAgentResponseStream {
/**
* Push a text part to this stream. Short-hand for
* `push(new ChatResponseTextPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A plain text value.
* @returns This stream.
*/
text(value: string): ChatAgentResponseStream;
/**
* Push a markdown part to this stream. Short-hand for
* `push(new ChatResponseMarkdownPart(value))`.
*
* @see {@link ChatAgentResponseStream.push}
* @param value A markdown string or a string that should be interpreted as markdown.
* @returns This stream.
*/
markdown(value: string | MarkdownString): ChatAgentResponseStream;
/**
* Push an anchor part to this stream. Short-hand for
* `push(new ChatResponseAnchorPart(value, title))`.
*
* @param value A uri or location
* @param title An optional title that is rendered with value
* @returns This stream.
*/
anchor(value: Uri | Location, title?: string): ChatAgentResponseStream;
/**
* Push a filetree part to this stream. Short-hand for
* `push(new ChatResponseFileTreePart(value))`.
*
* @param value File tree data.
* @param baseUri The base uri to which this file tree is relative to.
* @returns This stream.
*/
filetree(value: ChatResponseFileTree[], baseUri: Uri): ChatAgentResponseStream;
/**
* Push a progress part to this stream. Short-hand for
* `push(new ChatResponseProgressPart(value))`.
*
* @param value
* @returns This stream.
*/
// TODO@API is this always inline or not
// TODO@API is this markdown or string?
// TODO@API this influences the rendering, it inserts new lines which is likely a bug
progress(value: string): ChatAgentResponseStream;
/**
* Push a reference to this stream. Short-hand for
* `push(new ChatResponseReferencePart(value))`.
*
* *Note* that the reference is not rendered inline with the response.
*
* @param value A uri or location
* @returns This stream.
*/
// TODO@API support non-file uris, like http://example.com
// TODO@API support mapped edits
reference(value: Uri | Location): ChatAgentResponseStream;
/**
* Pushes a part to this stream.
*
* @param part A response part, rendered or metadata
*/
push(part: ChatResponsePart): ChatAgentResponseStream;
/**
* @deprecated use above methods instread
*/
report(value: ChatAgentProgress): void;
}
// TODO@API
// support ChatResponseCommandPart
// support ChatResponseTextEditPart
// support ChatResponseCodeReferencePart
// TODO@API should the name suffix differentiate between rendered items (XYZPart)
// and metadata like XYZItem
export class ChatResponseTextPart {
value: string;
constructor(value: string);
}
export class ChatResponseMarkdownPart {
value: MarkdownString;
constructor(value: string | MarkdownString);
}
export interface ChatResponseFileTree {
name: string;
children?: ChatResponseFileTree[];
}
export class ChatResponseFileTreePart {
value: ChatResponseFileTree[];
baseUri: Uri;
constructor(value: ChatResponseFileTree[], baseUri: Uri);
}
export class ChatResponseAnchorPart {
value: Uri | Location | SymbolInformation;
title?: string;
constructor(value: Uri | Location | SymbolInformation, title?: string);
}
export class ChatResponseProgressPart {
value: string;
constructor(value: string);
}
export class ChatResponseReferencePart {
value: Uri | Location;
constructor(value: Uri | Location);
}
export type ChatResponsePart = ChatResponseTextPart | ChatResponseMarkdownPart | ChatResponseFileTreePart | ChatResponseAnchorPart
| ChatResponseProgressPart | ChatResponseReferencePart;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentContentProgress =
| ChatAgentContent
| ChatAgentFileTree
| ChatAgentInlineContentReference;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentMetadataProgress =
| ChatAgentUsedContext
| ChatAgentContentReference
| ChatAgentProgressMessage;
/**
* @deprecated use ChatAgentResponseStream instead
*/
export type ChatAgentProgress = ChatAgentContentProgress | ChatAgentMetadataProgress;
/**
* Is displayed in the UI to communicate steps of progress to the user. Should be used when the agent may be slow to respond, e.g. due to doing extra work before sending the actual request to the LLM.
*/
export interface ChatAgentProgressMessage {
message: string;
}
/**
* Indicates a piece of content that was used by the chat agent while processing the request. Will be displayed to the user.
*/
export interface ChatAgentContentReference {
/**
* The resource that was referenced.
*/
reference: Uri | Location;
}
/**
* A reference to a piece of content that will be rendered inline with the markdown content.
*/
export interface ChatAgentInlineContentReference {
/**
* The resource being referenced.
*/
inlineReference: Uri | Location;
/**
* An alternate title for the resource.
*/
title?: string;
}
/**
* A piece of the chat response's content. Will be merged with other progress pieces as needed, and rendered as markdown.
*/
export interface ChatAgentContent {
/**
* The content as a string of markdown source.
*/
content: string;
}
/**
* Represents a tree, such as a file and directory structure, rendered in the chat response.
*/
export interface ChatAgentFileTree {
/**
* The root node of the tree.
*/
treeData: ChatAgentFileTreeData;
}
/**
* Represents a node in a chat response tree.
*/
export interface ChatAgentFileTreeData {
/**
* A human-readable string describing this node.
*/
label: string;
/**
* A Uri for this node, opened when it's clicked.
*/
// TODO@API why label and uri. Can the former be derived from the latter?
// TODO@API don't use uri but just names? This API allows to to build nonsense trees where the data structure doesn't match the uris
// path-structure.
uri: Uri;
/**
* The type of this node. Defaults to {@link FileType.Directory} if it has {@link ChatAgentFileTreeData.children children}.
*/
// TODO@API cross API usage
type?: FileType;
/**
* The children of this node.
*/
children?: ChatAgentFileTreeData[];
}
export interface ChatAgentDocumentContext {
uri: Uri;
version: number;
ranges: Range[];
}
/**
* Document references that should be used by the MappedEditsProvider.
*/
export interface ChatAgentUsedContext {
documents: ChatAgentDocumentContext[];
}
export type ChatAgentHandler = (request: ChatAgentRequest, context: ChatAgentContext, response: ChatAgentResponseStream, token: CancellationToken) => ProviderResult<ChatAgentResult2>;
export namespace chat {
/**
* Create a new {@link ChatAgent2 chat agent} instance.
*
* @param name Short name by which this agent is referred to in the UI
* @param handler The reply-handler of the agent.
* @returns A new chat agent
*/
export function createChatAgent<TResult extends ChatAgentResult2>(name: string, handler: ChatAgentHandler): ChatAgent2<TResult>;
/**
* Register a variable which can be used in a chat request to any agent.
* @param name The name of the variable, to be used in the chat input as `#name`.
* @param description A description of the variable for the chat input suggest widget.
* @param resolver Will be called to provide the chat variable's value when it is used.
*/
export function registerVariable(name: string, description: string, resolver: ChatVariableResolver): Disposable;
}
/**
* The detail level of this chat variable value.
*/
export enum ChatVariableLevel {
Short = 1,
Medium = 2,
Full = 3
}
export interface ChatVariableValue {
/**
* The detail level of this chat variable value. If possible, variable resolvers should try to offer shorter values that will consume fewer tokens in an LLM prompt.
*/
level: ChatVariableLevel;
/**
* The variable's value, which can be included in an LLM prompt as-is, or the chat agent may decide to read the value and do something else with it.
*/
value: string | Uri;
/**
* A description of this value, which could be provided to the LLM as a hint.
*/
description?: string;
}
export interface ChatVariableContext {
/**
* The message entered by the user, which includes this variable.
*/
prompt: string;
}
export interface ChatVariableResolver {
/**
* A callback to resolve the value of a chat variable.
* @param name The name of the variable.
* @param context Contextual information about this chat request.
* @param token A cancellation token.
*/
resolve(name: string, context: ChatVariableContext, token: CancellationToken): ProviderResult<ChatVariableValue[]>;
}
}
| src/vscode-dts/vscode.proposed.chatAgents2.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0002347118133911863,
0.00017103621212299913,
0.00015960376185830683,
0.00016878620954230428,
0.000010341014785808511
] |
{
"id": 10,
"code_window": [
"\t\t *\n",
"\t\t * @param id The id of the language model, e.g `copilot`\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects is access wasn't granted\n",
"\t\t */\n",
"\t\texport function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;\n",
"\n",
"\t\t/**\n",
"\t\t * The identifiers of all language models that are currently available.\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t * - *Note 2:* It is OK to hold on to the returned access object and use it later, but extensions\n",
"\t\t * should check {@link LanguageModelAccess.isRevoked} before using it.\n",
"\t\t *\n",
"\t\t * @param id The id of the language model, see {@link languageModels} for valid values.\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects if access wasn't granted\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withBrowserDefaults = require('../shared.webpack.config').browser;
const config = withBrowserDefaults({
context: __dirname,
entry: {
extension: './src/npmBrowserMain.ts'
},
output: {
filename: 'npmBrowserMain.js'
},
resolve: {
fallback: {
'child_process': false
}
}
});
module.exports = config;
| extensions/npm/extension-browser.webpack.config.js | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.0001780969905667007,
0.00017648364882916212,
0.0001742288877721876,
0.00017712506814859807,
0.0000016429888773927814
] |
{
"id": 10,
"code_window": [
"\t\t *\n",
"\t\t * @param id The id of the language model, e.g `copilot`\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects is access wasn't granted\n",
"\t\t */\n",
"\t\texport function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;\n",
"\n",
"\t\t/**\n",
"\t\t * The identifiers of all language models that are currently available.\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t * - *Note 2:* It is OK to hold on to the returned access object and use it later, but extensions\n",
"\t\t * should check {@link LanguageModelAccess.isRevoked} before using it.\n",
"\t\t *\n",
"\t\t * @param id The id of the language model, see {@link languageModels} for valid values.\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects if access wasn't granted\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { IStorageService, IStorageValueChangeEvent, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
export interface IStoredValueSerialization<T> {
deserialize(data: string): T;
serialize(data: T): string;
}
const defaultSerialization: IStoredValueSerialization<any> = {
deserialize: d => JSON.parse(d),
serialize: d => JSON.stringify(d),
};
interface IStoredValueOptions<T> {
key: string;
scope: StorageScope;
target: StorageTarget;
serialization?: IStoredValueSerialization<T>;
}
/**
* todo@connor4312: is this worthy to be in common?
*/
export class StoredValue<T> extends Disposable {
private readonly serialization: IStoredValueSerialization<T>;
private readonly key: string;
private readonly scope: StorageScope;
private readonly target: StorageTarget;
private value?: T;
/**
* Emitted whenever the value is updated or deleted.
*/
public readonly onDidChange: Event<IStorageValueChangeEvent>;
constructor(
options: IStoredValueOptions<T>,
@IStorageService private readonly storage: IStorageService,
) {
super();
this.key = options.key;
this.scope = options.scope;
this.target = options.target;
this.serialization = options.serialization ?? defaultSerialization;
this.onDidChange = this.storage.onDidChangeValue(this.scope, this.key, this._register(new DisposableStore()));
}
/**
* Reads the value, returning the undefined if it's not set.
*/
public get(): T | undefined;
/**
* Reads the value, returning the default value if it's not set.
*/
public get(defaultValue: T): T;
public get(defaultValue?: T): T | undefined {
if (this.value === undefined) {
const value = this.storage.get(this.key, this.scope);
this.value = value === undefined ? defaultValue : this.serialization.deserialize(value);
}
return this.value;
}
/**
* Persists changes to the value.
* @param value
*/
public store(value: T) {
this.value = value;
this.storage.store(this.key, this.serialization.serialize(value), this.scope, this.target);
}
/**
* Delete an element stored under the provided key from storage.
*/
public delete() {
this.storage.remove(this.key, this.scope);
}
}
| src/vs/workbench/contrib/testing/common/storedValue.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017564205336384475,
0.0001704249734757468,
0.000166496800375171,
0.000168832644703798,
0.000003055170736843138
] |
{
"id": 10,
"code_window": [
"\t\t *\n",
"\t\t * @param id The id of the language model, e.g `copilot`\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects is access wasn't granted\n",
"\t\t */\n",
"\t\texport function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;\n",
"\n",
"\t\t/**\n",
"\t\t * The identifiers of all language models that are currently available.\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t * - *Note 2:* It is OK to hold on to the returned access object and use it later, but extensions\n",
"\t\t * should check {@link LanguageModelAccess.isRevoked} before using it.\n",
"\t\t *\n",
"\t\t * @param id The id of the language model, see {@link languageModels} for valid values.\n",
"\t\t * @returns A thenable that resolves to a language model access object, rejects if access wasn't granted\n"
],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 83
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Transform } from 'stream';
export const splitNewLines = () => new StreamSplitter('\n'.charCodeAt(0));
/**
* Copied and simplified from src\vs\base\node\nodeStreams.ts
*
* Exception: does not include the split character in the output.
*/
export class StreamSplitter extends Transform {
private buffer: Buffer | undefined;
constructor(private readonly splitter: number) {
super();
}
override _transform(chunk: Buffer, _encoding: string, callback: (error?: Error | null, data?: any) => void): void {
if (!this.buffer) {
this.buffer = chunk;
} else {
this.buffer = Buffer.concat([this.buffer, chunk]);
}
let offset = 0;
while (offset < this.buffer.length) {
const index = this.buffer.indexOf(this.splitter, offset);
if (index === -1) {
break;
}
this.push(this.buffer.subarray(offset, index));
offset = index + 1;
}
this.buffer = offset === this.buffer.length ? undefined : this.buffer.subarray(offset);
callback();
}
override _flush(callback: (error?: Error | null, data?: any) => void): void {
if (this.buffer) {
this.push(this.buffer);
}
callback();
}
}
| extensions/tunnel-forwarding/src/split.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017852832388598472,
0.00017551843484397978,
0.00017384672537446022,
0.00017519001266919076,
0.000001491853254265152
] |
{
"id": 11,
"code_window": [
"\t\texport const languageModels: readonly string[];\n",
"\n",
"\t\t/**\n",
"\t\t * An event that is fired when the set of available language models changes.\n",
"\t\t */\n",
"\t\t//@API is this really needed?\n",
"\t\texport const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;\n",
"\t}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 96
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
export interface LanguageModelResponse {
/**
* The overall result of the request which represents failure or success
* but _not_ the actual response or responses
*/
// TODO@API define this type!
result: Thenable<unknown>;
stream: AsyncIterable<string>;
}
/**
* Represents access to using a language model. Access can be revoked at any time and extension
* must check if the access is {@link LanguageModelAccess.isRevoked still valid} before using it.
*/
export interface LanguageModelAccess {
/**
* Whether the access to the language model has been revoked.
*/
readonly isRevoked: boolean;
/**
* An event that is fired when the access the language model has has been revoked or re-granted.
*/
readonly onDidChangeAccess: Event<void>;
/**
* The name of the model.
*
* It is expected that the model name can be used to lookup properties like token limits or what
* `options` are available.
*/
readonly model: string;
/**
* Make a request to the language model.
*
* *Note:* This will throw an error if access has been revoked.
*
* @param messages
* @param options
*/
makeRequest(messages: ChatMessage[], options: { [name: string]: any }, token: CancellationToken): LanguageModelResponse;
}
export interface LanguageModelAccessOptions {
/**
* A human-readable message that explains why access to a language model is needed and what feature is enabled by it.
*/
justification?: string;
}
/**
* An event describing the change in the set of available language models.
*/
export interface LanguageModelChangeEvent {
/**
* Added language models.
*/
readonly added: readonly string[];
/**
* Removed language models.
*/
readonly removed: readonly string[];
}
//@API DEFINE the namespace for this: env, lm, ai?
export namespace chat {
/**
* Request access to a language model.
*
* *Note* that this function will throw an error when the user didn't grant access
*
* @param id The id of the language model, e.g `copilot`
* @returns A thenable that resolves to a language model access object, rejects is access wasn't granted
*/
export function requestLanguageModelAccess(id: string, options?: LanguageModelAccessOptions): Thenable<LanguageModelAccess>;
/**
* The identifiers of all language models that are currently available.
*/
export const languageModels: readonly string[];
/**
* An event that is fired when the set of available language models changes.
*/
//@API is this really needed?
export const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;
}
}
| src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts | 1 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.997157096862793,
0.09195797890424728,
0.00016451062401756644,
0.0004914547898806632,
0.2862538695335388
] |
{
"id": 11,
"code_window": [
"\t\texport const languageModels: readonly string[];\n",
"\n",
"\t\t/**\n",
"\t\t * An event that is fired when the set of available language models changes.\n",
"\t\t */\n",
"\t\t//@API is this really needed?\n",
"\t\texport const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;\n",
"\t}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 96
} | /*---------------------------------------------------------------------------------------------
* 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 terminalEncoding from 'vs/base/node/terminalEncoding';
import * as encoding from 'vs/workbench/services/textfile/common/encoding';
suite('Encoding', function () {
this.timeout(10000);
test('resolve terminal encoding (detect)', async function () {
const enc = await terminalEncoding.resolveTerminalEncoding();
assert.ok(enc.length > 0);
});
test('resolve terminal encoding (environment)', async function () {
process.env['VSCODE_CLI_ENCODING'] = 'utf16le';
const enc = await terminalEncoding.resolveTerminalEncoding();
assert.ok(await encoding.encodingExists(enc));
assert.strictEqual(enc, 'utf16le');
});
});
| src/vs/workbench/services/textfile/test/node/encoding/encoding.integrationTest.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017668752116151154,
0.0001754975673975423,
0.00017341460625175387,
0.00017639058933127671,
0.0000014778593140363228
] |
{
"id": 11,
"code_window": [
"\t\texport const languageModels: readonly string[];\n",
"\n",
"\t\t/**\n",
"\t\t * An event that is fired when the set of available language models changes.\n",
"\t\t */\n",
"\t\t//@API is this really needed?\n",
"\t\texport const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;\n",
"\t}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 96
} | /*---------------------------------------------------------------------------------------------
* 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 collections from 'vs/base/common/collections';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
suite('Collections', () => {
ensureNoDisposablesAreLeakedInTestSuite();
test('groupBy', () => {
const group1 = 'a', group2 = 'b';
const value1 = 1, value2 = 2, value3 = 3;
const source = [
{ key: group1, value: value1 },
{ key: group1, value: value2 },
{ key: group2, value: value3 },
];
const grouped = collections.groupBy(source, x => x.key);
// Group 1
assert.strictEqual(grouped[group1].length, 2);
assert.strictEqual(grouped[group1][0].value, value1);
assert.strictEqual(grouped[group1][1].value, value2);
// Group 2
assert.strictEqual(grouped[group2].length, 1);
assert.strictEqual(grouped[group2][0].value, value3);
});
});
| src/vs/base/test/common/collections.test.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.00017794728046283126,
0.0001750517840264365,
0.0001723937748465687,
0.00017493304039817303,
0.0000020927768673573155
] |
{
"id": 11,
"code_window": [
"\t\texport const languageModels: readonly string[];\n",
"\n",
"\t\t/**\n",
"\t\t * An event that is fired when the set of available language models changes.\n",
"\t\t */\n",
"\t\t//@API is this really needed?\n",
"\t\texport const onDidChangeLanguageModels: Event<LanguageModelChangeEvent>;\n",
"\t}\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vscode-dts/vscode.proposed.chatRequestAccess.d.ts",
"type": "replace",
"edit_start_line_idx": 96
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import * as errors from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { combinedDisposable } from 'vs/base/common/lifecycle';
import { Schemas, matchesScheme } from 'vs/base/common/network';
import Severity from 'vs/base/common/severity';
import { URI } from 'vs/base/common/uri';
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
import { score } from 'vs/editor/common/languageSelector';
import * as languageConfiguration from 'vs/editor/common/languages/languageConfiguration';
import { OverviewRulerLane } from 'vs/editor/common/model';
import { ExtensionIdentifierSet, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import * as files from 'vs/platform/files/common/files';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ILogService, ILoggerService, LogLevel } from 'vs/platform/log/common/log';
import { getRemoteName } from 'vs/platform/remote/common/remoteHosts';
import { TelemetryTrustedValue } from 'vs/platform/telemetry/common/telemetryUtils';
import { EditSessionIdentityMatch } from 'vs/platform/workspace/common/editSessions';
import { CandidatePortSource, ExtHostContext, ExtHostLogLevelServiceShape, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostRelatedInformation } from 'vs/workbench/api/common/extHostAiRelatedInformation';
import { ExtHostApiCommands } from 'vs/workbench/api/common/extHostApiCommands';
import { IExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService';
import { ExtHostAuthentication } from 'vs/workbench/api/common/extHostAuthentication';
import { ExtHostBulkEdits } from 'vs/workbench/api/common/extHostBulkEdits';
import { ExtHostChat } from 'vs/workbench/api/common/extHostChat';
import { ExtHostChatAgents2 } from 'vs/workbench/api/common/extHostChatAgents2';
import { ExtHostChatProvider } from 'vs/workbench/api/common/extHostChatProvider';
import { ExtHostChatVariables } from 'vs/workbench/api/common/extHostChatVariables';
import { ExtHostClipboard } from 'vs/workbench/api/common/extHostClipboard';
import { ExtHostEditorInsets } from 'vs/workbench/api/common/extHostCodeInsets';
import { IExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { createExtHostComments } from 'vs/workbench/api/common/extHostComments';
import { ExtHostConfigProvider, IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration';
import { ExtHostCustomEditors } from 'vs/workbench/api/common/extHostCustomEditors';
import { IExtHostDebugService } from 'vs/workbench/api/common/extHostDebugService';
import { IExtHostDecorations } from 'vs/workbench/api/common/extHostDecorations';
import { ExtHostDiagnostics } from 'vs/workbench/api/common/extHostDiagnostics';
import { ExtHostDialogs } from 'vs/workbench/api/common/extHostDialogs';
import { ExtHostDocumentContentProvider } from 'vs/workbench/api/common/extHostDocumentContentProviders';
import { ExtHostDocumentSaveParticipant } from 'vs/workbench/api/common/extHostDocumentSaveParticipant';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import { IExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { IExtHostEditorTabs } from 'vs/workbench/api/common/extHostEditorTabs';
import { ExtHostAiEmbeddingVector } from 'vs/workbench/api/common/extHostEmbeddingVector';
import { Extension, IExtHostExtensionService } from 'vs/workbench/api/common/extHostExtensionService';
import { ExtHostFileSystem } from 'vs/workbench/api/common/extHostFileSystem';
import { IExtHostConsumerFileSystem } from 'vs/workbench/api/common/extHostFileSystemConsumer';
import { ExtHostFileSystemEventService, FileSystemWatcherCreateOptions } from 'vs/workbench/api/common/extHostFileSystemEventService';
import { IExtHostFileSystemInfo } from 'vs/workbench/api/common/extHostFileSystemInfo';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { ExtHostInteractiveEditor } from 'vs/workbench/api/common/extHostInlineChat';
import { ExtHostInteractive } from 'vs/workbench/api/common/extHostInteractive';
import { ExtHostIssueReporter } from 'vs/workbench/api/common/extHostIssueReporter';
import { ExtHostLabelService } from 'vs/workbench/api/common/extHostLabelService';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures';
import { ExtHostLanguages } from 'vs/workbench/api/common/extHostLanguages';
import { IExtHostLocalizationService } from 'vs/workbench/api/common/extHostLocalizationService';
import { IExtHostManagedSockets } from 'vs/workbench/api/common/extHostManagedSockets';
import { ExtHostMessageService } from 'vs/workbench/api/common/extHostMessageService';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { ExtHostNotebookDocumentSaveParticipant } from 'vs/workbench/api/common/extHostNotebookDocumentSaveParticipant';
import { ExtHostNotebookDocuments } from 'vs/workbench/api/common/extHostNotebookDocuments';
import { ExtHostNotebookEditors } from 'vs/workbench/api/common/extHostNotebookEditors';
import { ExtHostNotebookKernels } from 'vs/workbench/api/common/extHostNotebookKernels';
import { ExtHostNotebookRenderers } from 'vs/workbench/api/common/extHostNotebookRenderers';
import { IExtHostOutputService } from 'vs/workbench/api/common/extHostOutput';
import { ExtHostProfileContentHandlers } from 'vs/workbench/api/common/extHostProfileContentHandler';
import { ExtHostProgress } from 'vs/workbench/api/common/extHostProgress';
import { ExtHostQuickDiff } from 'vs/workbench/api/common/extHostQuickDiff';
import { createExtHostQuickOpen } from 'vs/workbench/api/common/extHostQuickOpen';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ExtHostSCM } from 'vs/workbench/api/common/extHostSCM';
import { IExtHostSearch } from 'vs/workbench/api/common/extHostSearch';
import { IExtHostSecretState } from 'vs/workbench/api/common/extHostSecretState';
import { ExtHostShare } from 'vs/workbench/api/common/extHostShare';
import { ExtHostSpeech } from 'vs/workbench/api/common/extHostSpeech';
import { ExtHostStatusBar } from 'vs/workbench/api/common/extHostStatusBar';
import { IExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
import { IExtHostTask } from 'vs/workbench/api/common/extHostTask';
import { ExtHostTelemetryLogger, IExtHostTelemetry, isNewAppInstall } from 'vs/workbench/api/common/extHostTelemetry';
import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService';
import { ExtHostTesting } from 'vs/workbench/api/common/extHostTesting';
import { ExtHostEditors } from 'vs/workbench/api/common/extHostTextEditors';
import { ExtHostTheming } from 'vs/workbench/api/common/extHostTheming';
import { ExtHostTimeline } from 'vs/workbench/api/common/extHostTimeline';
import { ExtHostTreeViews } from 'vs/workbench/api/common/extHostTreeViews';
import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';
import { ExtHostUriOpeners } from 'vs/workbench/api/common/extHostUriOpener';
import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService';
import { ExtHostUrls } from 'vs/workbench/api/common/extHostUrls';
import { ExtHostWebviews } from 'vs/workbench/api/common/extHostWebview';
import { ExtHostWebviewPanels } from 'vs/workbench/api/common/extHostWebviewPanels';
import { ExtHostWebviewViews } from 'vs/workbench/api/common/extHostWebviewView';
import { IExtHostWindow } from 'vs/workbench/api/common/extHostWindow';
import { IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug';
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
import { UIKind } from 'vs/workbench/services/extensions/common/extensionHostProtocol';
import { checkProposedApiEnabled, isProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions';
import { ProxyIdentifier } from 'vs/workbench/services/extensions/common/proxyIdentifier';
import { TextSearchCompleteMessageType } from 'vs/workbench/services/search/common/searchExtTypes';
import type * as vscode from 'vscode';
export interface IExtensionRegistries {
mine: ExtensionDescriptionRegistry;
all: ExtensionDescriptionRegistry;
}
export interface IExtensionApiFactory {
(extension: IExtensionDescription, extensionInfo: IExtensionRegistries, configProvider: ExtHostConfigProvider): typeof vscode;
}
/**
* This method instantiates and returns the extension API surface
*/
export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): IExtensionApiFactory {
// services
const initData = accessor.get(IExtHostInitDataService);
const extHostFileSystemInfo = accessor.get(IExtHostFileSystemInfo);
const extHostConsumerFileSystem = accessor.get(IExtHostConsumerFileSystem);
const extensionService = accessor.get(IExtHostExtensionService);
const extHostWorkspace = accessor.get(IExtHostWorkspace);
const extHostTelemetry = accessor.get(IExtHostTelemetry);
const extHostConfiguration = accessor.get(IExtHostConfiguration);
const uriTransformer = accessor.get(IURITransformerService);
const rpcProtocol = accessor.get(IExtHostRpcService);
const extHostStorage = accessor.get(IExtHostStorage);
const extensionStoragePaths = accessor.get(IExtensionStoragePaths);
const extHostLoggerService = accessor.get(ILoggerService);
const extHostLogService = accessor.get(ILogService);
const extHostTunnelService = accessor.get(IExtHostTunnelService);
const extHostApiDeprecation = accessor.get(IExtHostApiDeprecationService);
const extHostWindow = accessor.get(IExtHostWindow);
const extHostSecretState = accessor.get(IExtHostSecretState);
const extHostEditorTabs = accessor.get(IExtHostEditorTabs);
const extHostManagedSockets = accessor.get(IExtHostManagedSockets);
// register addressable instances
rpcProtocol.set(ExtHostContext.ExtHostFileSystemInfo, extHostFileSystemInfo);
rpcProtocol.set(ExtHostContext.ExtHostLogLevelServiceShape, <ExtHostLogLevelServiceShape><any>extHostLoggerService);
rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
rpcProtocol.set(ExtHostContext.ExtHostStorage, extHostStorage);
rpcProtocol.set(ExtHostContext.ExtHostTunnelService, extHostTunnelService);
rpcProtocol.set(ExtHostContext.ExtHostWindow, extHostWindow);
rpcProtocol.set(ExtHostContext.ExtHostSecretState, extHostSecretState);
rpcProtocol.set(ExtHostContext.ExtHostTelemetry, extHostTelemetry);
rpcProtocol.set(ExtHostContext.ExtHostEditorTabs, extHostEditorTabs);
rpcProtocol.set(ExtHostContext.ExtHostManagedSockets, extHostManagedSockets);
// automatically create and register addressable instances
const extHostDecorations = rpcProtocol.set(ExtHostContext.ExtHostDecorations, accessor.get(IExtHostDecorations));
const extHostDocumentsAndEditors = rpcProtocol.set(ExtHostContext.ExtHostDocumentsAndEditors, accessor.get(IExtHostDocumentsAndEditors));
const extHostCommands = rpcProtocol.set(ExtHostContext.ExtHostCommands, accessor.get(IExtHostCommands));
const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, accessor.get(IExtHostTerminalService));
const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, accessor.get(IExtHostDebugService));
const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, accessor.get(IExtHostSearch));
const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, accessor.get(IExtHostTask));
const extHostOutputService = rpcProtocol.set(ExtHostContext.ExtHostOutputService, accessor.get(IExtHostOutputService));
const extHostLocalization = rpcProtocol.set(ExtHostContext.ExtHostLocalization, accessor.get(IExtHostLocalizationService));
// manually create and register addressable instances
const extHostUrls = rpcProtocol.set(ExtHostContext.ExtHostUrls, new ExtHostUrls(rpcProtocol));
const extHostDocuments = rpcProtocol.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors));
const extHostDocumentContentProviders = rpcProtocol.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(rpcProtocol, extHostDocumentsAndEditors, extHostLogService));
const extHostDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostLogService, extHostDocuments, rpcProtocol.getProxy(MainContext.MainThreadBulkEdits)));
const extHostNotebook = rpcProtocol.set(ExtHostContext.ExtHostNotebook, new ExtHostNotebookController(rpcProtocol, extHostCommands, extHostDocumentsAndEditors, extHostDocuments, extHostConsumerFileSystem, extHostSearch));
const extHostNotebookDocuments = rpcProtocol.set(ExtHostContext.ExtHostNotebookDocuments, new ExtHostNotebookDocuments(extHostNotebook));
const extHostNotebookEditors = rpcProtocol.set(ExtHostContext.ExtHostNotebookEditors, new ExtHostNotebookEditors(extHostLogService, extHostNotebook));
const extHostNotebookKernels = rpcProtocol.set(ExtHostContext.ExtHostNotebookKernels, new ExtHostNotebookKernels(rpcProtocol, initData, extHostNotebook, extHostCommands, extHostLogService));
const extHostNotebookRenderers = rpcProtocol.set(ExtHostContext.ExtHostNotebookRenderers, new ExtHostNotebookRenderers(rpcProtocol, extHostNotebook));
const extHostNotebookDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostNotebookDocumentSaveParticipant, new ExtHostNotebookDocumentSaveParticipant(extHostLogService, extHostNotebook, rpcProtocol.getProxy(MainContext.MainThreadBulkEdits)));
const extHostEditors = rpcProtocol.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(rpcProtocol, extHostDocumentsAndEditors));
const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands, extHostLogService));
const extHostEditorInsets = rpcProtocol.set(ExtHostContext.ExtHostEditorInsets, new ExtHostEditorInsets(rpcProtocol.getProxy(MainContext.MainThreadEditorInsets), extHostEditors, initData.remote));
const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol, extHostLogService, extHostFileSystemInfo, extHostDocumentsAndEditors));
const extHostLanguages = rpcProtocol.set(ExtHostContext.ExtHostLanguages, new ExtHostLanguages(rpcProtocol, extHostDocuments, extHostCommands.converter, uriTransformer));
const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, uriTransformer, extHostDocuments, extHostCommands, extHostDiagnostics, extHostLogService, extHostApiDeprecation, extHostTelemetry));
const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures));
const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService(rpcProtocol, extHostLogService, extHostDocumentsAndEditors));
const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, createExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands));
const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostDocuments, extHostLogService));
const extHostQuickDiff = rpcProtocol.set(ExtHostContext.ExtHostQuickDiff, new ExtHostQuickDiff(rpcProtocol, uriTransformer));
const extHostShare = rpcProtocol.set(ExtHostContext.ExtHostShare, new ExtHostShare(rpcProtocol, uriTransformer));
const extHostComment = rpcProtocol.set(ExtHostContext.ExtHostComments, createExtHostComments(rpcProtocol, extHostCommands, extHostDocuments));
const extHostProgress = rpcProtocol.set(ExtHostContext.ExtHostProgress, new ExtHostProgress(rpcProtocol.getProxy(MainContext.MainThreadProgress)));
const extHostLabelService = rpcProtocol.set(ExtHostContext.ExtHostLabelService, new ExtHostLabelService(rpcProtocol));
const extHostTheming = rpcProtocol.set(ExtHostContext.ExtHostTheming, new ExtHostTheming(rpcProtocol));
const extHostAuthentication = rpcProtocol.set(ExtHostContext.ExtHostAuthentication, new ExtHostAuthentication(rpcProtocol));
const extHostTimeline = rpcProtocol.set(ExtHostContext.ExtHostTimeline, new ExtHostTimeline(rpcProtocol, extHostCommands));
const extHostWebviews = rpcProtocol.set(ExtHostContext.ExtHostWebviews, new ExtHostWebviews(rpcProtocol, initData.remote, extHostWorkspace, extHostLogService, extHostApiDeprecation));
const extHostWebviewPanels = rpcProtocol.set(ExtHostContext.ExtHostWebviewPanels, new ExtHostWebviewPanels(rpcProtocol, extHostWebviews, extHostWorkspace));
const extHostCustomEditors = rpcProtocol.set(ExtHostContext.ExtHostCustomEditors, new ExtHostCustomEditors(rpcProtocol, extHostDocuments, extensionStoragePaths, extHostWebviews, extHostWebviewPanels));
const extHostWebviewViews = rpcProtocol.set(ExtHostContext.ExtHostWebviewViews, new ExtHostWebviewViews(rpcProtocol, extHostWebviews));
const extHostTesting = rpcProtocol.set(ExtHostContext.ExtHostTesting, new ExtHostTesting(rpcProtocol, extHostLogService, extHostCommands, extHostDocumentsAndEditors));
const extHostUriOpeners = rpcProtocol.set(ExtHostContext.ExtHostUriOpeners, new ExtHostUriOpeners(rpcProtocol));
const extHostProfileContentHandlers = rpcProtocol.set(ExtHostContext.ExtHostProfileContentHandlers, new ExtHostProfileContentHandlers(rpcProtocol));
rpcProtocol.set(ExtHostContext.ExtHostInteractive, new ExtHostInteractive(rpcProtocol, extHostNotebook, extHostDocumentsAndEditors, extHostCommands, extHostLogService));
const extHostInteractiveEditor = rpcProtocol.set(ExtHostContext.ExtHostInlineChat, new ExtHostInteractiveEditor(rpcProtocol, extHostCommands, extHostDocuments, extHostLogService));
const extHostChatProvider = rpcProtocol.set(ExtHostContext.ExtHostChatProvider, new ExtHostChatProvider(rpcProtocol, extHostLogService));
const extHostChatAgents2 = rpcProtocol.set(ExtHostContext.ExtHostChatAgents2, new ExtHostChatAgents2(rpcProtocol, extHostChatProvider, extHostLogService));
const extHostChatVariables = rpcProtocol.set(ExtHostContext.ExtHostChatVariables, new ExtHostChatVariables(rpcProtocol));
const extHostChat = rpcProtocol.set(ExtHostContext.ExtHostChat, new ExtHostChat(rpcProtocol));
const extHostAiRelatedInformation = rpcProtocol.set(ExtHostContext.ExtHostAiRelatedInformation, new ExtHostRelatedInformation(rpcProtocol));
const extHostAiEmbeddingVector = rpcProtocol.set(ExtHostContext.ExtHostAiEmbeddingVector, new ExtHostAiEmbeddingVector(rpcProtocol));
const extHostIssueReporter = rpcProtocol.set(ExtHostContext.ExtHostIssueReporter, new ExtHostIssueReporter(rpcProtocol));
const extHostStatusBar = rpcProtocol.set(ExtHostContext.ExtHostStatusBar, new ExtHostStatusBar(rpcProtocol, extHostCommands.converter));
const extHostSpeech = rpcProtocol.set(ExtHostContext.ExtHostSpeech, new ExtHostSpeech(rpcProtocol));
// Check that no named customers are missing
const expected = Object.values<ProxyIdentifier<any>>(ExtHostContext);
rpcProtocol.assertRegistered(expected);
// Other instances
const extHostBulkEdits = new ExtHostBulkEdits(rpcProtocol, extHostDocumentsAndEditors);
const extHostClipboard = new ExtHostClipboard(rpcProtocol);
const extHostMessageService = new ExtHostMessageService(rpcProtocol, extHostLogService);
const extHostDialogs = new ExtHostDialogs(rpcProtocol);
// Register API-ish commands
ExtHostApiCommands.register(extHostCommands);
return function (extension: IExtensionDescription, extensionInfo: IExtensionRegistries, configProvider: ExtHostConfigProvider): typeof vscode {
// Wraps an event with error handling and telemetry so that we know what extension fails
// handling events. This will prevent us from reporting this as "our" error-telemetry and
// allows for better blaming
function _asExtensionEvent<T>(actual: vscode.Event<T>): vscode.Event<T> {
return (listener, thisArgs, disposables) => {
const handle = actual(e => {
try {
listener.call(thisArgs, e);
} catch (err) {
errors.onUnexpectedExternalError(new Error(`[ExtensionListenerError] Extension '${extension.identifier.value}' FAILED to handle event: ${err.toString()}`, { cause: err }));
extHostTelemetry.onExtensionError(extension.identifier, err);
}
});
disposables?.push(handle);
return handle;
};
}
// Check document selectors for being overly generic. Technically this isn't a problem but
// in practice many extensions say they support `fooLang` but need fs-access to do so. Those
// extension should specify then the `file`-scheme, e.g. `{ scheme: 'fooLang', language: 'fooLang' }`
// We only inform once, it is not a warning because we just want to raise awareness and because
// we cannot say if the extension is doing it right or wrong...
const checkSelector = (function () {
let done = !extension.isUnderDevelopment;
function informOnce() {
if (!done) {
extHostLogService.info(`Extension '${extension.identifier.value}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
done = true;
}
}
return function perform(selector: vscode.DocumentSelector): vscode.DocumentSelector {
if (Array.isArray(selector)) {
selector.forEach(perform);
} else if (typeof selector === 'string') {
informOnce();
} else {
const filter = selector as vscode.DocumentFilter; // TODO: microsoft/TypeScript#42768
if (typeof filter.scheme === 'undefined') {
informOnce();
}
if (typeof filter.exclusive === 'boolean') {
checkProposedApiEnabled(extension, 'documentFiltersExclusive');
}
}
return selector;
};
})();
const authentication: typeof vscode.authentication = {
getSession(providerId: string, scopes: readonly string[], options?: vscode.AuthenticationGetSessionOptions) {
return extHostAuthentication.getSession(extension, providerId, scopes, options as any);
},
getSessions(providerId: string, scopes: readonly string[]) {
checkProposedApiEnabled(extension, 'authGetSessions');
return extHostAuthentication.getSessions(extension, providerId, scopes);
},
// TODO: remove this after GHPR and Codespaces move off of it
async hasSession(providerId: string, scopes: readonly string[]) {
checkProposedApiEnabled(extension, 'authSession');
return !!(await extHostAuthentication.getSession(extension, providerId, scopes, { silent: true } as any));
},
get onDidChangeSessions(): vscode.Event<vscode.AuthenticationSessionsChangeEvent> {
return _asExtensionEvent(extHostAuthentication.onDidChangeSessions);
},
registerAuthenticationProvider(id: string, label: string, provider: vscode.AuthenticationProvider, options?: vscode.AuthenticationProviderOptions): vscode.Disposable {
return extHostAuthentication.registerAuthenticationProvider(id, label, provider, options);
}
};
// namespace: commands
const commands: typeof vscode.commands = {
registerCommand(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable {
return extHostCommands.registerCommand(true, id, command, thisArgs, undefined, extension);
},
registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable {
return extHostCommands.registerCommand(true, id, (...args: any[]): any => {
const activeTextEditor = extHostEditors.getActiveTextEditor();
if (!activeTextEditor) {
extHostLogService.warn('Cannot execute ' + id + ' because there is no active text editor.');
return undefined;
}
return activeTextEditor.edit((edit: vscode.TextEditorEdit) => {
callback.apply(thisArg, [activeTextEditor, edit, ...args]);
}).then((result) => {
if (!result) {
extHostLogService.warn('Edits from command ' + id + ' were not applied.');
}
}, (err) => {
extHostLogService.warn('An error occurred while running command ' + id, err);
});
}, undefined, undefined, extension);
},
registerDiffInformationCommand: (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
checkProposedApiEnabled(extension, 'diffCommand');
return extHostCommands.registerCommand(true, id, async (...args: any[]): Promise<any> => {
const activeTextEditor = extHostDocumentsAndEditors.activeEditor(true);
if (!activeTextEditor) {
extHostLogService.warn('Cannot execute ' + id + ' because there is no active text editor.');
return undefined;
}
const diff = await extHostEditors.getDiffInformation(activeTextEditor.id);
callback.apply(thisArg, [diff, ...args]);
}, undefined, undefined, extension);
},
executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
return extHostCommands.executeCommand<T>(id, ...args);
},
getCommands(filterInternal: boolean = false): Thenable<string[]> {
return extHostCommands.getCommands(filterInternal);
}
};
// namespace: env
const env: typeof vscode.env = {
get machineId() { return initData.telemetryInfo.machineId; },
get sessionId() { return initData.telemetryInfo.sessionId; },
get language() { return initData.environment.appLanguage; },
get appName() { return initData.environment.appName; },
get appRoot() { return initData.environment.appRoot?.fsPath ?? ''; },
get appHost() { return initData.environment.appHost; },
get uriScheme() { return initData.environment.appUriScheme; },
get clipboard(): vscode.Clipboard { return extHostClipboard.value; },
get shell() {
return extHostTerminalService.getDefaultShell(false);
},
get onDidChangeShell() {
return _asExtensionEvent(extHostTerminalService.onDidChangeShell);
},
get isTelemetryEnabled() {
return extHostTelemetry.getTelemetryConfiguration();
},
get onDidChangeTelemetryEnabled(): vscode.Event<boolean> {
return _asExtensionEvent(extHostTelemetry.onDidChangeTelemetryEnabled);
},
get telemetryConfiguration(): vscode.TelemetryConfiguration {
checkProposedApiEnabled(extension, 'telemetry');
return extHostTelemetry.getTelemetryDetails();
},
get onDidChangeTelemetryConfiguration(): vscode.Event<vscode.TelemetryConfiguration> {
checkProposedApiEnabled(extension, 'telemetry');
return _asExtensionEvent(extHostTelemetry.onDidChangeTelemetryConfiguration);
},
get isNewAppInstall() {
return isNewAppInstall(initData.telemetryInfo.firstSessionDate);
},
createTelemetryLogger(sender: vscode.TelemetrySender, options?: vscode.TelemetryLoggerOptions): vscode.TelemetryLogger {
ExtHostTelemetryLogger.validateSender(sender);
return extHostTelemetry.instantiateLogger(extension, sender, options);
},
openExternal(uri: URI, options?: { allowContributedOpeners?: boolean | string }) {
return extHostWindow.openUri(uri, {
allowTunneling: !!initData.remote.authority,
allowContributedOpeners: options?.allowContributedOpeners,
});
},
async asExternalUri(uri: URI) {
if (uri.scheme === initData.environment.appUriScheme) {
return extHostUrls.createAppUri(uri);
}
try {
return await extHostWindow.asExternalUri(uri, { allowTunneling: !!initData.remote.authority });
} catch (err) {
if (matchesScheme(uri, Schemas.http) || matchesScheme(uri, Schemas.https)) {
return uri;
}
throw err;
}
},
get remoteName() {
return getRemoteName(initData.remote.authority);
},
get remoteAuthority() {
checkProposedApiEnabled(extension, 'resolvers');
return initData.remote.authority;
},
get uiKind() {
return initData.uiKind;
},
get logLevel() {
return extHostLogService.getLevel();
},
get onDidChangeLogLevel() {
return _asExtensionEvent(extHostLogService.onDidChangeLogLevel);
},
registerIssueUriRequestHandler(handler: vscode.IssueUriRequestHandler) {
checkProposedApiEnabled(extension, 'handleIssueUri');
return extHostIssueReporter.registerIssueUriRequestHandler(extension, handler);
},
registerIssueDataProvider(handler: vscode.IssueDataProvider) {
checkProposedApiEnabled(extension, 'handleIssueUri');
return extHostIssueReporter.registerIssueDataProvider(extension, handler);
},
get appQuality(): string | undefined {
checkProposedApiEnabled(extension, 'resolvers');
return initData.quality;
},
get appCommit(): string | undefined {
checkProposedApiEnabled(extension, 'resolvers');
return initData.commit;
},
};
if (!initData.environment.extensionTestsLocationURI) {
// allow to patch env-function when running tests
Object.freeze(env);
}
// namespace: tests
const tests: typeof vscode.tests = {
createTestController(provider, label, refreshHandler?: (token: vscode.CancellationToken) => Thenable<void> | void) {
return extHostTesting.createTestController(extension, provider, label, refreshHandler);
},
createTestObserver() {
checkProposedApiEnabled(extension, 'testObserver');
return extHostTesting.createTestObserver();
},
runTests(provider) {
checkProposedApiEnabled(extension, 'testObserver');
return extHostTesting.runTests(provider);
},
get onDidChangeTestResults() {
checkProposedApiEnabled(extension, 'testObserver');
return _asExtensionEvent(extHostTesting.onResultsChanged);
},
get testResults() {
checkProposedApiEnabled(extension, 'testObserver');
return extHostTesting.results;
},
};
// namespace: extensions
const extensionKind = initData.remote.isRemote
? extHostTypes.ExtensionKind.Workspace
: extHostTypes.ExtensionKind.UI;
const extensions: typeof vscode.extensions = {
getExtension(extensionId: string, includeFromDifferentExtensionHosts?: boolean): vscode.Extension<any> | undefined {
if (!isProposedApiEnabled(extension, 'extensionsAny')) {
includeFromDifferentExtensionHosts = false;
}
const mine = extensionInfo.mine.getExtensionDescription(extensionId);
if (mine) {
return new Extension(extensionService, extension.identifier, mine, extensionKind, false);
}
if (includeFromDifferentExtensionHosts) {
const foreign = extensionInfo.all.getExtensionDescription(extensionId);
if (foreign) {
return new Extension(extensionService, extension.identifier, foreign, extensionKind /* TODO@alexdima THIS IS WRONG */, true);
}
}
return undefined;
},
get all(): vscode.Extension<any>[] {
const result: vscode.Extension<any>[] = [];
for (const desc of extensionInfo.mine.getAllExtensionDescriptions()) {
result.push(new Extension(extensionService, extension.identifier, desc, extensionKind, false));
}
return result;
},
get allAcrossExtensionHosts(): vscode.Extension<any>[] {
checkProposedApiEnabled(extension, 'extensionsAny');
const local = new ExtensionIdentifierSet(extensionInfo.mine.getAllExtensionDescriptions().map(desc => desc.identifier));
const result: vscode.Extension<any>[] = [];
for (const desc of extensionInfo.all.getAllExtensionDescriptions()) {
const isFromDifferentExtensionHost = !local.has(desc.identifier);
result.push(new Extension(extensionService, extension.identifier, desc, extensionKind /* TODO@alexdima THIS IS WRONG */, isFromDifferentExtensionHost));
}
return result;
},
get onDidChange() {
if (isProposedApiEnabled(extension, 'extensionsAny')) {
return _asExtensionEvent(Event.any(extensionInfo.mine.onDidChange, extensionInfo.all.onDidChange));
}
return _asExtensionEvent(extensionInfo.mine.onDidChange);
}
};
// namespace: languages
const languages: typeof vscode.languages = {
createDiagnosticCollection(name?: string): vscode.DiagnosticCollection {
return extHostDiagnostics.createDiagnosticCollection(extension.identifier, name);
},
get onDidChangeDiagnostics() {
return _asExtensionEvent(extHostDiagnostics.onDidChangeDiagnostics);
},
getDiagnostics: (resource?: vscode.Uri) => {
return <any>extHostDiagnostics.getDiagnostics(resource);
},
getLanguages(): Thenable<string[]> {
return extHostLanguages.getLanguages();
},
setTextDocumentLanguage(document: vscode.TextDocument, languageId: string): Thenable<vscode.TextDocument> {
return extHostLanguages.changeLanguage(document.uri, languageId);
},
match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
const notebook = extHostDocuments.getDocumentData(document.uri)?.notebook;
return score(typeConverters.LanguageSelector.from(selector), document.uri, document.languageId, true, notebook?.uri, notebook?.notebookType);
},
registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable {
return extHostLanguageFeatures.registerCodeActionProvider(extension, checkSelector(selector), provider, metadata);
},
registerDocumentPasteEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentPasteEditProvider, metadata: vscode.DocumentPasteProviderMetadata): vscode.Disposable {
checkProposedApiEnabled(extension, 'documentPaste');
return extHostLanguageFeatures.registerDocumentPasteEditProvider(extension, checkSelector(selector), provider, metadata);
},
registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {
return extHostLanguageFeatures.registerCodeLensProvider(extension, checkSelector(selector), provider);
},
registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDefinitionProvider(extension, checkSelector(selector), provider);
},
registerDeclarationProvider(selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDeclarationProvider(extension, checkSelector(selector), provider);
},
registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
return extHostLanguageFeatures.registerImplementationProvider(extension, checkSelector(selector), provider);
},
registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
return extHostLanguageFeatures.registerTypeDefinitionProvider(extension, checkSelector(selector), provider);
},
registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
return extHostLanguageFeatures.registerHoverProvider(extension, checkSelector(selector), provider, extension.identifier);
},
registerEvaluatableExpressionProvider(selector: vscode.DocumentSelector, provider: vscode.EvaluatableExpressionProvider): vscode.Disposable {
return extHostLanguageFeatures.registerEvaluatableExpressionProvider(extension, checkSelector(selector), provider, extension.identifier);
},
registerInlineValuesProvider(selector: vscode.DocumentSelector, provider: vscode.InlineValuesProvider): vscode.Disposable {
return extHostLanguageFeatures.registerInlineValuesProvider(extension, checkSelector(selector), provider, extension.identifier);
},
registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentHighlightProvider(extension, checkSelector(selector), provider);
},
registerMultiDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.MultiDocumentHighlightProvider): vscode.Disposable {
return extHostLanguageFeatures.registerMultiDocumentHighlightProvider(extension, checkSelector(selector), provider);
},
registerLinkedEditingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.LinkedEditingRangeProvider): vscode.Disposable {
return extHostLanguageFeatures.registerLinkedEditingRangeProvider(extension, checkSelector(selector), provider);
},
registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable {
return extHostLanguageFeatures.registerReferenceProvider(extension, checkSelector(selector), provider);
},
registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable {
return extHostLanguageFeatures.registerRenameProvider(extension, checkSelector(selector), provider);
},
registerNewSymbolNamesProvider(selector: vscode.DocumentSelector, provider: vscode.NewSymbolNamesProvider): vscode.Disposable {
checkProposedApiEnabled(extension, 'newSymbolNamesProvider');
return extHostLanguageFeatures.registerNewSymbolNamesProvider(extension, checkSelector(selector), provider);
},
registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentSymbolProvider(extension, checkSelector(selector), provider, metadata);
},
registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
return extHostLanguageFeatures.registerWorkspaceSymbolProvider(extension, provider);
},
registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentFormattingEditProvider(extension, checkSelector(selector), provider);
},
registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(extension, checkSelector(selector), provider);
},
registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable {
return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(extension, checkSelector(selector), provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
},
registerDocumentSemanticTokensProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSemanticTokensProvider, legend: vscode.SemanticTokensLegend): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentSemanticTokensProvider(extension, checkSelector(selector), provider, legend);
},
registerDocumentRangeSemanticTokensProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeSemanticTokensProvider, legend: vscode.SemanticTokensLegend): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentRangeSemanticTokensProvider(extension, checkSelector(selector), provider, legend);
},
registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, firstItem?: string | vscode.SignatureHelpProviderMetadata, ...remaining: string[]): vscode.Disposable {
if (typeof firstItem === 'object') {
return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, firstItem);
}
return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, typeof firstItem === 'undefined' ? [] : [firstItem, ...remaining]);
},
registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable {
return extHostLanguageFeatures.registerCompletionItemProvider(extension, checkSelector(selector), provider, triggerCharacters);
},
registerInlineCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.InlineCompletionItemProvider, metadata?: vscode.InlineCompletionItemProviderMetadata): vscode.Disposable {
if (provider.handleDidShowCompletionItem) {
checkProposedApiEnabled(extension, 'inlineCompletionsAdditions');
}
if (provider.handleDidPartiallyAcceptCompletionItem) {
checkProposedApiEnabled(extension, 'inlineCompletionsAdditions');
}
if (metadata) {
checkProposedApiEnabled(extension, 'inlineCompletionsAdditions');
}
return extHostLanguageFeatures.registerInlineCompletionsProvider(extension, checkSelector(selector), provider, metadata);
},
registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentLinkProvider(extension, checkSelector(selector), provider);
},
registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable {
return extHostLanguageFeatures.registerColorProvider(extension, checkSelector(selector), provider);
},
registerFoldingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable {
return extHostLanguageFeatures.registerFoldingRangeProvider(extension, checkSelector(selector), provider);
},
registerSelectionRangeProvider(selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable {
return extHostLanguageFeatures.registerSelectionRangeProvider(extension, selector, provider);
},
registerCallHierarchyProvider(selector: vscode.DocumentSelector, provider: vscode.CallHierarchyProvider): vscode.Disposable {
return extHostLanguageFeatures.registerCallHierarchyProvider(extension, selector, provider);
},
registerTypeHierarchyProvider(selector: vscode.DocumentSelector, provider: vscode.TypeHierarchyProvider): vscode.Disposable {
return extHostLanguageFeatures.registerTypeHierarchyProvider(extension, selector, provider);
},
setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
return extHostLanguageFeatures.setLanguageConfiguration(extension, language, configuration);
},
getTokenInformationAtPosition(doc: vscode.TextDocument, pos: vscode.Position) {
checkProposedApiEnabled(extension, 'tokenInformation');
return extHostLanguages.tokenAtPosition(doc, pos);
},
registerInlayHintsProvider(selector: vscode.DocumentSelector, provider: vscode.InlayHintsProvider): vscode.Disposable {
return extHostLanguageFeatures.registerInlayHintsProvider(extension, selector, provider);
},
createLanguageStatusItem(id: string, selector: vscode.DocumentSelector): vscode.LanguageStatusItem {
return extHostLanguages.createLanguageStatusItem(extension, id, selector);
},
registerDocumentDropEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentDropEditProvider, metadata?: vscode.DocumentDropEditProviderMetadata): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentOnDropEditProvider(extension, selector, provider, isProposedApiEnabled(extension, 'dropMetadata') ? metadata : undefined);
}
};
// namespace: window
const window: typeof vscode.window = {
get activeTextEditor() {
return extHostEditors.getActiveTextEditor();
},
get visibleTextEditors() {
return extHostEditors.getVisibleTextEditors();
},
get activeTerminal() {
return extHostTerminalService.activeTerminal;
},
get terminals() {
return extHostTerminalService.terminals;
},
async showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): Promise<vscode.TextEditor> {
if (URI.isUri(documentOrUri) && documentOrUri.scheme === Schemas.vscodeRemote && !documentOrUri.authority) {
extHostApiDeprecation.report('workspace.showTextDocument', extension, `A URI of 'vscode-remote' scheme requires an authority.`);
}
const document = await (URI.isUri(documentOrUri)
? Promise.resolve(workspace.openTextDocument(documentOrUri))
: Promise.resolve(<vscode.TextDocument>documentOrUri));
return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus);
},
createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
return extHostEditors.createTextEditorDecorationType(extension, options);
},
onDidChangeActiveTextEditor(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostEditors.onDidChangeActiveTextEditor)(listener, thisArg, disposables);
},
onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
return _asExtensionEvent(extHostEditors.onDidChangeVisibleTextEditors)(listener, thisArg, disposables);
},
onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
return _asExtensionEvent(extHostEditors.onDidChangeTextEditorSelection)(listener, thisArgs, disposables);
},
onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
return _asExtensionEvent(extHostEditors.onDidChangeTextEditorOptions)(listener, thisArgs, disposables);
},
onDidChangeTextEditorVisibleRanges(listener: (e: vscode.TextEditorVisibleRangesChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
return _asExtensionEvent(extHostEditors.onDidChangeTextEditorVisibleRanges)(listener, thisArgs, disposables);
},
onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostEditors.onDidChangeTextEditorViewColumn)(listener, thisArg, disposables);
},
onDidCloseTerminal(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostTerminalService.onDidCloseTerminal)(listener, thisArg, disposables);
},
onDidOpenTerminal(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostTerminalService.onDidOpenTerminal)(listener, thisArg, disposables);
},
onDidChangeActiveTerminal(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostTerminalService.onDidChangeActiveTerminal)(listener, thisArg, disposables);
},
onDidChangeTerminalDimensions(listener, thisArg?, disposables?) {
checkProposedApiEnabled(extension, 'terminalDimensions');
return _asExtensionEvent(extHostTerminalService.onDidChangeTerminalDimensions)(listener, thisArg, disposables);
},
onDidChangeTerminalState(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostTerminalService.onDidChangeTerminalState)(listener, thisArg, disposables);
},
onDidWriteTerminalData(listener, thisArg?, disposables?) {
checkProposedApiEnabled(extension, 'terminalDataWriteEvent');
return _asExtensionEvent(extHostTerminalService.onDidWriteTerminalData)(listener, thisArg, disposables);
},
onDidExecuteTerminalCommand(listener, thisArg?, disposables?) {
checkProposedApiEnabled(extension, 'terminalExecuteCommandEvent');
return _asExtensionEvent(extHostTerminalService.onDidExecuteTerminalCommand)(listener, thisArg, disposables);
},
get state() {
return extHostWindow.getState(extension);
},
onDidChangeWindowState(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostWindow.onDidChangeWindowState)(listener, thisArg, disposables);
},
showInformationMessage(message: string, ...rest: Array<vscode.MessageOptions | string | vscode.MessageItem>) {
return <Thenable<any>>extHostMessageService.showMessage(extension, Severity.Info, message, rest[0], <Array<string | vscode.MessageItem>>rest.slice(1));
},
showWarningMessage(message: string, ...rest: Array<vscode.MessageOptions | string | vscode.MessageItem>) {
return <Thenable<any>>extHostMessageService.showMessage(extension, Severity.Warning, message, rest[0], <Array<string | vscode.MessageItem>>rest.slice(1));
},
showErrorMessage(message: string, ...rest: Array<vscode.MessageOptions | string | vscode.MessageItem>) {
return <Thenable<any>>extHostMessageService.showMessage(extension, Severity.Error, message, rest[0], <Array<string | vscode.MessageItem>>rest.slice(1));
},
showQuickPick(items: any, options?: vscode.QuickPickOptions, token?: vscode.CancellationToken): any {
return extHostQuickOpen.showQuickPick(extension, items, options, token);
},
showWorkspaceFolderPick(options?: vscode.WorkspaceFolderPickOptions) {
return extHostQuickOpen.showWorkspaceFolderPick(options);
},
showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
return extHostQuickOpen.showInput(options, token);
},
showOpenDialog(options) {
return extHostDialogs.showOpenDialog(extension, options);
},
showSaveDialog(options) {
return extHostDialogs.showSaveDialog(options);
},
createStatusBarItem(alignmentOrId?: vscode.StatusBarAlignment | string, priorityOrAlignment?: number | vscode.StatusBarAlignment, priorityArg?: number): vscode.StatusBarItem {
let id: string | undefined;
let alignment: number | undefined;
let priority: number | undefined;
if (typeof alignmentOrId === 'string') {
id = alignmentOrId;
alignment = priorityOrAlignment;
priority = priorityArg;
} else {
alignment = alignmentOrId;
priority = priorityOrAlignment;
}
return extHostStatusBar.createStatusBarEntry(extension, id, alignment, priority);
},
setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable {
return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
},
withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) {
extHostApiDeprecation.report('window.withScmProgress', extension,
`Use 'withProgress' instead.`);
return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } }));
},
withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; worked?: number }>, token: vscode.CancellationToken) => Thenable<R>) {
return extHostProgress.withProgress(extension, options, task);
},
createOutputChannel(name: string, options: string | { log: true } | undefined): any {
return extHostOutputService.createOutputChannel(name, options, extension);
},
createWebviewPanel(viewType: string, title: string, showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn; preserveFocus?: boolean }, options?: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel {
return extHostWebviewPanels.createWebviewPanel(extension, viewType, title, showOptions, options);
},
createWebviewTextEditorInset(editor: vscode.TextEditor, line: number, height: number, options?: vscode.WebviewOptions): vscode.WebviewEditorInset {
checkProposedApiEnabled(extension, 'editorInsets');
return extHostEditorInsets.createWebviewEditorInset(editor, line, height, options, extension);
},
createTerminal(nameOrOptions?: vscode.TerminalOptions | vscode.ExtensionTerminalOptions | string, shellPath?: string, shellArgs?: readonly string[] | string): vscode.Terminal {
if (typeof nameOrOptions === 'object') {
if ('pty' in nameOrOptions) {
return extHostTerminalService.createExtensionTerminal(nameOrOptions);
}
return extHostTerminalService.createTerminalFromOptions(nameOrOptions);
}
return extHostTerminalService.createTerminal(nameOrOptions, shellPath, shellArgs);
},
registerTerminalLinkProvider(provider: vscode.TerminalLinkProvider): vscode.Disposable {
return extHostTerminalService.registerLinkProvider(provider);
},
registerTerminalProfileProvider(id: string, provider: vscode.TerminalProfileProvider): vscode.Disposable {
return extHostTerminalService.registerProfileProvider(extension, id, provider);
},
registerTerminalQuickFixProvider(id: string, provider: vscode.TerminalQuickFixProvider): vscode.Disposable {
checkProposedApiEnabled(extension, 'terminalQuickFixProvider');
return extHostTerminalService.registerTerminalQuickFixProvider(id, extension.identifier.value, provider);
},
registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable {
return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider, extension);
},
createTreeView(viewId: string, options: { treeDataProvider: vscode.TreeDataProvider<any> }): vscode.TreeView<any> {
return extHostTreeViews.createTreeView(viewId, options, extension);
},
registerWebviewPanelSerializer: (viewType: string, serializer: vscode.WebviewPanelSerializer) => {
return extHostWebviewPanels.registerWebviewPanelSerializer(extension, viewType, serializer);
},
registerCustomEditorProvider: (viewType: string, provider: vscode.CustomTextEditorProvider | vscode.CustomReadonlyEditorProvider, options: { webviewOptions?: vscode.WebviewPanelOptions; supportsMultipleEditorsPerDocument?: boolean } = {}) => {
return extHostCustomEditors.registerCustomEditorProvider(extension, viewType, provider, options);
},
registerFileDecorationProvider(provider: vscode.FileDecorationProvider) {
return extHostDecorations.registerFileDecorationProvider(provider, extension);
},
registerUriHandler(handler: vscode.UriHandler) {
return extHostUrls.registerUriHandler(extension, handler);
},
createQuickPick<T extends vscode.QuickPickItem>(): vscode.QuickPick<T> {
return extHostQuickOpen.createQuickPick(extension);
},
createInputBox(): vscode.InputBox {
return extHostQuickOpen.createInputBox(extension);
},
get activeColorTheme(): vscode.ColorTheme {
return extHostTheming.activeColorTheme;
},
onDidChangeActiveColorTheme(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostTheming.onDidChangeActiveColorTheme)(listener, thisArg, disposables);
},
registerWebviewViewProvider(viewId: string, provider: vscode.WebviewViewProvider, options?: {
webviewOptions?: {
retainContextWhenHidden?: boolean;
};
}) {
return extHostWebviewViews.registerWebviewViewProvider(extension, viewId, provider, options?.webviewOptions);
},
get activeNotebookEditor(): vscode.NotebookEditor | undefined {
return extHostNotebook.activeNotebookEditor;
},
onDidChangeActiveNotebookEditor(listener, thisArgs?, disposables?) {
return _asExtensionEvent(extHostNotebook.onDidChangeActiveNotebookEditor)(listener, thisArgs, disposables);
},
get visibleNotebookEditors() {
return extHostNotebook.visibleNotebookEditors;
},
get onDidChangeVisibleNotebookEditors() {
return _asExtensionEvent(extHostNotebook.onDidChangeVisibleNotebookEditors);
},
onDidChangeNotebookEditorSelection(listener, thisArgs?, disposables?) {
return _asExtensionEvent(extHostNotebookEditors.onDidChangeNotebookEditorSelection)(listener, thisArgs, disposables);
},
onDidChangeNotebookEditorVisibleRanges(listener, thisArgs?, disposables?) {
return _asExtensionEvent(extHostNotebookEditors.onDidChangeNotebookEditorVisibleRanges)(listener, thisArgs, disposables);
},
showNotebookDocument(document, options?) {
return extHostNotebook.showNotebookDocument(document, options);
},
registerExternalUriOpener(id: string, opener: vscode.ExternalUriOpener, metadata: vscode.ExternalUriOpenerMetadata) {
checkProposedApiEnabled(extension, 'externalUriOpener');
return extHostUriOpeners.registerExternalUriOpener(extension.identifier, id, opener, metadata);
},
registerProfileContentHandler(id: string, handler: vscode.ProfileContentHandler) {
checkProposedApiEnabled(extension, 'profileContentHandlers');
return extHostProfileContentHandlers.registerProfileContentHandler(extension, id, handler);
},
registerQuickDiffProvider(selector: vscode.DocumentSelector, quickDiffProvider: vscode.QuickDiffProvider, label: string, rootUri?: vscode.Uri): vscode.Disposable {
checkProposedApiEnabled(extension, 'quickDiffProvider');
return extHostQuickDiff.registerQuickDiffProvider(checkSelector(selector), quickDiffProvider, label, rootUri);
},
get tabGroups(): vscode.TabGroups {
return extHostEditorTabs.tabGroups;
},
registerShareProvider(selector: vscode.DocumentSelector, provider: vscode.ShareProvider): vscode.Disposable {
checkProposedApiEnabled(extension, 'shareProvider');
return extHostShare.registerShareProvider(checkSelector(selector), provider);
}
};
// namespace: workspace
const workspace: typeof vscode.workspace = {
get rootPath() {
extHostApiDeprecation.report('workspace.rootPath', extension,
`Please use 'workspace.workspaceFolders' instead. More details: https://aka.ms/vscode-eliminating-rootpath`);
return extHostWorkspace.getPath();
},
set rootPath(value) {
throw new errors.ReadonlyError('rootPath');
},
getWorkspaceFolder(resource) {
return extHostWorkspace.getWorkspaceFolder(resource);
},
get workspaceFolders() {
return extHostWorkspace.getWorkspaceFolders();
},
get name() {
return extHostWorkspace.name;
},
set name(value) {
throw new errors.ReadonlyError('name');
},
get workspaceFile() {
return extHostWorkspace.workspaceFile;
},
set workspaceFile(value) {
throw new errors.ReadonlyError('workspaceFile');
},
updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => {
return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd);
},
onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
return _asExtensionEvent(extHostWorkspace.onDidChangeWorkspace)(listener, thisArgs, disposables);
},
asRelativePath: (pathOrUri, includeWorkspace?) => {
return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
},
findFiles: (include, exclude, maxResults?, token?) => {
// Note, undefined/null have different meanings on "exclude"
return extHostWorkspace.findFiles(include, exclude, maxResults, extension.identifier, token);
},
findFiles2: (filePattern, options?, token?) => {
checkProposedApiEnabled(extension, 'findFiles2');
return extHostWorkspace.findFiles2(filePattern, options, extension.identifier, token);
},
findTextInFiles: (query: vscode.TextSearchQuery, optionsOrCallback: vscode.FindTextInFilesOptions | ((result: vscode.TextSearchResult) => void), callbackOrToken?: vscode.CancellationToken | ((result: vscode.TextSearchResult) => void), token?: vscode.CancellationToken) => {
checkProposedApiEnabled(extension, 'findTextInFiles');
let options: vscode.FindTextInFilesOptions;
let callback: (result: vscode.TextSearchResult) => void;
if (typeof optionsOrCallback === 'object') {
options = optionsOrCallback;
callback = callbackOrToken as (result: vscode.TextSearchResult) => void;
} else {
options = {};
callback = optionsOrCallback;
token = callbackOrToken as vscode.CancellationToken;
}
return extHostWorkspace.findTextInFiles(query, options || {}, callback, extension.identifier, token);
},
save: (uri) => {
return extHostWorkspace.save(uri);
},
saveAs: (uri) => {
return extHostWorkspace.saveAs(uri);
},
saveAll: (includeUntitled?) => {
return extHostWorkspace.saveAll(includeUntitled);
},
applyEdit(edit: vscode.WorkspaceEdit, metadata?: vscode.WorkspaceEditMetadata): Thenable<boolean> {
return extHostBulkEdits.applyWorkspaceEdit(edit, extension, metadata);
},
createFileSystemWatcher: (pattern, optionsOrIgnoreCreate, ignoreChange?, ignoreDelete?): vscode.FileSystemWatcher => {
let options: FileSystemWatcherCreateOptions | undefined = undefined;
if (typeof optionsOrIgnoreCreate === 'boolean') {
options = {
ignoreCreateEvents: Boolean(optionsOrIgnoreCreate),
ignoreChangeEvents: Boolean(ignoreChange),
ignoreDeleteEvents: Boolean(ignoreDelete),
correlate: false
};
} else if (optionsOrIgnoreCreate) {
checkProposedApiEnabled(extension, 'createFileSystemWatcher');
options = {
...optionsOrIgnoreCreate,
correlate: true
};
}
return extHostFileSystemEvent.createFileSystemWatcher(extHostWorkspace, extension, pattern, options);
},
get textDocuments() {
return extHostDocuments.getAllDocumentData().map(data => data.document);
},
set textDocuments(value) {
throw new errors.ReadonlyError('textDocuments');
},
openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string }) {
let uriPromise: Thenable<URI>;
const options = uriOrFileNameOrOptions as { language?: string; content?: string };
if (typeof uriOrFileNameOrOptions === 'string') {
uriPromise = Promise.resolve(URI.file(uriOrFileNameOrOptions));
} else if (URI.isUri(uriOrFileNameOrOptions)) {
uriPromise = Promise.resolve(uriOrFileNameOrOptions);
} else if (!options || typeof options === 'object') {
uriPromise = extHostDocuments.createDocumentData(options);
} else {
throw new Error('illegal argument - uriOrFileNameOrOptions');
}
return uriPromise.then(uri => {
if (uri.scheme === Schemas.vscodeRemote && !uri.authority) {
extHostApiDeprecation.report('workspace.openTextDocument', extension, `A URI of 'vscode-remote' scheme requires an authority.`);
}
return extHostDocuments.ensureDocumentData(uri).then(documentData => {
return documentData.document;
});
});
},
onDidOpenTextDocument: (listener, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostDocuments.onDidAddDocument)(listener, thisArgs, disposables);
},
onDidCloseTextDocument: (listener, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostDocuments.onDidRemoveDocument)(listener, thisArgs, disposables);
},
onDidChangeTextDocument: (listener, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostDocuments.onDidChangeDocument)(listener, thisArgs, disposables);
},
onDidSaveTextDocument: (listener, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostDocuments.onDidSaveDocument)(listener, thisArgs, disposables);
},
onWillSaveTextDocument: (listener, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension))(listener, thisArgs, disposables);
},
get notebookDocuments(): vscode.NotebookDocument[] {
return extHostNotebook.notebookDocuments.map(d => d.apiNotebook);
},
async openNotebookDocument(uriOrType?: URI | string, content?: vscode.NotebookData) {
let uri: URI;
if (URI.isUri(uriOrType)) {
uri = uriOrType;
await extHostNotebook.openNotebookDocument(uriOrType);
} else if (typeof uriOrType === 'string') {
uri = URI.revive(await extHostNotebook.createNotebookDocument({ viewType: uriOrType, content }));
} else {
throw new Error('Invalid arguments');
}
return extHostNotebook.getNotebookDocument(uri).apiNotebook;
},
onDidSaveNotebookDocument(listener, thisArg, disposables) {
return _asExtensionEvent(extHostNotebookDocuments.onDidSaveNotebookDocument)(listener, thisArg, disposables);
},
onDidChangeNotebookDocument(listener, thisArg, disposables) {
return _asExtensionEvent(extHostNotebookDocuments.onDidChangeNotebookDocument)(listener, thisArg, disposables);
},
onWillSaveNotebookDocument(listener, thisArg, disposables) {
return _asExtensionEvent(extHostNotebookDocumentSaveParticipant.getOnWillSaveNotebookDocumentEvent(extension))(listener, thisArg, disposables);
},
get onDidOpenNotebookDocument() {
return _asExtensionEvent(extHostNotebook.onDidOpenNotebookDocument);
},
get onDidCloseNotebookDocument() {
return _asExtensionEvent(extHostNotebook.onDidCloseNotebookDocument);
},
registerNotebookSerializer(viewType: string, serializer: vscode.NotebookSerializer, options?: vscode.NotebookDocumentContentOptions, registration?: vscode.NotebookRegistrationData) {
return extHostNotebook.registerNotebookSerializer(extension, viewType, serializer, options, isProposedApiEnabled(extension, 'notebookLiveShare') ? registration : undefined);
},
onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
return _asExtensionEvent(configProvider.onDidChangeConfiguration)(listener, thisArgs, disposables);
},
getConfiguration(section?: string, scope?: vscode.ConfigurationScope | null): vscode.WorkspaceConfiguration {
scope = arguments.length === 1 ? undefined : scope;
return configProvider.getConfiguration(section, scope, extension);
},
registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
},
registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
extHostApiDeprecation.report('window.registerTaskProvider', extension,
`Use the corresponding function on the 'tasks' namespace instead`);
return extHostTask.registerTaskProvider(extension, type, provider);
},
registerFileSystemProvider(scheme, provider, options) {
return combinedDisposable(
extHostFileSystem.registerFileSystemProvider(extension, scheme, provider, options),
extHostConsumerFileSystem.addFileSystemProvider(scheme, provider, options)
);
},
get fs() {
return extHostConsumerFileSystem.value;
},
registerFileSearchProvider: (scheme: string, provider: vscode.FileSearchProvider) => {
checkProposedApiEnabled(extension, 'fileSearchProvider');
return extHostSearch.registerFileSearchProvider(scheme, provider);
},
registerTextSearchProvider: (scheme: string, provider: vscode.TextSearchProvider) => {
checkProposedApiEnabled(extension, 'textSearchProvider');
return extHostSearch.registerTextSearchProvider(scheme, provider);
},
registerRemoteAuthorityResolver: (authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver) => {
checkProposedApiEnabled(extension, 'resolvers');
return extensionService.registerRemoteAuthorityResolver(authorityPrefix, resolver);
},
registerResourceLabelFormatter: (formatter: vscode.ResourceLabelFormatter) => {
checkProposedApiEnabled(extension, 'resolvers');
return extHostLabelService.$registerResourceLabelFormatter(formatter);
},
getRemoteExecServer: (authority: string) => {
checkProposedApiEnabled(extension, 'resolvers');
return extensionService.getRemoteExecServer(authority);
},
onDidCreateFiles: (listener, thisArg, disposables) => {
return _asExtensionEvent(extHostFileSystemEvent.onDidCreateFile)(listener, thisArg, disposables);
},
onDidDeleteFiles: (listener, thisArg, disposables) => {
return _asExtensionEvent(extHostFileSystemEvent.onDidDeleteFile)(listener, thisArg, disposables);
},
onDidRenameFiles: (listener, thisArg, disposables) => {
return _asExtensionEvent(extHostFileSystemEvent.onDidRenameFile)(listener, thisArg, disposables);
},
onWillCreateFiles: (listener: (e: vscode.FileWillCreateEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => {
return _asExtensionEvent(extHostFileSystemEvent.getOnWillCreateFileEvent(extension))(listener, thisArg, disposables);
},
onWillDeleteFiles: (listener: (e: vscode.FileWillDeleteEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => {
return _asExtensionEvent(extHostFileSystemEvent.getOnWillDeleteFileEvent(extension))(listener, thisArg, disposables);
},
onWillRenameFiles: (listener: (e: vscode.FileWillRenameEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => {
return _asExtensionEvent(extHostFileSystemEvent.getOnWillRenameFileEvent(extension))(listener, thisArg, disposables);
},
openTunnel: (forward: vscode.TunnelOptions) => {
checkProposedApiEnabled(extension, 'tunnels');
return extHostTunnelService.openTunnel(extension, forward).then(value => {
if (!value) {
throw new Error('cannot open tunnel');
}
return value;
});
},
get tunnels() {
checkProposedApiEnabled(extension, 'tunnels');
return extHostTunnelService.getTunnels();
},
onDidChangeTunnels: (listener, thisArg?, disposables?) => {
checkProposedApiEnabled(extension, 'tunnels');
return _asExtensionEvent(extHostTunnelService.onDidChangeTunnels)(listener, thisArg, disposables);
},
registerPortAttributesProvider: (portSelector: vscode.PortAttributesSelector, provider: vscode.PortAttributesProvider) => {
checkProposedApiEnabled(extension, 'portsAttributes');
return extHostTunnelService.registerPortsAttributesProvider(portSelector, provider);
},
registerTunnelProvider: (tunnelProvider: vscode.TunnelProvider, information: vscode.TunnelInformation) => {
checkProposedApiEnabled(extension, 'tunnelFactory');
return extHostTunnelService.registerTunnelProvider(tunnelProvider, information);
},
registerTimelineProvider: (scheme: string | string[], provider: vscode.TimelineProvider) => {
checkProposedApiEnabled(extension, 'timeline');
return extHostTimeline.registerTimelineProvider(scheme, provider, extension.identifier, extHostCommands.converter);
},
get isTrusted() {
return extHostWorkspace.trusted;
},
requestWorkspaceTrust: (options?: vscode.WorkspaceTrustRequestOptions) => {
checkProposedApiEnabled(extension, 'workspaceTrust');
return extHostWorkspace.requestWorkspaceTrust(options);
},
onDidGrantWorkspaceTrust: (listener, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostWorkspace.onDidGrantWorkspaceTrust)(listener, thisArgs, disposables);
},
registerEditSessionIdentityProvider: (scheme: string, provider: vscode.EditSessionIdentityProvider) => {
checkProposedApiEnabled(extension, 'editSessionIdentityProvider');
return extHostWorkspace.registerEditSessionIdentityProvider(scheme, provider);
},
onWillCreateEditSessionIdentity: (listener, thisArgs?, disposables?) => {
checkProposedApiEnabled(extension, 'editSessionIdentityProvider');
return _asExtensionEvent(extHostWorkspace.getOnWillCreateEditSessionIdentityEvent(extension))(listener, thisArgs, disposables);
},
registerCanonicalUriProvider: (scheme: string, provider: vscode.CanonicalUriProvider) => {
checkProposedApiEnabled(extension, 'canonicalUriProvider');
return extHostWorkspace.registerCanonicalUriProvider(scheme, provider);
},
getCanonicalUri: (uri: vscode.Uri, options: vscode.CanonicalUriRequestOptions, token: vscode.CancellationToken) => {
checkProposedApiEnabled(extension, 'canonicalUriProvider');
return extHostWorkspace.provideCanonicalUri(uri, options, token);
}
};
// namespace: scm
const scm: typeof vscode.scm = {
get inputBox() {
extHostApiDeprecation.report('scm.inputBox', extension,
`Use 'SourceControl.inputBox' instead`);
return extHostSCM.getLastInputBox(extension)!; // Strict null override - Deprecated api
},
createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
return extHostSCM.createSourceControl(extension, id, label, rootUri);
}
};
// namespace: comments
const comments: typeof vscode.comments = {
createCommentController(id: string, label: string) {
return extHostComment.createCommentController(extension, id, label);
}
};
// namespace: debug
const debug: typeof vscode.debug = {
get activeDebugSession() {
return extHostDebugService.activeDebugSession;
},
get activeDebugConsole() {
return extHostDebugService.activeDebugConsole;
},
get breakpoints() {
return extHostDebugService.breakpoints;
},
get stackFrameFocus() {
return extHostDebugService.stackFrameFocus;
},
registerDebugVisualizationProvider(id, provider) {
checkProposedApiEnabled(extension, 'debugVisualization');
return extHostDebugService.registerDebugVisualizationProvider(extension, id, provider);
},
onDidStartDebugSession(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostDebugService.onDidStartDebugSession)(listener, thisArg, disposables);
},
onDidTerminateDebugSession(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostDebugService.onDidTerminateDebugSession)(listener, thisArg, disposables);
},
onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostDebugService.onDidChangeActiveDebugSession)(listener, thisArg, disposables);
},
onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
return _asExtensionEvent(extHostDebugService.onDidReceiveDebugSessionCustomEvent)(listener, thisArg, disposables);
},
onDidChangeBreakpoints(listener, thisArgs?, disposables?) {
return _asExtensionEvent(extHostDebugService.onDidChangeBreakpoints)(listener, thisArgs, disposables);
},
onDidChangeStackFrameFocus(listener, thisArg?, disposables?) {
checkProposedApiEnabled(extension, 'debugFocus');
return _asExtensionEvent(extHostDebugService.onDidChangeStackFrameFocus)(listener, thisArg, disposables);
},
registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider, triggerKind?: vscode.DebugConfigurationProviderTriggerKind) {
return extHostDebugService.registerDebugConfigurationProvider(debugType, provider, triggerKind || DebugConfigurationProviderTriggerKind.Initial);
},
registerDebugAdapterDescriptorFactory(debugType: string, factory: vscode.DebugAdapterDescriptorFactory) {
return extHostDebugService.registerDebugAdapterDescriptorFactory(extension, debugType, factory);
},
registerDebugAdapterTrackerFactory(debugType: string, factory: vscode.DebugAdapterTrackerFactory) {
return extHostDebugService.registerDebugAdapterTrackerFactory(debugType, factory);
},
startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration, parentSessionOrOptions?: vscode.DebugSession | vscode.DebugSessionOptions) {
if (!parentSessionOrOptions || (typeof parentSessionOrOptions === 'object' && 'configuration' in parentSessionOrOptions)) {
return extHostDebugService.startDebugging(folder, nameOrConfig, { parentSession: parentSessionOrOptions });
}
return extHostDebugService.startDebugging(folder, nameOrConfig, parentSessionOrOptions || {});
},
stopDebugging(session?: vscode.DebugSession) {
return extHostDebugService.stopDebugging(session);
},
addBreakpoints(breakpoints: readonly vscode.Breakpoint[]) {
return extHostDebugService.addBreakpoints(breakpoints);
},
removeBreakpoints(breakpoints: readonly vscode.Breakpoint[]) {
return extHostDebugService.removeBreakpoints(breakpoints);
},
asDebugSourceUri(source: vscode.DebugProtocolSource, session?: vscode.DebugSession): vscode.Uri {
return extHostDebugService.asDebugSourceUri(source, session);
}
};
const tasks: typeof vscode.tasks = {
registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
return extHostTask.registerTaskProvider(extension, type, provider);
},
fetchTasks: (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => {
return extHostTask.fetchTasks(filter);
},
executeTask: (task: vscode.Task): Thenable<vscode.TaskExecution> => {
return extHostTask.executeTask(extension, task);
},
get taskExecutions(): vscode.TaskExecution[] {
return extHostTask.taskExecutions;
},
onDidStartTask: (listeners, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostTask.onDidStartTask)(listeners, thisArgs, disposables);
},
onDidEndTask: (listeners, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostTask.onDidEndTask)(listeners, thisArgs, disposables);
},
onDidStartTaskProcess: (listeners, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostTask.onDidStartTaskProcess)(listeners, thisArgs, disposables);
},
onDidEndTaskProcess: (listeners, thisArgs?, disposables?) => {
return _asExtensionEvent(extHostTask.onDidEndTaskProcess)(listeners, thisArgs, disposables);
}
};
// namespace: notebook
const notebooks: typeof vscode.notebooks = {
createNotebookController(id: string, notebookType: string, label: string, handler?, rendererScripts?: vscode.NotebookRendererScript[]) {
return extHostNotebookKernels.createNotebookController(extension, id, notebookType, label, handler, isProposedApiEnabled(extension, 'notebookMessaging') ? rendererScripts : undefined);
},
registerNotebookCellStatusBarItemProvider: (notebookType: string, provider: vscode.NotebookCellStatusBarItemProvider) => {
return extHostNotebook.registerNotebookCellStatusBarItemProvider(extension, notebookType, provider);
},
createRendererMessaging(rendererId) {
return extHostNotebookRenderers.createRendererMessaging(extension, rendererId);
},
createNotebookControllerDetectionTask(notebookType: string) {
checkProposedApiEnabled(extension, 'notebookKernelSource');
return extHostNotebookKernels.createNotebookControllerDetectionTask(extension, notebookType);
},
registerKernelSourceActionProvider(notebookType: string, provider: vscode.NotebookKernelSourceActionProvider) {
checkProposedApiEnabled(extension, 'notebookKernelSource');
return extHostNotebookKernels.registerKernelSourceActionProvider(extension, notebookType, provider);
},
onDidChangeNotebookCellExecutionState(listener, thisArgs?, disposables?) {
checkProposedApiEnabled(extension, 'notebookCellExecutionState');
return _asExtensionEvent(extHostNotebookKernels.onDidChangeNotebookCellExecutionState)(listener, thisArgs, disposables);
}
};
// namespace: l10n
const l10n: typeof vscode.l10n = {
t(...params: [message: string, ...args: Array<string | number | boolean>] | [message: string, args: Record<string, any>] | [{ message: string; args?: Array<string | number | boolean> | Record<string, any>; comment: string | string[] }]): string {
if (typeof params[0] === 'string') {
const key = params.shift() as string;
// We have either rest args which are Array<string | number | boolean> or an array with a single Record<string, any>.
// This ensures we get a Record<string | number, any> which will be formatted correctly.
const argsFormatted = !params || typeof params[0] !== 'object' ? params : params[0];
return extHostLocalization.getMessage(extension.identifier.value, { message: key, args: argsFormatted as Record<string | number, any> | undefined });
}
return extHostLocalization.getMessage(extension.identifier.value, params[0]);
},
get bundle() {
return extHostLocalization.getBundle(extension.identifier.value);
},
get uri() {
return extHostLocalization.getBundleUri(extension.identifier.value);
}
};
// namespace: interactive
const interactive: typeof vscode.interactive = {
// IMPORTANT
// this needs to be updated whenever the API proposal changes
_version: 1,
registerInteractiveEditorSessionProvider(provider: vscode.InteractiveEditorSessionProvider, metadata?: vscode.InteractiveEditorSessionProviderMetadata) {
checkProposedApiEnabled(extension, 'interactive');
return extHostInteractiveEditor.registerProvider(extension, provider, metadata);
},
registerInteractiveSessionProvider(id: string, provider: vscode.InteractiveSessionProvider) {
checkProposedApiEnabled(extension, 'interactive');
return extHostChat.registerChatProvider(extension, id, provider);
},
sendInteractiveRequestToProvider(providerId: string, message: vscode.InteractiveSessionDynamicRequest) {
checkProposedApiEnabled(extension, 'interactive');
return extHostChat.sendInteractiveRequestToProvider(providerId, message);
},
transferChatSession(session: vscode.InteractiveSession, toWorkspace: vscode.Uri) {
checkProposedApiEnabled(extension, 'interactive');
return extHostChat.transferChatSession(session, toWorkspace);
}
};
// namespace: ai
const ai: typeof vscode.ai = {
getRelatedInformation(query: string, types: vscode.RelatedInformationType[]): Thenable<vscode.RelatedInformationResult[]> {
checkProposedApiEnabled(extension, 'aiRelatedInformation');
return extHostAiRelatedInformation.getRelatedInformation(extension, query, types);
},
registerRelatedInformationProvider(type: vscode.RelatedInformationType, provider: vscode.RelatedInformationProvider) {
checkProposedApiEnabled(extension, 'aiRelatedInformation');
return extHostAiRelatedInformation.registerRelatedInformationProvider(extension, type, provider);
},
registerEmbeddingVectorProvider(model: string, provider: vscode.EmbeddingVectorProvider) {
checkProposedApiEnabled(extension, 'aiRelatedInformation');
return extHostAiEmbeddingVector.registerEmbeddingVectorProvider(extension, model, provider);
}
};
// namespace: llm
const chat: typeof vscode.chat = {
registerChatResponseProvider(id: string, provider: vscode.ChatResponseProvider, metadata: vscode.ChatResponseProviderMetadata) {
checkProposedApiEnabled(extension, 'chatProvider');
return extHostChatProvider.registerLanguageModel(extension.identifier, id, provider, metadata);
},
requestLanguageModelAccess(id, options) {
checkProposedApiEnabled(extension, 'chatRequestAccess');
return extHostChatProvider.requestLanguageModelAccess(extension.identifier, id, options);
},
get languageModels() {
checkProposedApiEnabled(extension, 'chatRequestAccess');
return extHostChatProvider.getLanguageModelIds();
},
onDidChangeLanguageModels: (listener, thisArgs?, disposables?) => {
checkProposedApiEnabled(extension, 'chatRequestAccess');
return extHostChatProvider.onDidChangeProviders(listener, thisArgs, disposables);
},
registerVariable(name: string, description: string, resolver: vscode.ChatVariableResolver) {
checkProposedApiEnabled(extension, 'chatAgents2');
return extHostChatVariables.registerVariableResolver(extension, name, description, resolver);
},
registerMappedEditsProvider(selector: vscode.DocumentSelector, provider: vscode.MappedEditsProvider) {
checkProposedApiEnabled(extension, 'mappedEditsProvider');
return extHostLanguageFeatures.registerMappedEditsProvider(extension, selector, provider);
},
createChatAgent(name: string, handler: vscode.ChatAgentExtendedHandler) {
checkProposedApiEnabled(extension, 'chatAgents2');
return extHostChatAgents2.createChatAgent(extension, name, handler);
},
};
// namespace: speech
const speech: typeof vscode.speech = {
registerSpeechProvider(id: string, provider: vscode.SpeechProvider) {
checkProposedApiEnabled(extension, 'speech');
return extHostSpeech.registerProvider(extension.identifier, id, provider);
}
};
return <typeof vscode>{
version: initData.version,
// namespaces
ai,
authentication,
commands,
comments,
chat,
debug,
env,
extensions,
interactive,
l10n,
languages,
notebooks,
scm,
speech,
tasks,
tests,
window,
workspace,
// types
Breakpoint: extHostTypes.Breakpoint,
TerminalOutputAnchor: extHostTypes.TerminalOutputAnchor,
ChatAgentResultFeedbackKind: extHostTypes.ChatAgentResultFeedbackKind,
ChatMessage: extHostTypes.ChatMessage,
ChatMessageRole: extHostTypes.ChatMessageRole,
ChatVariableLevel: extHostTypes.ChatVariableLevel,
ChatAgentCompletionItem: extHostTypes.ChatAgentCompletionItem,
CallHierarchyIncomingCall: extHostTypes.CallHierarchyIncomingCall,
CallHierarchyItem: extHostTypes.CallHierarchyItem,
CallHierarchyOutgoingCall: extHostTypes.CallHierarchyOutgoingCall,
CancellationError: errors.CancellationError,
CancellationTokenSource: CancellationTokenSource,
CandidatePortSource: CandidatePortSource,
CodeAction: extHostTypes.CodeAction,
CodeActionKind: extHostTypes.CodeActionKind,
CodeActionTriggerKind: extHostTypes.CodeActionTriggerKind,
CodeLens: extHostTypes.CodeLens,
Color: extHostTypes.Color,
ColorInformation: extHostTypes.ColorInformation,
ColorPresentation: extHostTypes.ColorPresentation,
ColorThemeKind: extHostTypes.ColorThemeKind,
CommentMode: extHostTypes.CommentMode,
CommentState: extHostTypes.CommentState,
CommentThreadCollapsibleState: extHostTypes.CommentThreadCollapsibleState,
CommentThreadState: extHostTypes.CommentThreadState,
CompletionItem: extHostTypes.CompletionItem,
CompletionItemKind: extHostTypes.CompletionItemKind,
CompletionItemTag: extHostTypes.CompletionItemTag,
CompletionList: extHostTypes.CompletionList,
CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
ConfigurationTarget: extHostTypes.ConfigurationTarget,
CustomExecution: extHostTypes.CustomExecution,
DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable,
DebugAdapterInlineImplementation: extHostTypes.DebugAdapterInlineImplementation,
DebugAdapterNamedPipeServer: extHostTypes.DebugAdapterNamedPipeServer,
DebugAdapterServer: extHostTypes.DebugAdapterServer,
DebugConfigurationProviderTriggerKind: DebugConfigurationProviderTriggerKind,
DebugConsoleMode: extHostTypes.DebugConsoleMode,
DebugVisualization: extHostTypes.DebugVisualization,
DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
Diagnostic: extHostTypes.Diagnostic,
DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation,
DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
DiagnosticTag: extHostTypes.DiagnosticTag,
Disposable: extHostTypes.Disposable,
DocumentHighlight: extHostTypes.DocumentHighlight,
DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
MultiDocumentHighlight: extHostTypes.MultiDocumentHighlight,
DocumentLink: extHostTypes.DocumentLink,
DocumentSymbol: extHostTypes.DocumentSymbol,
EndOfLine: extHostTypes.EndOfLine,
EnvironmentVariableMutatorType: extHostTypes.EnvironmentVariableMutatorType,
EvaluatableExpression: extHostTypes.EvaluatableExpression,
InlineValueText: extHostTypes.InlineValueText,
InlineValueVariableLookup: extHostTypes.InlineValueVariableLookup,
InlineValueEvaluatableExpression: extHostTypes.InlineValueEvaluatableExpression,
InlineCompletionTriggerKind: extHostTypes.InlineCompletionTriggerKind,
EventEmitter: Emitter,
ExtensionKind: extHostTypes.ExtensionKind,
ExtensionMode: extHostTypes.ExtensionMode,
ExternalUriOpenerPriority: extHostTypes.ExternalUriOpenerPriority,
FileChangeType: extHostTypes.FileChangeType,
FileDecoration: extHostTypes.FileDecoration,
FileDecoration2: extHostTypes.FileDecoration,
FileSystemError: extHostTypes.FileSystemError,
FileType: files.FileType,
FilePermission: files.FilePermission,
FoldingRange: extHostTypes.FoldingRange,
FoldingRangeKind: extHostTypes.FoldingRangeKind,
FunctionBreakpoint: extHostTypes.FunctionBreakpoint,
InlineCompletionItem: extHostTypes.InlineSuggestion,
InlineCompletionList: extHostTypes.InlineSuggestionList,
Hover: extHostTypes.Hover,
IndentAction: languageConfiguration.IndentAction,
Location: extHostTypes.Location,
MarkdownString: extHostTypes.MarkdownString,
OverviewRulerLane: OverviewRulerLane,
ParameterInformation: extHostTypes.ParameterInformation,
PortAutoForwardAction: extHostTypes.PortAutoForwardAction,
Position: extHostTypes.Position,
ProcessExecution: extHostTypes.ProcessExecution,
ProgressLocation: extHostTypes.ProgressLocation,
QuickInputButtons: extHostTypes.QuickInputButtons,
Range: extHostTypes.Range,
RelativePattern: extHostTypes.RelativePattern,
Selection: extHostTypes.Selection,
SelectionRange: extHostTypes.SelectionRange,
SemanticTokens: extHostTypes.SemanticTokens,
SemanticTokensBuilder: extHostTypes.SemanticTokensBuilder,
SemanticTokensEdit: extHostTypes.SemanticTokensEdit,
SemanticTokensEdits: extHostTypes.SemanticTokensEdits,
SemanticTokensLegend: extHostTypes.SemanticTokensLegend,
ShellExecution: extHostTypes.ShellExecution,
ShellQuoting: extHostTypes.ShellQuoting,
SignatureHelp: extHostTypes.SignatureHelp,
SignatureHelpTriggerKind: extHostTypes.SignatureHelpTriggerKind,
SignatureInformation: extHostTypes.SignatureInformation,
SnippetString: extHostTypes.SnippetString,
SourceBreakpoint: extHostTypes.SourceBreakpoint,
StandardTokenType: extHostTypes.StandardTokenType,
StatusBarAlignment: extHostTypes.StatusBarAlignment,
SymbolInformation: extHostTypes.SymbolInformation,
SymbolKind: extHostTypes.SymbolKind,
SymbolTag: extHostTypes.SymbolTag,
Task: extHostTypes.Task,
TaskGroup: extHostTypes.TaskGroup,
TaskPanelKind: extHostTypes.TaskPanelKind,
TaskRevealKind: extHostTypes.TaskRevealKind,
TaskScope: extHostTypes.TaskScope,
TerminalLink: extHostTypes.TerminalLink,
TerminalQuickFixTerminalCommand: extHostTypes.TerminalQuickFixCommand,
TerminalQuickFixOpener: extHostTypes.TerminalQuickFixOpener,
TerminalLocation: extHostTypes.TerminalLocation,
TerminalProfile: extHostTypes.TerminalProfile,
TerminalExitReason: extHostTypes.TerminalExitReason,
TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason,
TextEdit: extHostTypes.TextEdit,
SnippetTextEdit: extHostTypes.SnippetTextEdit,
TextEditorCursorStyle: TextEditorCursorStyle,
TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
TextEditorRevealType: extHostTypes.TextEditorRevealType,
TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
SyntaxTokenType: extHostTypes.SyntaxTokenType,
TextDocumentChangeReason: extHostTypes.TextDocumentChangeReason,
ThemeColor: extHostTypes.ThemeColor,
ThemeIcon: extHostTypes.ThemeIcon,
TreeItem: extHostTypes.TreeItem,
TreeItemCheckboxState: extHostTypes.TreeItemCheckboxState,
TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
TypeHierarchyItem: extHostTypes.TypeHierarchyItem,
UIKind: UIKind,
Uri: URI,
ViewColumn: extHostTypes.ViewColumn,
WorkspaceEdit: extHostTypes.WorkspaceEdit,
// proposed api types
DocumentDropEdit: extHostTypes.DocumentDropEdit,
DocumentPasteEdit: extHostTypes.DocumentPasteEdit,
InlayHint: extHostTypes.InlayHint,
InlayHintLabelPart: extHostTypes.InlayHintLabelPart,
InlayHintKind: extHostTypes.InlayHintKind,
RemoteAuthorityResolverError: extHostTypes.RemoteAuthorityResolverError,
ResolvedAuthority: extHostTypes.ResolvedAuthority,
ManagedResolvedAuthority: extHostTypes.ManagedResolvedAuthority,
SourceControlInputBoxValidationType: extHostTypes.SourceControlInputBoxValidationType,
ExtensionRuntime: extHostTypes.ExtensionRuntime,
TimelineItem: extHostTypes.TimelineItem,
NotebookRange: extHostTypes.NotebookRange,
NotebookCellKind: extHostTypes.NotebookCellKind,
NotebookCellExecutionState: extHostTypes.NotebookCellExecutionState,
NotebookCellData: extHostTypes.NotebookCellData,
NotebookData: extHostTypes.NotebookData,
NotebookRendererScript: extHostTypes.NotebookRendererScript,
NotebookCellStatusBarAlignment: extHostTypes.NotebookCellStatusBarAlignment,
NotebookEditorRevealType: extHostTypes.NotebookEditorRevealType,
NotebookCellOutput: extHostTypes.NotebookCellOutput,
NotebookCellOutputItem: extHostTypes.NotebookCellOutputItem,
NotebookCellStatusBarItem: extHostTypes.NotebookCellStatusBarItem,
NotebookControllerAffinity: extHostTypes.NotebookControllerAffinity,
NotebookControllerAffinity2: extHostTypes.NotebookControllerAffinity2,
NotebookEdit: extHostTypes.NotebookEdit,
NotebookKernelSourceAction: extHostTypes.NotebookKernelSourceAction,
NotebookVariablesRequestKind: extHostTypes.NotebookVariablesRequestKind,
PortAttributes: extHostTypes.PortAttributes,
LinkedEditingRanges: extHostTypes.LinkedEditingRanges,
TestResultState: extHostTypes.TestResultState,
TestRunRequest: extHostTypes.TestRunRequest,
TestMessage: extHostTypes.TestMessage,
TestTag: extHostTypes.TestTag,
TestRunProfileKind: extHostTypes.TestRunProfileKind,
TextSearchCompleteMessageType: TextSearchCompleteMessageType,
DataTransfer: extHostTypes.DataTransfer,
DataTransferItem: extHostTypes.DataTransferItem,
CoveredCount: extHostTypes.CoveredCount,
FileCoverage: extHostTypes.FileCoverage,
StatementCoverage: extHostTypes.StatementCoverage,
BranchCoverage: extHostTypes.BranchCoverage,
DeclarationCoverage: extHostTypes.DeclarationCoverage,
FunctionCoverage: extHostTypes.DeclarationCoverage, // back compat for Feb 2024
WorkspaceTrustState: extHostTypes.WorkspaceTrustState,
LanguageStatusSeverity: extHostTypes.LanguageStatusSeverity,
QuickPickItemKind: extHostTypes.QuickPickItemKind,
InputBoxValidationSeverity: extHostTypes.InputBoxValidationSeverity,
TabInputText: extHostTypes.TextTabInput,
TabInputTextDiff: extHostTypes.TextDiffTabInput,
TabInputTextMerge: extHostTypes.TextMergeTabInput,
TabInputCustom: extHostTypes.CustomEditorTabInput,
TabInputNotebook: extHostTypes.NotebookEditorTabInput,
TabInputNotebookDiff: extHostTypes.NotebookDiffEditorTabInput,
TabInputWebview: extHostTypes.WebviewEditorTabInput,
TabInputTerminal: extHostTypes.TerminalEditorTabInput,
TabInputInteractiveWindow: extHostTypes.InteractiveWindowInput,
TabInputChat: extHostTypes.ChatEditorTabInput,
TelemetryTrustedValue: TelemetryTrustedValue,
LogLevel: LogLevel,
EditSessionIdentityMatch: EditSessionIdentityMatch,
InteractiveSessionVoteDirection: extHostTypes.InteractiveSessionVoteDirection,
ChatAgentCopyKind: extHostTypes.ChatAgentCopyKind,
InteractiveEditorResponseFeedbackKind: extHostTypes.InteractiveEditorResponseFeedbackKind,
StackFrameFocus: extHostTypes.StackFrameFocus,
ThreadFocus: extHostTypes.ThreadFocus,
RelatedInformationType: extHostTypes.RelatedInformationType,
SpeechToTextStatus: extHostTypes.SpeechToTextStatus,
KeywordRecognitionStatus: extHostTypes.KeywordRecognitionStatus,
ChatResponseTextPart: extHostTypes.ChatResponseTextPart,
ChatResponseMarkdownPart: extHostTypes.ChatResponseMarkdownPart,
ChatResponseFileTreePart: extHostTypes.ChatResponseFileTreePart,
ChatResponseAnchorPart: extHostTypes.ChatResponseAnchorPart,
ChatResponseProgressPart: extHostTypes.ChatResponseProgressPart,
ChatResponseReferencePart: extHostTypes.ChatResponseReferencePart,
};
};
}
| src/vs/workbench/api/common/extHost.api.impl.ts | 0 | https://github.com/microsoft/vscode/commit/fbb7175b4c8d0da79c74abb3bd256e7bc27c602b | [
0.9982593655586243,
0.006519937887787819,
0.00016395891725551337,
0.000172927844687365,
0.07706574350595474
] |
{
"id": 0,
"code_window": [
" * If `true`, the keyboard will be automatically dismissed when the overlay is presented.\n",
" */\n",
" \"keyboardClose\": boolean;\n",
" /**\n",
" * Animation to use when the popover is dismissed.\n",
" */\n",
" \"leaveAnimation\"?: AnimationBuilder;\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"keyboardEvents\": boolean;\n"
],
"file_path": "core/src/components.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, State, Watch, h, writeTask } from '@stencil/core';
import {
caretDownSharp,
caretUpSharp,
chevronBack,
chevronDown,
chevronForward
} from 'ionicons/icons';
import { getIonMode } from '../../global/ionic-global';
import { Color, DatetimeChangeEventDetail, DatetimeParts, Mode, StyleEventDetail } from '../../interface';
import { startFocusVisible } from '../../utils/focus-visible';
import { getElementRoot, renderHiddenInput } from '../../utils/helpers';
import { createColorClasses } from '../../utils/theme';
import { PickerColumnItem } from '../picker-column-internal/picker-column-internal-interfaces';
import {
generateMonths,
generateTime,
getCalendarYears,
getDaysOfMonth,
getDaysOfWeek,
getPickerMonths,
getToday
} from './utils/data';
import {
addTimePadding,
getFormattedHour,
getFormattedTime,
getMonthAndDay,
getMonthAndYear
} from './utils/format';
import {
is24Hour
} from './utils/helpers';
import {
calculateHourFromAMPM,
convertDataToISO,
getEndOfWeek,
getInternalHourValue,
getNextDay,
getNextMonth,
getNextWeek,
getNextYear,
getPreviousDay,
getPreviousMonth,
getPreviousWeek,
getPreviousYear,
getStartOfWeek
} from './utils/manipulation';
import {
convertToArrayOfNumbers,
getPartsFromCalendarDay,
parseDate
} from './utils/parse';
import {
getCalendarDayState,
isDayDisabled
} from './utils/state';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot title - The title of the datetime.
* @slot buttons - The buttons in the datetime.
* @slot time-label - The label for the time selector in the datetime.
*/
@Component({
tag: 'ion-datetime',
styleUrls: {
ios: 'datetime.ios.scss',
md: 'datetime.md.scss'
},
shadow: true
})
export class Datetime implements ComponentInterface {
private inputId = `ion-dt-${datetimeIds++}`;
private calendarBodyRef?: HTMLElement;
private popoverRef?: HTMLIonPopoverElement;
private clearFocusVisible?: () => void;
private overlayIsPresenting = false;
private parsedMinuteValues?: number[];
private parsedHourValues?: number[];
private parsedMonthValues?: number[];
private parsedYearValues?: number[];
private parsedDayValues?: number[];
private destroyCalendarIO?: () => void;
private destroyKeyboardMO?: () => void;
private minParts?: any;
private maxParts?: any;
/**
* Duplicate reference to `activeParts` that does not trigger a re-render of the component.
* Allows caching an instance of the `activeParts` in between render cycles.
*/
private activePartsClone!: DatetimeParts;
@State() showMonthAndYear = false;
@State() activeParts: DatetimeParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm'
}
@State() workingParts: DatetimeParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm'
}
private todayParts = parseDate(getToday())
@Element() el!: HTMLIonDatetimeElement;
@State() isPresented = false;
@State() isTimePopoverOpen = false;
/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
* For more information on colors, see [theming](/docs/theming/basics).
*/
@Prop() color?: Color = 'primary';
/**
* The name of the control, which is submitted with the form data.
*/
@Prop() name: string = this.inputId;
/**
* If `true`, the user cannot interact with the datetime.
*/
@Prop() disabled = false;
/**
* If `true`, the datetime appears normal but is not interactive.
*/
@Prop() readonly = false;
@Watch('disabled')
protected disabledChanged() {
this.emitStyle();
}
/**
* The minimum datetime allowed. Value must be a date string
* following the
* [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
* such as `1996-12-19`. The format does not have to be specific to an exact
* datetime. For example, the minimum could just be the year, such as `1994`.
* Defaults to the beginning of the year, 100 years ago from today.
*/
@Prop({ mutable: true }) min?: string;
@Watch('min')
protected minChanged() {
this.processMinParts();
}
/**
* The maximum datetime allowed. Value must be a date string
* following the
* [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
* `1996-12-19`. The format does not have to be specific to an exact
* datetime. For example, the maximum could just be the year, such as `1994`.
* Defaults to the end of this year.
*/
@Prop({ mutable: true }) max?: string;
@Watch('max')
protected maxChanged() {
this.processMaxParts();
}
/**
* Which values you want to select. `'date'` will show
* a calendar picker to select the month, day, and year. `'time'`
* will show a time picker to select the hour, minute, and (optionally)
* AM/PM. `'date-time'` will show the date picker first and time picker second.
* `'time-date'` will show the time picker first and date picker second.
*/
@Prop() presentation: 'date-time' | 'time-date' | 'date' | 'time' | 'month' | 'year' | 'month-year' = 'date-time';
/**
* The text to display on the picker's cancel button.
*/
@Prop() cancelText = 'Cancel';
/**
* The text to display on the picker's "Done" button.
*/
@Prop() doneText = 'Done';
/**
* The text to display on the picker's "Clear" button.
*/
@Prop() clearText = 'Clear';
/**
* Values used to create the list of selectable years. By default
* the year values range between the `min` and `max` datetime inputs. However, to
* control exactly which years to display, the `yearValues` input can take a number, an array
* of numbers, or string of comma separated numbers. For example, to show upcoming and
* recent leap years, then this input's value would be `yearValues="2024,2020,2016,2012,2008"`.
*/
@Prop() yearValues?: number[] | number | string;
@Watch('yearValues')
protected yearValuesChanged() {
this.parsedYearValues = convertToArrayOfNumbers(this.yearValues);
}
/**
* Values used to create the list of selectable months. By default
* the month values range from `1` to `12`. However, to control exactly which months to
* display, the `monthValues` input can take a number, an array of numbers, or a string of
* comma separated numbers. For example, if only summer months should be shown, then this
* input value would be `monthValues="6,7,8"`. Note that month numbers do *not* have a
* zero-based index, meaning January's value is `1`, and December's is `12`.
*/
@Prop() monthValues?: number[] | number | string;
@Watch('monthValues')
protected monthValuesChanged() {
this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues);
}
/**
* Values used to create the list of selectable days. By default
* every day is shown for the given month. However, to control exactly which days of
* the month to display, the `dayValues` input can take a number, an array of numbers, or
* a string of comma separated numbers. Note that even if the array days have an invalid
* number for the selected month, like `31` in February, it will correctly not show
* days which are not valid for the selected month.
*/
@Prop() dayValues?: number[] | number | string;
@Watch('dayValues')
protected dayValuesChanged() {
this.parsedDayValues = convertToArrayOfNumbers(this.dayValues);
}
/**
* Values used to create the list of selectable hours. By default
* the hour values range from `0` to `23` for 24-hour, or `1` to `12` for 12-hour. However,
* to control exactly which hours to display, the `hourValues` input can take a number, an
* array of numbers, or a string of comma separated numbers.
*/
@Prop() hourValues?: number[] | number | string;
@Watch('hourValues')
protected hourValuesChanged() {
this.parsedHourValues = convertToArrayOfNumbers(this.hourValues);
}
/**
* Values used to create the list of selectable minutes. By default
* the minutes range from `0` to `59`. However, to control exactly which minutes to display,
* the `minuteValues` input can take a number, an array of numbers, or a string of comma
* separated numbers. For example, if the minute selections should only be every 15 minutes,
* then this input value would be `minuteValues="0,15,30,45"`.
*/
@Prop() minuteValues?: number[] | number | string;
@Watch('minuteValues')
protected minuteValuesChanged() {
this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues);
}
/**
* The locale to use for `ion-datetime`. This
* impacts month and day name formatting.
* The `'default'` value refers to the default
* locale set by your device.
*/
@Prop() locale = 'default';
/**
* The first day of the week to use for `ion-datetime`. The
* default value is `0` and represents Sunday.
*/
@Prop() firstDayOfWeek = 0;
/**
* The value of the datetime as a valid ISO 8601 datetime string.
*/
@Prop({ mutable: true }) value?: string | null;
/**
* Update the datetime value when the value changes
*/
@Watch('value')
protected valueChanged() {
if (this.hasValue()) {
/**
* Clones the value of the `activeParts` to the private clone, to update
* the date display on the current render cycle without causing another render.
*
* This allows us to update the current value's date/time display without
* refocusing or shifting the user's display (leaves the user in place).
*/
const { month, day, year, hour, minute } = parseDate(this.value);
this.activePartsClone = {
...this.activeParts,
month,
day,
year,
hour,
minute
}
}
this.emitStyle();
this.ionChange.emit({
value: this.value
});
}
/**
* If `true`, a header will be shown above the calendar
* picker. On `ios` mode this will include the
* slotted title, and on `md` mode this will include
* the slotted title and the selected date.
*/
@Prop() showDefaultTitle = false;
/**
* If `true`, the default "Cancel" and "OK" buttons
* will be rendered at the bottom of the `ion-datetime`
* component. Developers can also use the `button` slot
* if they want to customize these buttons. If custom
* buttons are set in the `button` slot then the
* default buttons will not be rendered.
*/
@Prop() showDefaultButtons = false;
/**
* If `true`, a "Clear" button will be rendered alongside
* the default "Cancel" and "OK" buttons at the bottom of the `ion-datetime`
* component. Developers can also use the `button` slot
* if they want to customize these buttons. If custom
* buttons are set in the `button` slot then the
* default buttons will not be rendered.
*/
@Prop() showClearButton = false;
/**
* If `true`, the default "Time" label will be rendered
* for the time selector of the `ion-datetime` component.
* Developers can also use the `time-label` slot
* if they want to customize this label. If a custom
* label is set in the `time-label` slot then the
* default label will not be rendered.
*/
@Prop() showDefaultTimeLabel = true;
/**
* The hour cycle of the `ion-datetime`. If no value is set, this is
* specified by the current locale.
*/
@Prop() hourCycle?: 'h23' | 'h12';
/**
* If `cover`, the `ion-datetime` will expand to cover the full width of its container.
* If `fixed`, the `ion-datetime` will have a fixed width.
*/
@Prop() size: 'cover' | 'fixed' = 'fixed';
/**
* Emitted when the datetime selection was cancelled.
*/
@Event() ionCancel!: EventEmitter<void>;
/**
* Emitted when the value (selected date) has changed.
*/
@Event() ionChange!: EventEmitter<DatetimeChangeEventDetail>;
/**
* Emitted when the datetime has focus.
*/
@Event() ionFocus!: EventEmitter<void>;
/**
* Emitted when the datetime loses focus.
*/
@Event() ionBlur!: EventEmitter<void>;
/**
* Emitted when the styles change.
* @internal
*/
@Event() ionStyle!: EventEmitter<StyleEventDetail>;
/**
* Confirms the selected datetime value, updates the
* `value` property, and optionally closes the popover
* or modal that the datetime was presented in.
*/
@Method()
async confirm(closeOverlay = false) {
/**
* Prevent convertDataToISO from doing any
* kind of transformation based on timezone
* This cancels out any change it attempts to make
*
* Important: Take the timezone offset based on
* the date that is currently selected, otherwise
* there can be 1 hr difference when dealing w/ DST
*/
const date = new Date(convertDataToISO(this.workingParts));
this.workingParts.tzOffset = date.getTimezoneOffset() * -1;
this.value = convertDataToISO(this.workingParts);
if (closeOverlay) {
this.closeParentOverlay();
}
}
/**
* Resets the internal state of the datetime but does not update the value.
* Passing a valid ISO-8601 string will reset the state of the component to the provided date.
* If no value is provided, the internal state will be reset to today.
*/
@Method()
async reset(startDate?: string) {
this.processValue(startDate);
}
/**
* Emits the ionCancel event and
* optionally closes the popover
* or modal that the datetime was
* presented in.
*/
@Method()
async cancel(closeOverlay = false) {
this.ionCancel.emit();
if (closeOverlay) {
this.closeParentOverlay();
}
}
private closeParentOverlay = () => {
const popoverOrModal = this.el.closest('ion-modal, ion-popover') as HTMLIonModalElement | HTMLIonPopoverElement | null;
if (popoverOrModal) {
popoverOrModal.dismiss();
}
}
private setWorkingParts = (parts: DatetimeParts) => {
this.workingParts = {
...parts
}
}
private setActiveParts = (parts: DatetimeParts) => {
this.activeParts = {
...parts
}
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (hasSlottedButtons || this.showDefaultButtons) { return; }
this.confirm();
}
private initializeKeyboardListeners = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const root = this.el!.shadowRoot!;
/**
* Get a reference to the month
* element we are currently viewing.
*/
const currentMonth = calendarBodyRef.querySelector('.calendar-month:nth-of-type(2)')!;
/**
* When focusing the calendar body, we want to pass focus
* to the working day, but other days should
* only be accessible using the arrow keys. Pressing
* Tab should jump between bodies of selectable content.
*/
const checkCalendarBodyFocus = (ev: MutationRecord[]) => {
const record = ev[0];
/**
* If calendar body was already focused
* when this fired or if the calendar body
* if not currently focused, we should not re-focus
* the inner day.
*/
if (
record.oldValue?.includes('ion-focused') ||
!calendarBodyRef.classList.contains('ion-focused')
) {
return;
}
this.focusWorkingDay(currentMonth);
}
const mo = new MutationObserver(checkCalendarBodyFocus);
mo.observe(calendarBodyRef, { attributeFilter: ['class'], attributeOldValue: true });
this.destroyKeyboardMO = () => {
mo?.disconnect();
}
/**
* We must use keydown not keyup as we want
* to prevent scrolling when using the arrow keys.
*/
this.calendarBodyRef!.addEventListener('keydown', (ev: KeyboardEvent) => {
const activeElement = root.activeElement;
if (!activeElement || !activeElement.classList.contains('calendar-day')) { return; }
const parts = getPartsFromCalendarDay(activeElement as HTMLElement)
let partsToFocus: DatetimeParts | undefined;
switch (ev.key) {
case 'ArrowDown':
ev.preventDefault();
partsToFocus = getNextWeek(parts);
break;
case 'ArrowUp':
ev.preventDefault();
partsToFocus = getPreviousWeek(parts);
break;
case 'ArrowRight':
ev.preventDefault();
partsToFocus = getNextDay(parts);
break;
case 'ArrowLeft':
ev.preventDefault();
partsToFocus = getPreviousDay(parts);
break;
case 'Home':
ev.preventDefault();
partsToFocus = getStartOfWeek(parts);
break;
case 'End':
ev.preventDefault();
partsToFocus = getEndOfWeek(parts);
break;
case 'PageUp':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getPreviousYear(parts) : getPreviousMonth(parts);
break;
case 'PageDown':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getNextYear(parts) : getNextMonth(parts);
break;
/**
* Do not preventDefault here
* as we do not want to override other
* browser defaults such as pressing Enter/Space
* to select a day.
*/
default:
return;
}
/**
* If the day we want to move focus to is
* disabled, do not do anything.
*/
if (isDayDisabled(partsToFocus, this.minParts, this.maxParts)) {
return;
}
this.setWorkingParts({
...this.workingParts,
...partsToFocus
})
/**
* Give view a chance to re-render
* then move focus to the new working day
*/
requestAnimationFrame(() => this.focusWorkingDay(currentMonth));
})
}
private focusWorkingDay = (currentMonth: Element) => {
/**
* Get the number of padding days so
* we know how much to offset our next selector by
* to grab the correct calenday-day element.
*/
const padding = currentMonth.querySelectorAll('.calendar-day-padding');
const { day } = this.workingParts;
if (day === null) { return; }
/**
* Get the calendar day element
* and focus it.
*/
const dayEl = currentMonth.querySelector(`.calendar-day:nth-of-type(${padding.length + day})`) as HTMLElement | null;
if (dayEl) {
dayEl.focus();
}
}
private processMinParts = () => {
if (this.min === undefined) {
this.minParts = undefined;
return;
}
const { month, day, year, hour, minute } = parseDate(this.min);
this.minParts = {
month,
day,
year,
hour,
minute
}
}
private processMaxParts = () => {
if (this.max === undefined) {
this.maxParts = undefined;
return;
}
const { month, day, year, hour, minute } = parseDate(this.max);
this.maxParts = {
month,
day,
year,
hour,
minute
}
}
private initializeCalendarIOListeners = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const mode = getIonMode(this);
/**
* For performance reasons, we only render 3
* months at a time: The current month, the previous
* month, and the next month. We have IntersectionObservers
* on the previous and next month elements to append/prepend
* new months.
*
* We can do this because Stencil is smart enough to not
* re-create the .calendar-month containers, but rather
* update the content within those containers.
*
* As an added bonus, WebKit has some troubles with
* scroll-snap-stop: always, so not rendering all of
* the months in a row allows us to mostly sidestep
* that issue.
*/
const months = calendarBodyRef.querySelectorAll('.calendar-month');
const startMonth = months[0] as HTMLElement;
const workingMonth = months[1] as HTMLElement;
const endMonth = months[2] as HTMLElement;
/**
* Before setting up the IntersectionObserver,
* scroll the middle month into view.
* scrollIntoView() will scroll entire page
* if element is not in viewport. Use scrollLeft instead.
*/
writeTask(() => {
calendarBodyRef.scrollLeft = startMonth.clientWidth;
let endIO: IntersectionObserver | undefined;
let startIO: IntersectionObserver | undefined;
const ioCallback = (callbackType: 'start' | 'end', entries: IntersectionObserverEntry[]) => {
const refIO = (callbackType === 'start') ? startIO : endIO;
const refMonth = (callbackType === 'start') ? startMonth : endMonth;
const refMonthFn = (callbackType === 'start') ? getPreviousMonth : getNextMonth;
/**
* If the month is not fully in view, do not do anything
*/
const ev = entries[0];
if (!ev.isIntersecting) { return; }
/**
* When presenting an inline overlay,
* subsequent presentations will cause
* the IO to fire again (since the overlay
* is now visible and therefore the calendar
* months are intersecting).
*/
if (this.overlayIsPresenting) {
this.overlayIsPresenting = false;
return;
}
/**
* On iOS, we need to set pointer-events: none
* when the user is almost done with the gesture
* so that they cannot quickly swipe while
* the scrollable container is snapping.
* Updating the container while snapping
* causes WebKit to snap incorrectly.
*/
if (mode === 'ios') {
const ratio = ev.intersectionRatio;
const shouldDisable = Math.abs(ratio - 0.7) <= 0.1;
if (shouldDisable) {
calendarBodyRef.style.setProperty('pointer-events', 'none');
return;
}
}
/**
* Prevent scrolling for other browsers
* to give the DOM time to update and the container
* time to properly snap.
*/
calendarBodyRef.style.setProperty('overflow', 'hidden');
/**
* Remove the IO temporarily
* otherwise you can sometimes get duplicate
* events when rubber banding.
*/
if (refIO === undefined) { return; }
refIO.disconnect();
/**
* Use a writeTask here to ensure
* that the state is updated and the
* correct month is scrolled into view
* in the same frame. This is not
* typically a problem on newer devices
* but older/slower device may have a flicker
* if we did not do this.
*/
writeTask(() => {
const { month, year, day } = refMonthFn(this.workingParts);
this.setWorkingParts({
...this.workingParts,
month,
day: day!,
year
});
calendarBodyRef.scrollLeft = workingMonth.clientWidth;
calendarBodyRef.style.removeProperty('overflow');
calendarBodyRef.style.removeProperty('pointer-events');
/**
* Now that state has been updated
* and the correct month is in view,
* we can resume the IO.
*/
// tslint:disable-next-line
if (refIO === undefined) { return; }
refIO.observe(refMonth);
});
}
/**
* Listen on the first month to
* prepend a new month and on the last
* month to append a new month.
* The 0.7 threshold is required on ios
* so that we can remove pointer-events
* when adding new months.
* Adding to a scroll snapping container
* while the container is snapping does not
* completely work as expected in WebKit.
* Adding pointer-events: none allows us to
* avoid these issues.
*
* This should be fine on Chromium, but
* when you set pointer-events: none
* it applies to active gestures which is not
* something WebKit does.
*/
endIO = new IntersectionObserver(ev => ioCallback('end', ev), {
threshold: mode === 'ios' ? [0.7, 1] : 1,
root: calendarBodyRef
});
endIO.observe(endMonth);
startIO = new IntersectionObserver(ev => ioCallback('start', ev), {
threshold: mode === 'ios' ? [0.7, 1] : 1,
root: calendarBodyRef
});
startIO.observe(startMonth);
this.destroyCalendarIO = () => {
endIO?.disconnect();
startIO?.disconnect();
}
});
}
connectedCallback() {
this.clearFocusVisible = startFocusVisible(this.el).destroy;
}
disconnectedCallback() {
if (this.clearFocusVisible) {
this.clearFocusVisible();
this.clearFocusVisible = undefined;
}
}
/**
* Clean up all listeners except for the overlay
* listener. This is so that we can re-create the listeners
* if the datetime has been hidden/presented by a modal or popover.
*/
private destroyListeners = () => {
const { destroyCalendarIO, destroyKeyboardMO } = this;
if (destroyCalendarIO !== undefined) {
destroyCalendarIO();
}
if (destroyKeyboardMO !== undefined) {
destroyKeyboardMO();
}
}
componentDidLoad() {
/**
* If a scrollable element is hidden using `display: none`,
* it will not have a scroll height meaning we cannot scroll elements
* into view. As a result, we will need to wait for the datetime to become
* visible if used inside of a modal or a popover otherwise the scrollable
* areas will not have the correct values snapped into place.
*/
let visibleIO: IntersectionObserver | undefined;
const visibleCallback = (entries: IntersectionObserverEntry[]) => {
const ev = entries[0];
if (!ev.isIntersecting) { return; }
this.initializeCalendarIOListeners();
this.initializeKeyboardListeners();
this.initializeOverlayListener();
/**
* TODO: Datetime needs a frame to ensure that it
* can properly scroll contents into view. As a result
* we hide the scrollable content until after that frame
* so users do not see the content quickly shifting. The downside
* is that the content will pop into view a frame after. Maybe there
* is a better way to handle this?
*/
writeTask(() => {
this.el.classList.add('datetime-ready');
});
}
visibleIO = new IntersectionObserver(visibleCallback, { threshold: 0.01 });
visibleIO.observe(this.el);
/**
* We need to clean up listeners when the datetime is hidden
* in a popover/modal so that we can properly scroll containers
* back into view if they are re-presented. When the datetime is hidden
* the scroll areas have scroll widths/heights of 0px, so any snapping
* we did originally has been lost.
*/
let hiddenIO: IntersectionObserver | undefined;
const hiddenCallback = (entries: IntersectionObserverEntry[]) => {
const ev = entries[0];
if (ev.isIntersecting) { return; }
this.destroyListeners();
writeTask(() => {
this.el.classList.remove('datetime-ready');
});
}
hiddenIO = new IntersectionObserver(hiddenCallback, { threshold: 0 });
hiddenIO.observe(this.el);
/**
* Datetime uses Ionic components that emit
* ionFocus and ionBlur. These events are
* composed meaning they will cross
* the shadow dom boundary. We need to
* stop propagation on these events otherwise
* developers will see 2 ionFocus or 2 ionBlur
* events at a time.
*/
const root = getElementRoot(this.el);
root.addEventListener('ionFocus', (ev: Event) => ev.stopPropagation());
root.addEventListener('ionBlur', (ev: Event) => ev.stopPropagation());
}
/**
* When doing subsequent presentations of an inline
* overlay, the IO callback will fire again causing
* the calendar to go back one month. We need to listen
* for the presentation of the overlay so we can properly
* cancel that IO callback.
*/
private initializeOverlayListener = () => {
const overlay = this.el.closest('ion-popover, ion-modal');
if (overlay === null) { return; }
overlay.addEventListener('willPresent', () => {
this.overlayIsPresenting = true;
});
}
private processValue = (value?: string | null) => {
const valueToProcess = value || getToday();
const { month, day, year, hour, minute, tzOffset } = parseDate(valueToProcess);
this.workingParts = {
month,
day,
year,
hour,
minute,
tzOffset,
ampm: hour >= 12 ? 'pm' : 'am'
}
this.activePartsClone = this.activeParts = {
month,
day,
year,
hour,
minute,
tzOffset,
ampm: hour >= 12 ? 'pm' : 'am'
}
}
componentWillLoad() {
this.processValue(this.value);
this.processMinParts();
this.processMaxParts();
this.parsedHourValues = convertToArrayOfNumbers(this.hourValues);
this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues);
this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues);
this.parsedYearValues = convertToArrayOfNumbers(this.yearValues);
this.parsedDayValues = convertToArrayOfNumbers(this.dayValues);
this.emitStyle();
}
private emitStyle() {
this.ionStyle.emit({
'interactive': true,
'datetime': true,
'interactive-disabled': this.disabled,
});
}
private onFocus = () => {
this.ionFocus.emit();
}
private onBlur = () => {
this.ionBlur.emit();
}
private hasValue = () => {
return this.value != null && this.value !== '';
}
private nextMonth = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const nextMonth = calendarBodyRef.querySelector('.calendar-month:last-of-type');
if (!nextMonth) { return; }
calendarBodyRef.scrollTo({
top: 0,
left: (nextMonth as HTMLElement).offsetWidth * 2,
behavior: 'smooth'
});
}
private prevMonth = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const prevMonth = calendarBodyRef.querySelector('.calendar-month:first-of-type');
if (!prevMonth) { return; }
calendarBodyRef.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
});
}
private renderFooter() {
const { showDefaultButtons, showClearButton } = this;
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (!hasSlottedButtons && !showDefaultButtons && !showClearButton) { return; }
const clearButtonClick = () => {
this.reset();
this.value = undefined;
}
/**
* By default we render two buttons:
* Cancel - Dismisses the datetime and
* does not update the `value` prop.
* OK - Dismisses the datetime and
* updates the `value` prop.
*/
return (
<div class="datetime-footer">
<div class="datetime-buttons">
<div class={{
['datetime-action-buttons']: true,
['has-clear-button']: this.showClearButton
}}>
<slot name="buttons">
<ion-buttons>
{showDefaultButtons && <ion-button id="cancel-button" color={this.color} onClick={() => this.cancel(true)}>{this.cancelText}</ion-button>}
<div>
{showClearButton && <ion-button id="clear-button" color={this.color} onClick={() => clearButtonClick()}>{this.clearText}</ion-button>}
{showDefaultButtons && <ion-button id="confirm-button" color={this.color} onClick={() => this.confirm(true)}>{this.doneText}</ion-button>}
</div>
</ion-buttons>
</slot>
</div>
</div>
</div>
);
}
private toggleMonthAndYearView = () => {
this.showMonthAndYear = !this.showMonthAndYear;
}
private renderYearView() {
const { presentation, workingParts } = this;
const calendarYears = getCalendarYears(this.todayParts, this.minParts, this.maxParts, this.parsedYearValues);
const showMonth = presentation !== 'year';
const showYear = presentation !== 'month';
const months = getPickerMonths(this.locale, workingParts, this.minParts, this.maxParts, this.parsedMonthValues);
const years = calendarYears.map(year => {
return {
text: `${year}`,
value: year
}
})
return (
<div class="datetime-year">
<div class="datetime-year-body">
<ion-picker-internal>
{
showMonth &&
<ion-picker-column-internal
color={this.color}
items={months}
value={workingParts.month}
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...this.workingParts,
month: ev.detail.value
});
if (presentation === 'month' || presentation === 'month-year') {
this.setActiveParts({
...this.activeParts,
month: ev.detail.value
});
}
ev.stopPropagation();
}}
></ion-picker-column-internal>
}
{
showYear &&
<ion-picker-column-internal
color={this.color}
items={years}
value={workingParts.year}
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...this.workingParts,
year: ev.detail.value
});
if (presentation === 'year' || presentation === 'month-year') {
this.setActiveParts({
...this.activeParts,
year: ev.detail.value
});
}
ev.stopPropagation();
}}
></ion-picker-column-internal>
}
</ion-picker-internal>
</div>
</div>
);
}
private renderCalendarHeader(mode: Mode) {
const expandedIcon = mode === 'ios' ? chevronDown : caretUpSharp;
const collapsedIcon = mode === 'ios' ? chevronForward : caretDownSharp;
return (
<div class="calendar-header">
<div class="calendar-action-buttons">
<div class="calendar-month-year">
<ion-item button detail={false} lines="none" onClick={() => this.toggleMonthAndYearView()}>
<ion-label>
{getMonthAndYear(this.locale, this.workingParts)} <ion-icon icon={this.showMonthAndYear ? expandedIcon : collapsedIcon} lazy={false}></ion-icon>
</ion-label>
</ion-item>
</div>
<div class="calendar-next-prev">
<ion-buttons>
<ion-button onClick={() => this.prevMonth()}>
<ion-icon slot="icon-only" icon={chevronBack} lazy={false}></ion-icon>
</ion-button>
<ion-button onClick={() => this.nextMonth()}>
<ion-icon slot="icon-only" icon={chevronForward} lazy={false}></ion-icon>
</ion-button>
</ion-buttons>
</div>
</div>
<div class="calendar-days-of-week">
{getDaysOfWeek(this.locale, mode, this.firstDayOfWeek % 7).map(d => {
return <div class="day-of-week">{d}</div>
})}
</div>
</div>
)
}
private renderMonth(month: number, year: number) {
const yearAllowed = this.parsedYearValues === undefined || this.parsedYearValues.includes(year);
const monthAllowed = this.parsedMonthValues === undefined || this.parsedMonthValues.includes(month);
const isMonthDisabled = !yearAllowed || !monthAllowed;
return (
<div class="calendar-month">
<div class="calendar-month-grid">
{getDaysOfMonth(month, year, this.firstDayOfWeek % 7).map((dateObject, index) => {
const { day, dayOfWeek } = dateObject;
const referenceParts = { month, day, year };
const { isActive, isToday, ariaLabel, ariaSelected, disabled } = getCalendarDayState(this.locale, referenceParts, this.activePartsClone, this.todayParts, this.minParts, this.maxParts, this.parsedDayValues);
return (
<button
tabindex="-1"
data-day={day}
data-month={month}
data-year={year}
data-index={index}
data-day-of-week={dayOfWeek}
disabled={isMonthDisabled || disabled}
class={{
'calendar-day-padding': day === null,
'calendar-day': true,
'calendar-day-active': isActive,
'calendar-day-today': isToday
}}
aria-selected={ariaSelected}
aria-label={ariaLabel}
onClick={() => {
if (day === null) { return; }
this.setWorkingParts({
...this.workingParts,
month,
day,
year
});
this.setActiveParts({
...this.activeParts,
month,
day,
year
})
}}
>{day}</button>
)
})}
</div>
</div>
)
}
private renderCalendarBody() {
return (
<div class="calendar-body ion-focusable" ref={el => this.calendarBodyRef = el} tabindex="0">
{generateMonths(this.workingParts).map(({ month, year }) => {
return this.renderMonth(month, year);
})}
</div>
)
}
private renderCalendar(mode: Mode) {
return (
<div class="datetime-calendar">
{this.renderCalendarHeader(mode)}
{this.renderCalendarBody()}
</div>
)
}
private renderTimeLabel() {
const hasSlottedTimeLabel = this.el.querySelector('[slot="time-label"]') !== null;
if (!hasSlottedTimeLabel && !this.showDefaultTimeLabel) { return; }
return (
<slot name="time-label">Time</slot>
);
}
private renderTimePicker(
hoursItems: PickerColumnItem[],
minutesItems: PickerColumnItem[],
ampmItems: PickerColumnItem[],
use24Hour: boolean
) {
const { color, activePartsClone, workingParts } = this;
return (
<ion-picker-internal>
<ion-picker-column-internal
color={color}
value={activePartsClone.hour}
items={hoursItems}
numericInput
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...workingParts,
hour: ev.detail.value
});
this.setActiveParts({
...activePartsClone,
hour: ev.detail.value
});
ev.stopPropagation();
}}
></ion-picker-column-internal>
<ion-picker-column-internal
color={color}
value={activePartsClone.minute}
items={minutesItems}
numericInput
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...workingParts,
minute: ev.detail.value
});
this.setActiveParts({
...activePartsClone,
minute: ev.detail.value
});
ev.stopPropagation();
}}
></ion-picker-column-internal>
{ !use24Hour && <ion-picker-column-internal
color={color}
value={activePartsClone.ampm}
items={ampmItems}
onIonChange={(ev: CustomEvent) => {
const hour = calculateHourFromAMPM(workingParts, ev.detail.value);
this.setWorkingParts({
...workingParts,
ampm: ev.detail.value,
hour
});
this.setActiveParts({
...activePartsClone,
ampm: ev.detail.value,
hour
});
ev.stopPropagation();
}}
></ion-picker-column-internal> }
</ion-picker-internal>
)
}
private renderTimeOverlay(
hoursItems: PickerColumnItem[],
minutesItems: PickerColumnItem[],
ampmItems: PickerColumnItem[],
use24Hour: boolean
) {
return [
<div class="time-header">
{this.renderTimeLabel()}
</div>,
<button
class={{
'time-body': true,
'time-body-active': this.isTimePopoverOpen
}}
aria-expanded="false"
aria-haspopup="true"
onClick={async ev => {
const { popoverRef } = this;
if (popoverRef) {
this.isTimePopoverOpen = true;
popoverRef.present(ev);
await popoverRef.onWillDismiss();
this.isTimePopoverOpen = false;
}
}}
>
{getFormattedTime(this.activePartsClone, use24Hour)}
</button>,
<ion-popover
alignment="center"
translucent
overlayIndex={1}
arrow={false}
style={{
'--offset-y': '-10px'
}}
ref={el => this.popoverRef = el}
>
{this.renderTimePicker(hoursItems, minutesItems, ampmItems, use24Hour)}
</ion-popover>
]
}
/**
* Render time picker inside of datetime.
* Do not pass color prop to segment on
* iOS mode. MD segment has been customized and
* should take on the color prop, but iOS
* should just be the default segment.
*/
private renderTime() {
const { workingParts, presentation } = this;
const timeOnlyPresentation = presentation === 'time';
const use24Hour = is24Hour(this.locale, this.hourCycle);
const { hours, minutes, am, pm } = generateTime(this.workingParts, use24Hour ? 'h23' : 'h12', this.minParts, this.maxParts, this.parsedHourValues, this.parsedMinuteValues);
const hoursItems = hours.map(hour => {
return {
text: getFormattedHour(hour, use24Hour),
value: getInternalHourValue(hour, use24Hour, workingParts.ampm)
}
});
const minutesItems = minutes.map(minute => {
return {
text: addTimePadding(minute),
value: minute
}
});
const ampmItems = [];
if (am) {
ampmItems.push({
text: 'AM',
value: 'am'
})
}
if (pm) {
ampmItems.push({
text: 'PM',
value: 'pm'
})
}
return (
<div class="datetime-time">
{timeOnlyPresentation ? this.renderTimePicker(hoursItems, minutesItems, ampmItems, use24Hour) : this.renderTimeOverlay(hoursItems, minutesItems, ampmItems, use24Hour)}
</div>
)
}
private renderCalendarViewHeader(mode: Mode) {
const hasSlottedTitle = this.el.querySelector('[slot="title"]') !== null;
if (!hasSlottedTitle && !this.showDefaultTitle) { return; }
return (
<div class="datetime-header">
<div class="datetime-title">
<slot name="title">Select Date</slot>
</div>
{mode === 'md' && <div class="datetime-selected-date">
{getMonthAndDay(this.locale, this.activeParts)}
</div>}
</div>
);
}
private renderDatetime(mode: Mode) {
const { presentation } = this;
switch (presentation) {
case 'date-time':
return [
this.renderCalendarViewHeader(mode),
this.renderCalendar(mode),
this.renderYearView(),
this.renderTime(),
this.renderFooter()
]
case 'time-date':
return [
this.renderCalendarViewHeader(mode),
this.renderTime(),
this.renderCalendar(mode),
this.renderYearView(),
this.renderFooter()
]
case 'time':
return [
this.renderTime(),
this.renderFooter()
]
case 'month':
case 'month-year':
case 'year':
return [
this.renderYearView(),
this.renderFooter()
]
default:
return [
this.renderCalendarViewHeader(mode),
this.renderCalendar(mode),
this.renderYearView(),
this.renderFooter()
]
}
}
render() {
const { name, value, disabled, el, color, isPresented, readonly, showMonthAndYear, presentation, size } = this;
const mode = getIonMode(this);
const isMonthAndYearPresentation = presentation === 'year' || presentation === 'month' || presentation === 'month-year';
const shouldShowMonthAndYear = showMonthAndYear || isMonthAndYearPresentation;
renderHiddenInput(true, el, name, value, disabled);
return (
<Host
aria-disabled={disabled ? 'true' : null}
onFocus={this.onFocus}
onBlur={this.onBlur}
class={{
...createColorClasses(color, {
[mode]: true,
['datetime-presented']: isPresented,
['datetime-readonly']: readonly,
['datetime-disabled']: disabled,
'show-month-and-year': shouldShowMonthAndYear,
[`datetime-presentation-${presentation}`]: true,
[`datetime-size-${size}`]: true
})
}}
>
{this.renderDatetime(mode)}
</Host>
);
}
}
let datetimeIds = 0;
| core/src/components/datetime/datetime.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.005736759398132563,
0.00025480741169303656,
0.0001603350101504475,
0.00017087871674448252,
0.0004940858925692737
] |
{
"id": 0,
"code_window": [
" * If `true`, the keyboard will be automatically dismissed when the overlay is presented.\n",
" */\n",
" \"keyboardClose\": boolean;\n",
" /**\n",
" * Animation to use when the popover is dismissed.\n",
" */\n",
" \"leaveAnimation\"?: AnimationBuilder;\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"keyboardEvents\": boolean;\n"
],
"file_path": "core/src/components.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | ```html
<template>
<ion-list>
<ion-item>
<ion-range color="danger" :pin="true"></ion-range>
</ion-item>
<ion-item>
<ion-range min="-200" max="200" color="secondary">
<ion-label slot="start">-200</ion-label>
<ion-label slot="end">200</ion-label>
</ion-range>
</ion-item>
<ion-item>
<ion-range min="20" max="80" step="2">
<ion-icon size="small" slot="start" name="sunny"></ion-icon>
<ion-icon slot="end" name="sunny"></ion-icon>
</ion-range>
</ion-item>
<ion-item>
<ion-range min="1000" max="2000" step="100" snaps="true" color="secondary"></ion-range>
</ion-item>
<ion-item>
<ion-range min="1000" max="2000" step="100" snaps="true" ticks="false" color="secondary"></ion-range>
</ion-item>
<ion-item>
<ion-range ref="rangeDualKnobs" dual-knobs="true" min="21" max="72" step="3" snaps="true"></ion-range>
</ion-item>
<ion-item>
<ion-range min="0" max="100" :pin-formatter="customFormatter" :pin="true"></ion-range>
</ion-item>
</ion-list>
</template>
<script lang="ts">
import { IonItem, IonLabel, IonList, IonRange } from '@ionic/vue';
import { defineComponent } from 'vue';
export default defineComponent({
components: { IonItem, IonLabel, IonList, IonRange },
mounted() {
// Sets initial value for dual-knob ion-range
this.$refs.rangeDualKnobs.value = { lower: 24, upper: 42 };
},
setup() {
const customFormatter = (value: number) => `${value}%`;
return { customFormatter };
}
});
</script>
```
| core/src/components/range/usage/vue.md | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0001759548467816785,
0.0001742346357787028,
0.00017305123037658632,
0.00017412012675777078,
0.0000011218251074751606
] |
{
"id": 0,
"code_window": [
" * If `true`, the keyboard will be automatically dismissed when the overlay is presented.\n",
" */\n",
" \"keyboardClose\": boolean;\n",
" /**\n",
" * Animation to use when the popover is dismissed.\n",
" */\n",
" \"leaveAnimation\"?: AnimationBuilder;\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"keyboardEvents\": boolean;\n"
],
"file_path": "core/src/components.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | @import "../../themes/ionic.globals.ios";
// iOS Header
// --------------------------------------------------
/// @prop - Blur value for backdrop-filter
$header-ios-blur: 20px;
/// @prop - Filter of the translucent header
$header-ios-translucent-filter: saturate(180%) blur($header-ios-blur) !default;
| core/src/components/header/header.ios.vars.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017275431309826672,
0.00017131376080214977,
0.00016987320850603282,
0.00017131376080214977,
0.0000014405522961169481
] |
{
"id": 0,
"code_window": [
" * If `true`, the keyboard will be automatically dismissed when the overlay is presented.\n",
" */\n",
" \"keyboardClose\": boolean;\n",
" /**\n",
" * Animation to use when the popover is dismissed.\n",
" */\n",
" \"leaveAnimation\"?: AnimationBuilder;\n",
" /**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"keyboardEvents\": boolean;\n"
],
"file_path": "core/src/components.d.ts",
"type": "add",
"edit_start_line_idx": 1000
} | <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Slides - Image</title>
<meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="../../../../../css/ionic.bundle.css" rel="stylesheet">
<link href="../../../../../scripts/testing/styles.css" rel="stylesheet">
<script src="../../../../../scripts/testing/scripts.js"></script>
<script nomodule src="../../../../../dist/ionic/ionic.js"></script>
<script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script> <style>
ion-slide {
height: 200px !important;
}
</style>
</head>
<body>
<ion-app>
<ion-content id="content">
<ion-slides style="background: black" id="slides" pager>
<ion-slide style="background: rgb(0, 200, 0); color: white;">
<img src="image/cat.jpeg">
</ion-slide>
<ion-slide style="background: white; color: blue;">
<img src="image/cat.jpeg">
</ion-slide>
<ion-slide style="background: blue; color: white;">
<img src="image/cat.jpeg">
</ion-slide>
</ion-slides>
<ion-button expand="block" onclick="slidePrev()">Slide Prev</ion-button>
<ion-button expand="block" onclick="slideNext()">Slide Next</ion-button>
<ion-button expand="block" onclick="getActiveIndex()">Get Active Index</ion-button>
<ion-button expand="block" onclick="getPreviousIndex()">Get Previous Index</ion-button>
<ion-button expand="block" onclick="isEnd()">Is the End?</ion-button>
<ion-button expand="block" onclick="isBeginning()">Is the beginning?</ion-button>
<ion-button expand="block" onclick="slideTo()">Slide to slide index 2</ion-button>
<ion-button expand="block" onclick="slideLength()">Get slide length</ion-button>
<ion-button expand="block" onclick="slideAutoPlay()">Start auto play</ion-button>
<ion-button expand="block" onclick="slideStopAutoPlay()">Stop auto play</ion-button>
<ion-button expand="block" onclick="setOptions()">Set options</ion-button>
</ion-content>
</ion-app>
<script>
const slides = document.getElementById('slides')
slides.pager = false;
slides.options = {}
async function slideNext() {
await slides.slideNext(500)
};
async function slidePrev() {
await slides.slidePrev(500);
};
async function slideTo() {
await slides.slideTo(2);
}
async function slideAutoPlay() {
slides.options = Object.assign({}, slides.options, {
autoplay: {
delay: 2500,
disableOnInteraction: false
}
});
await slides.startAutoplay();
}
async function slideStopAutoPlay() {
await slides.stopAutoplay();
}
async function setOptions() {
slides.options = Object.assign({}, slides.options, {
slidesPerView: 2,
});
}
async function slideLength() {
console.log(await slides.length());
}
async function getActiveIndex() {
console.log(await slides.getActiveIndex());
};
async function getPreviousIndex() {
console.log(await slides.getPreviousIndex());
};
async function isEnd() {
console.log(await slides.isEnd());
}
async function isBeginning() {
console.log(await slides.isBeginning());
}
slides.addEventListener('ionSlideDidChange', function (e) {
console.log('slide did change', e)
});
slides.addEventListener('ionSlideWillChange', function (e) {
console.log('slide will change', e)
});
slides.addEventListener('ionSlideNextStart', function (e) {
console.log('slide next start', e)
});
slides.addEventListener('ionSlidePrevStart', function (e) {
console.log('slide prev start', e)
});
slides.addEventListener('ionSlideNextEnd', function (e) {
console.log('slide next end', e)
});
slides.addEventListener('ionSlidePrevEnd', function (e) {
console.log('slide prev end', e)
});
slides.addEventListener('ionSlideTransitionStart', function (e) {
console.log('slide transition start', e)
});
slides.addEventListener('ionSlideTransitionEnd', function (e) {
console.log('slide transition end', e)
});
slides.addEventListener('ionSlideDrag', function (e) {
console.log('slide drag', e)
});
slides.addEventListener('ionSlideReachStart', function (e) {
console.log('slide reach start', e)
});
slides.addEventListener('ionSlideReachEnd', function (e) {
console.log('slide reach end', e)
});
slides.addEventListener('ionSlideTouchStart', function (e) {
console.log('slide touch start', e)
});
slides.addEventListener('ionSlideTouchEnd', function (e) {
console.log('slide touch end', e)
});
slides.addEventListener('ionSlidesDidLoad', function (e) {
console.log('slides did load', e)
});
slides.addEventListener('ionSlideTap', function (e) {
console.log('slide tapped', e)
});
slides.addEventListener('ionSlideDoubleTap', function (e) {
console.log('slide double-tapped', e)
});
</script>
</body>
</html>
| core/src/components/slides/test/image/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0002467070589773357,
0.00017630636284593493,
0.0001673799124546349,
0.00017221106099896133,
0.000018287535567651503
] |
{
"id": 3,
"code_window": [
" * the popover dismisses. You will need to do that in your code.\n",
" */\n",
" @Prop() isOpen = false;\n",
"\n",
" @Watch('trigger')\n",
" @Watch('triggerAction')\n",
" onTriggerChange() {\n",
" this.configureTriggerInteraction();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @internal\n",
" *\n",
" * If `true` the popover will not register its own keyboard event handlers.\n",
" * This allows the contents of the popover to handle their own keyboard interactions.\n",
" *\n",
" * If `false`, the popover will register its own keyboard event handlers for\n",
" * navigating `ion-list` items within a popover (up/down/home/end/etc.).\n",
" * This will also cancel browser keyboard event bindings to prevent scroll\n",
" * behavior in a popover using a list of items.\n",
" */\n",
" @Prop() keyboardEvents = false;\n",
"\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "add",
"edit_start_line_idx": 210
} | import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, State, Watch, h } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
import { AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, OverlayEventDetail, PopoverAttributes, PopoverInterface, PopoverSize, PositionAlign, PositionReference, PositionSide, TriggerAction } from '../../interface';
import { CoreDelegate, attachComponent, detachComponent } from '../../utils/framework-delegate';
import { addEventListener, raf } from '../../utils/helpers';
import { BACKDROP, dismiss, eventMethod, focusFirstDescendant, prepareOverlay, present } from '../../utils/overlays';
import { isPlatform } from '../../utils/platform';
import { getClassMap } from '../../utils/theme';
import { deepReady } from '../../utils/transition';
import { iosEnterAnimation } from './animations/ios.enter';
import { iosLeaveAnimation } from './animations/ios.leave';
import { mdEnterAnimation } from './animations/md.enter';
import { mdLeaveAnimation } from './animations/md.leave';
import { configureDismissInteraction, configureKeyboardInteraction, configureTriggerInteraction } from './utils';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - Content is placed inside of the `.popover-content` element.
*
* @part backdrop - The `ion-backdrop` element.
* @part arrow - The arrow that points to the reference element. Only applies on `ios` mode.
* @part content - The wrapper element for the default slot.
*/
@Component({
tag: 'ion-popover',
styleUrls: {
ios: 'popover.ios.scss',
md: 'popover.md.scss'
},
shadow: true
})
export class Popover implements ComponentInterface, PopoverInterface {
private usersElement?: HTMLElement;
private triggerEl?: HTMLElement | null;
private parentPopover: HTMLIonPopoverElement | null = null;
private popoverIndex = popoverIds++;
private popoverId?: string;
private coreDelegate: FrameworkDelegate = CoreDelegate();
private currentTransition?: Promise<any>;
private destroyTriggerInteraction?: () => void;
private destroyKeyboardInteraction?: () => void;
private destroyDismissInteraction?: () => void;
private inline = false;
private workingDelegate?: FrameworkDelegate;
private focusDescendantOnPresent = false;
lastFocus?: HTMLElement;
@State() presented = false;
@Element() el!: HTMLIonPopoverElement;
/** @internal */
@Prop() hasController = false;
/** @internal */
@Prop() delegate?: FrameworkDelegate;
/** @internal */
@Prop() overlayIndex!: number;
/**
* Animation to use when the popover is presented.
*/
@Prop() enterAnimation?: AnimationBuilder;
/**
* Animation to use when the popover is dismissed.
*/
@Prop() leaveAnimation?: AnimationBuilder;
/**
* The component to display inside of the popover.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* slot your component inside of `ion-popover`.
*/
@Prop() component?: ComponentRef;
/**
* The data to pass to the popover component.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* set the props directly on your component.
*/
@Prop() componentProps?: ComponentProps;
/**
* If `true`, the keyboard will be automatically dismissed when the overlay is presented.
*/
@Prop() keyboardClose = true;
/**
* Additional classes to apply for custom CSS. If multiple classes are
* provided they should be separated by spaces.
* @internal
*/
@Prop() cssClass?: string | string[];
/**
* If `true`, the popover will be dismissed when the backdrop is clicked.
*/
@Prop() backdropDismiss = true;
/**
* The event to pass to the popover animation.
*/
@Prop() event: any;
/**
* If `true`, a backdrop will be displayed behind the popover.
*/
@Prop() showBackdrop = true;
/**
* If `true`, the popover will be translucent.
* Only applies when the mode is `"ios"` and the device supports
* [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility).
*/
@Prop() translucent = false;
/**
* If `true`, the popover will animate.
*/
@Prop() animated = true;
/**
* Additional attributes to pass to the popover.
*/
@Prop() htmlAttributes?: PopoverAttributes;
/**
* Describes what kind of interaction with the trigger that
* should cause the popover to open. Does not apply when the `trigger`
* property is `undefined`.
* If `'click'`, the popover will be presented when the trigger is left clicked.
* If `'hover'`, the popover will be presented when a pointer hovers over the trigger.
* If `'context-menu'`, the popover will be presented when the trigger is right
* clicked on desktop and long pressed on mobile. This will also prevent your
* device's normal context menu from appearing.
*/
@Prop() triggerAction: TriggerAction = 'click';
/**
* An ID corresponding to the trigger element that
* causes the popover to open. Use the `trigger-action`
* property to customize the interaction that results in
* the popover opening.
*/
@Prop() trigger: string | undefined;
/**
* Describes how to calculate the popover width.
* If `'cover'`, the popover width will match the width of the trigger.
* If `'auto'`, the popover width will be determined by the content in
* the popover.
*/
@Prop() size: PopoverSize = 'auto';
/**
* If `true`, the popover will be automatically
* dismissed when the content has been clicked.
*/
@Prop() dismissOnSelect = false;
/**
* Describes what to position the popover relative to.
* If `'trigger'`, the popover will be positioned relative
* to the trigger button. If passing in an event, this is
* determined via event.target.
* If `'event'`, the popover will be positioned relative
* to the x/y coordinates of the trigger action. If passing
* in an event, this is determined via event.clientX and event.clientY.
*/
@Prop() reference: PositionReference = 'trigger';
/**
* Describes which side of the `reference` point to position
* the popover on. The `'start'` and `'end'` values are RTL-aware,
* and the `'left'` and `'right'` values are not.
*/
@Prop() side: PositionSide = 'bottom';
/**
* Describes how to align the popover content with the `reference` point.
*/
@Prop() alignment: PositionAlign = 'start';
/**
* If `true`, the popover will display an arrow
* that points at the `reference` when running in `ios` mode
* on mobile. Does not apply in `md` mode or on desktop.
*/
@Prop() arrow = true;
/**
* If `true`, the popover will open. If `false`, the popover will close.
* Use this if you need finer grained control over presentation, otherwise
* just use the popoverController or the `trigger` property.
* Note: `isOpen` will not automatically be set back to `false` when
* the popover dismisses. You will need to do that in your code.
*/
@Prop() isOpen = false;
@Watch('trigger')
@Watch('triggerAction')
onTriggerChange() {
this.configureTriggerInteraction();
}
@Watch('isOpen')
onIsOpenChange(newValue: boolean, oldValue: boolean) {
if (newValue === true && oldValue === false) {
this.present();
} else if (newValue === false && oldValue === true) {
this.dismiss();
}
}
/**
* Emitted after the popover has presented.
*/
@Event({ eventName: 'ionPopoverDidPresent' }) didPresent!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
*/
@Event({ eventName: 'ionPopoverWillPresent' }) willPresent!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has presented.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'didPresent' }) didPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
* Shorthand for ionPopoverWillPresent.
*/
@Event({ eventName: 'willPresent' }) willPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'willDismiss' }) willDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
* Shorthand for ionPopoverDidDismiss.
*/
@Event({ eventName: 'didDismiss' }) didDismissShorthand!: EventEmitter<OverlayEventDetail>;
connectedCallback() {
prepareOverlay(this.el);
}
componentWillLoad() {
/**
* If user has custom ID set then we should
* not assign the default incrementing ID.
*/
this.popoverId = (this.el.hasAttribute('id')) ? this.el.getAttribute('id')! : `ion-popover-${this.popoverIndex}`;
this.parentPopover = this.el.closest(`ion-popover:not(#${this.popoverId})`) as HTMLIonPopoverElement | null;
}
componentDidLoad() {
const { parentPopover, isOpen } = this;
/**
* If popover was rendered with isOpen="true"
* then we should open popover immediately.
*/
if (isOpen === true) {
raf(() => this.present());
}
if (parentPopover) {
addEventListener(parentPopover, 'ionPopoverWillDismiss', () => {
this.dismiss(undefined, undefined, false);
});
}
this.configureTriggerInteraction();
}
/**
* When opening a popover from a trigger, we should not be
* modifying the `event` prop from inside the component.
* Additionally, when pressing the "Right" arrow key, we need
* to shift focus to the first descendant in the newly presented
* popover.
*
* @internal
*/
@Method()
async presentFromTrigger(event?: any, focusDescendant = false) {
this.focusDescendantOnPresent = focusDescendant;
await this.present(event);
this.focusDescendantOnPresent = false;
}
/**
* Determines whether or not an overlay
* is being used inline or via a controller/JS
* and returns the correct delegate.
* By default, subsequent calls to getDelegate
* will use a cached version of the delegate.
* This is useful for calling dismiss after
* present so that the correct delegate is given.
*/
private getDelegate(force = false) {
if (this.workingDelegate && !force) {
return {
delegate: this.workingDelegate,
inline: this.inline
}
}
/**
* If using overlay inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps.
* If a developer has presented this component
* via a controller, then we can assume
* the component is already in the
* correct place.
*/
const parentEl = this.el.parentNode as HTMLElement | null;
const inline = this.inline = parentEl !== null && !this.hasController;
const delegate = this.workingDelegate = (inline) ? this.delegate || this.coreDelegate : this.delegate
return { inline, delegate }
}
/**
* Present the popover overlay after it has been created.
* Developers can pass a mouse, touch, or pointer event
* to position the popover relative to where that event
* was dispatched.
*/
@Method()
async present(event?: MouseEvent | TouchEvent | PointerEvent): Promise<void> {
if (this.presented) {
return;
}
/**
* When using an inline popover
* and dismissing a popover it is possible to
* quickly present the popover while it is
* dismissing. We need to await any current
* transition to allow the dismiss to finish
* before presenting again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const data = {
...this.componentProps,
popover: this.el
};
const { inline, delegate } = this.getDelegate(true);
this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);
await deepReady(this.usersElement);
this.configureKeyboardInteraction();
this.configureDismissInteraction();
this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {
event: event || this.event,
size: this.size,
trigger: this.triggerEl,
reference: this.reference,
side: this.side,
align: this.alignment
});
await this.currentTransition;
this.currentTransition = undefined;
/**
* If popover is nested and was
* presented using the "Right" arrow key,
* we need to move focus to the first
* descendant inside of the popover.
*/
if (this.focusDescendantOnPresent) {
focusFirstDescendant(this.el, this.el);
}
}
/**
* Dismiss the popover overlay after it has been presented.
*
* @param data Any data to emit in the dismiss events.
* @param role The role of the element that is dismissing the popover. For example, 'cancel' or 'backdrop'.
* @param dismissParentPopover If `true`, dismissing this popover will also dismiss
* a parent popover if this popover is nested. Defaults to `true`.
*/
@Method()
async dismiss(data?: any, role?: string, dismissParentPopover = true): Promise<boolean> {
/**
* When using an inline popover
* and presenting a popover it is possible to
* quickly dismiss the popover while it is
* presenting. We need to await any current
* transition to allow the present to finish
* before dismissing again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const { destroyKeyboardInteraction, destroyDismissInteraction } = this;
if (dismissParentPopover && this.parentPopover) {
this.parentPopover.dismiss(data, role, dismissParentPopover)
}
this.currentTransition = dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
const shouldDismiss = await this.currentTransition;
if (shouldDismiss) {
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
this.destroyKeyboardInteraction = undefined;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
this.destroyDismissInteraction = undefined;
}
/**
* If using popover inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps
*/
const { delegate } = this.getDelegate();
await detachComponent(delegate, this.usersElement);
}
this.currentTransition = undefined;
return shouldDismiss;
}
/**
* @internal
*/
@Method()
async getParentPopover(): Promise<HTMLIonPopoverElement | null> {
return this.parentPopover;
}
/**
* Returns a promise that resolves when the popover did dismiss.
*/
@Method()
onDidDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverDidDismiss');
}
/**
* Returns a promise that resolves when the popover will dismiss.
*/
@Method()
onWillDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverWillDismiss');
}
private onDismiss = (ev: UIEvent) => {
ev.stopPropagation();
ev.preventDefault();
this.dismiss();
}
private onBackdropTap = () => {
this.dismiss(undefined, BACKDROP);
}
private onLifecycle = (modalEvent: CustomEvent) => {
const el = this.usersElement;
const name = LIFECYCLE_MAP[modalEvent.type];
if (el && name) {
const event = new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: modalEvent.detail
});
el.dispatchEvent(event);
}
}
private configureTriggerInteraction = () => {
const { trigger, triggerAction, el, destroyTriggerInteraction } = this;
if (destroyTriggerInteraction) {
destroyTriggerInteraction();
}
const triggerEl = this.triggerEl = (trigger !== undefined) ? document.getElementById(trigger) : null;
if (!triggerEl) { return; }
this.destroyTriggerInteraction = configureTriggerInteraction(triggerEl, triggerAction, el);
}
private configureKeyboardInteraction = () => {
const { destroyKeyboardInteraction, el } = this;
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
}
this.destroyKeyboardInteraction = configureKeyboardInteraction(el);
}
private configureDismissInteraction = () => {
const { destroyDismissInteraction, parentPopover, triggerAction, triggerEl, el } = this;
if (!parentPopover || !triggerEl) { return; }
if (destroyDismissInteraction) {
destroyDismissInteraction();
}
this.destroyDismissInteraction = configureDismissInteraction(triggerEl, triggerAction, el, parentPopover);
}
render() {
const mode = getIonMode(this);
const { onLifecycle, popoverId, parentPopover, dismissOnSelect, presented, side, arrow, htmlAttributes } = this;
const desktop = isPlatform('desktop');
const enableArrow = arrow && !parentPopover && !desktop;
return (
<Host
aria-modal="true"
no-router
tabindex="-1"
{...htmlAttributes as any}
style={{
zIndex: `${20000 + this.overlayIndex}`,
}}
id={popoverId}
class={{
...getClassMap(this.cssClass),
[mode]: true,
'popover-translucent': this.translucent,
'overlay-hidden': true,
'popover-interactive': presented,
'popover-desktop': desktop,
[`popover-side-${side}`]: true,
'popover-nested': !!parentPopover
}}
onIonPopoverDidPresent={onLifecycle}
onIonPopoverWillPresent={onLifecycle}
onIonPopoverWillDismiss={onLifecycle}
onIonPopoverDidDismiss={onLifecycle}
onIonDismiss={this.onDismiss}
onIonBackdropTap={this.onBackdropTap}
>
{!parentPopover && <ion-backdrop tappable={this.backdropDismiss} visible={this.showBackdrop} part="backdrop" />}
<div
class="popover-wrapper ion-overlay-wrapper"
onClick={dismissOnSelect ? () => this.dismiss() : undefined}
>
{enableArrow && <div class="popover-arrow" part="arrow"></div>}
<div class="popover-content" part="content">
<slot></slot>
</div>
</div>
</Host>
);
}
}
const LIFECYCLE_MAP: any = {
'ionPopoverDidPresent': 'ionViewDidEnter',
'ionPopoverWillPresent': 'ionViewWillEnter',
'ionPopoverWillDismiss': 'ionViewWillLeave',
'ionPopoverDidDismiss': 'ionViewDidLeave',
};
let popoverIds = 0;
| core/src/components/popover/popover.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.11430512368679047,
0.0027423985302448273,
0.0001651340862736106,
0.0002078482211800292,
0.014510621316730976
] |
{
"id": 3,
"code_window": [
" * the popover dismisses. You will need to do that in your code.\n",
" */\n",
" @Prop() isOpen = false;\n",
"\n",
" @Watch('trigger')\n",
" @Watch('triggerAction')\n",
" onTriggerChange() {\n",
" this.configureTriggerInteraction();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @internal\n",
" *\n",
" * If `true` the popover will not register its own keyboard event handlers.\n",
" * This allows the contents of the popover to handle their own keyboard interactions.\n",
" *\n",
" * If `false`, the popover will register its own keyboard event handlers for\n",
" * navigating `ion-list` items within a popover (up/down/home/end/etc.).\n",
" * This will also cancel browser keyboard event bindings to prevent scroll\n",
" * behavior in a popover using a list of items.\n",
" */\n",
" @Prop() keyboardEvents = false;\n",
"\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "add",
"edit_start_line_idx": 210
} | @import "./popover";
@import "./popover.md.vars";
// Material Design Popover
// --------------------------------------------------
:host {
--width: #{$popover-md-width};
--max-height: #{$popover-md-max-height};
--box-shadow: #{$popover-md-box-shadow};
--backdrop-opacity: var(--ion-backdrop-opacity, 0.32);
}
.popover-content {
@include border-radius($popover-md-border-radius);
@include transform-origin(start, top);
}
.popover-viewport {
transition-delay: 100ms;
}
| core/src/components/popover/popover.md.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0001820306060835719,
0.00017233396647498012,
0.00016652490012347698,
0.00016844640776980668,
0.000006901284905325156
] |
{
"id": 3,
"code_window": [
" * the popover dismisses. You will need to do that in your code.\n",
" */\n",
" @Prop() isOpen = false;\n",
"\n",
" @Watch('trigger')\n",
" @Watch('triggerAction')\n",
" onTriggerChange() {\n",
" this.configureTriggerInteraction();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @internal\n",
" *\n",
" * If `true` the popover will not register its own keyboard event handlers.\n",
" * This allows the contents of the popover to handle their own keyboard interactions.\n",
" *\n",
" * If `false`, the popover will register its own keyboard event handlers for\n",
" * navigating `ion-list` items within a popover (up/down/home/end/etc.).\n",
" * This will also cancel browser keyboard event bindings to prevent scroll\n",
" * behavior in a popover using a list of items.\n",
" */\n",
" @Prop() keyboardEvents = false;\n",
"\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "add",
"edit_start_line_idx": 210
} | <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>Toolbar - Custom</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="../../../../../css/ionic.bundle.css" rel="stylesheet">
<link href="../../../../../scripts/testing/styles.css" rel="stylesheet">
<script src="../../../../../scripts/testing/scripts.js"></script>
<script nomodule src="../../../../../dist/ionic/ionic.js"></script>
<script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script>
</head>
<body>
<ion-app>
<ion-content id="content">
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button default-href="/" text=""></ion-back-button>
<ion-menu-button auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button>
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Default</ion-title>
</ion-toolbar>
<ion-toolbar>
<ion-buttons slot="secondary">
<ion-button fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Default</ion-title>
</ion-toolbar>
<ion-toolbar color="tertiary">
<ion-buttons slot="start">
<ion-back-button default-href="/" text=""></ion-back-button>
<ion-menu-button auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button>
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Color</ion-title>
</ion-toolbar>
<ion-toolbar color="tertiary">
<ion-buttons slot="secondary">
<ion-button fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Color</ion-title>
</ion-toolbar>
<ion-toolbar color="tertiary" class="themed-colors component-colors">
<ion-buttons slot="start">
<ion-back-button default-href="/" text=""></ion-back-button>
<ion-menu-button auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button>
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Color: Themed</ion-title>
</ion-toolbar>
<ion-toolbar color="tertiary" class="themed-colors component-colors">
<ion-buttons slot="secondary">
<ion-button fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Color: Themed</ion-title>
</ion-toolbar>
<ion-toolbar class="themed-colors">
<ion-buttons slot="start">
<ion-back-button default-href="/" text=""></ion-back-button>
<ion-menu-button auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button>
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Themed</ion-title>
</ion-toolbar>
<ion-toolbar class="themed-colors">
<ion-buttons slot="secondary">
<ion-button fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Themed</ion-title>
</ion-toolbar>
<ion-toolbar class="themed-colors">
<ion-buttons slot="start">
<ion-back-button color="danger" default-href="/" text=""></ion-back-button>
<ion-menu-button color="danger" auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button color="danger">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button color="danger">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Themed w / Color Buttons</ion-title>
</ion-toolbar>
<ion-toolbar class="themed-colors">
<ion-buttons slot="secondary">
<ion-button color="danger" fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button color="danger">
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button color="danger" fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button color="danger" fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Themed w / Color Buttons</ion-title>
</ion-toolbar>
<ion-toolbar class="component-colors">
<ion-buttons slot="start">
<ion-back-button default-href="/" text=""></ion-back-button>
<ion-menu-button auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button>
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Component Level Vars</ion-title>
</ion-toolbar>
<ion-toolbar class="component-colors">
<ion-buttons slot="secondary">
<ion-button fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button>
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Component Level Vars</ion-title>
</ion-toolbar>
<ion-toolbar class="component-colors">
<ion-buttons slot="start">
<ion-back-button color="secondary" default-href="/" text=""></ion-back-button>
<ion-menu-button color="secondary" auto-hide="false"></ion-menu-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button color="secondary">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button color="secondary">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Component Level Vars w/ Color Buttons</ion-title>
</ion-toolbar>
<ion-toolbar class="component-colors">
<ion-buttons slot="secondary">
<ion-button color="secondary" fill="clear">
<ion-icon slot="icon-only" ios="list-outline" md="list"></ion-icon>
</ion-button>
<ion-button color="secondary">
<ion-icon slot="icon-only" name="star"></ion-icon>
</ion-button>
</ion-buttons>
<ion-buttons slot="primary">
<ion-button color="secondary" fill="solid">
<ion-icon slot="icon-only" name="person-circle"></ion-icon>
</ion-button>
<ion-button color="secondary" fill="outline">
<ion-icon slot="icon-only" ios="ellipsis-horizontal" md="ellipsis-vertical"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Component Level Vars w/ Color Buttons</ion-title>
</ion-toolbar>
</ion-content>
</ion-app>
<style>
.themed-colors {
--ion-toolbar-background: #d9fae0;
--ion-toolbar-color: #b68928;
}
.component-colors {
--background: #fff4f5;
}
.component-colors,
.component-colors ion-back-button,
.component-colors ion-menu-button,
.component-colors ion-button {
--color: #aa3723;
}
.component-colors ion-button[fill="solid"] {
--background: #aa3723;
--color: #fff;
}
</style>
</body>
</html>
| core/src/components/toolbar/test/custom/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017674682021606714,
0.0001728473143884912,
0.00016890396364033222,
0.00017314974684268236,
0.0000016037989780670614
] |
{
"id": 3,
"code_window": [
" * the popover dismisses. You will need to do that in your code.\n",
" */\n",
" @Prop() isOpen = false;\n",
"\n",
" @Watch('trigger')\n",
" @Watch('triggerAction')\n",
" onTriggerChange() {\n",
" this.configureTriggerInteraction();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /**\n",
" * @internal\n",
" *\n",
" * If `true` the popover will not register its own keyboard event handlers.\n",
" * This allows the contents of the popover to handle their own keyboard interactions.\n",
" *\n",
" * If `false`, the popover will register its own keyboard event handlers for\n",
" * navigating `ion-list` items within a popover (up/down/home/end/etc.).\n",
" * This will also cancel browser keyboard event bindings to prevent scroll\n",
" * behavior in a popover using a list of items.\n",
" */\n",
" @Prop() keyboardEvents = false;\n",
"\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "add",
"edit_start_line_idx": 210
} | export { Swiper as SwiperInterface, SwiperOptions } from 'swiper/js/swiper.esm';
| core/src/components/slides/swiper/swiper-interface.d.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017451388703193516,
0.00017451388703193516,
0.00017451388703193516,
0.00017451388703193516,
0
] |
{
"id": 4,
"code_window": [
" const { inline, delegate } = this.getDelegate(true);\n",
" this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);\n",
" await deepReady(this.usersElement);\n",
"\n",
" this.configureKeyboardInteraction();\n",
" this.configureDismissInteraction();\n",
"\n",
" this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {\n",
" event: event || this.event,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this.keyboardEvents) {\n",
" this.configureKeyboardInteraction();\n",
" }\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "replace",
"edit_start_line_idx": 387
} | import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, State, Watch, h } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
import { AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, OverlayEventDetail, PopoverAttributes, PopoverInterface, PopoverSize, PositionAlign, PositionReference, PositionSide, TriggerAction } from '../../interface';
import { CoreDelegate, attachComponent, detachComponent } from '../../utils/framework-delegate';
import { addEventListener, raf } from '../../utils/helpers';
import { BACKDROP, dismiss, eventMethod, focusFirstDescendant, prepareOverlay, present } from '../../utils/overlays';
import { isPlatform } from '../../utils/platform';
import { getClassMap } from '../../utils/theme';
import { deepReady } from '../../utils/transition';
import { iosEnterAnimation } from './animations/ios.enter';
import { iosLeaveAnimation } from './animations/ios.leave';
import { mdEnterAnimation } from './animations/md.enter';
import { mdLeaveAnimation } from './animations/md.leave';
import { configureDismissInteraction, configureKeyboardInteraction, configureTriggerInteraction } from './utils';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - Content is placed inside of the `.popover-content` element.
*
* @part backdrop - The `ion-backdrop` element.
* @part arrow - The arrow that points to the reference element. Only applies on `ios` mode.
* @part content - The wrapper element for the default slot.
*/
@Component({
tag: 'ion-popover',
styleUrls: {
ios: 'popover.ios.scss',
md: 'popover.md.scss'
},
shadow: true
})
export class Popover implements ComponentInterface, PopoverInterface {
private usersElement?: HTMLElement;
private triggerEl?: HTMLElement | null;
private parentPopover: HTMLIonPopoverElement | null = null;
private popoverIndex = popoverIds++;
private popoverId?: string;
private coreDelegate: FrameworkDelegate = CoreDelegate();
private currentTransition?: Promise<any>;
private destroyTriggerInteraction?: () => void;
private destroyKeyboardInteraction?: () => void;
private destroyDismissInteraction?: () => void;
private inline = false;
private workingDelegate?: FrameworkDelegate;
private focusDescendantOnPresent = false;
lastFocus?: HTMLElement;
@State() presented = false;
@Element() el!: HTMLIonPopoverElement;
/** @internal */
@Prop() hasController = false;
/** @internal */
@Prop() delegate?: FrameworkDelegate;
/** @internal */
@Prop() overlayIndex!: number;
/**
* Animation to use when the popover is presented.
*/
@Prop() enterAnimation?: AnimationBuilder;
/**
* Animation to use when the popover is dismissed.
*/
@Prop() leaveAnimation?: AnimationBuilder;
/**
* The component to display inside of the popover.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* slot your component inside of `ion-popover`.
*/
@Prop() component?: ComponentRef;
/**
* The data to pass to the popover component.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* set the props directly on your component.
*/
@Prop() componentProps?: ComponentProps;
/**
* If `true`, the keyboard will be automatically dismissed when the overlay is presented.
*/
@Prop() keyboardClose = true;
/**
* Additional classes to apply for custom CSS. If multiple classes are
* provided they should be separated by spaces.
* @internal
*/
@Prop() cssClass?: string | string[];
/**
* If `true`, the popover will be dismissed when the backdrop is clicked.
*/
@Prop() backdropDismiss = true;
/**
* The event to pass to the popover animation.
*/
@Prop() event: any;
/**
* If `true`, a backdrop will be displayed behind the popover.
*/
@Prop() showBackdrop = true;
/**
* If `true`, the popover will be translucent.
* Only applies when the mode is `"ios"` and the device supports
* [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility).
*/
@Prop() translucent = false;
/**
* If `true`, the popover will animate.
*/
@Prop() animated = true;
/**
* Additional attributes to pass to the popover.
*/
@Prop() htmlAttributes?: PopoverAttributes;
/**
* Describes what kind of interaction with the trigger that
* should cause the popover to open. Does not apply when the `trigger`
* property is `undefined`.
* If `'click'`, the popover will be presented when the trigger is left clicked.
* If `'hover'`, the popover will be presented when a pointer hovers over the trigger.
* If `'context-menu'`, the popover will be presented when the trigger is right
* clicked on desktop and long pressed on mobile. This will also prevent your
* device's normal context menu from appearing.
*/
@Prop() triggerAction: TriggerAction = 'click';
/**
* An ID corresponding to the trigger element that
* causes the popover to open. Use the `trigger-action`
* property to customize the interaction that results in
* the popover opening.
*/
@Prop() trigger: string | undefined;
/**
* Describes how to calculate the popover width.
* If `'cover'`, the popover width will match the width of the trigger.
* If `'auto'`, the popover width will be determined by the content in
* the popover.
*/
@Prop() size: PopoverSize = 'auto';
/**
* If `true`, the popover will be automatically
* dismissed when the content has been clicked.
*/
@Prop() dismissOnSelect = false;
/**
* Describes what to position the popover relative to.
* If `'trigger'`, the popover will be positioned relative
* to the trigger button. If passing in an event, this is
* determined via event.target.
* If `'event'`, the popover will be positioned relative
* to the x/y coordinates of the trigger action. If passing
* in an event, this is determined via event.clientX and event.clientY.
*/
@Prop() reference: PositionReference = 'trigger';
/**
* Describes which side of the `reference` point to position
* the popover on. The `'start'` and `'end'` values are RTL-aware,
* and the `'left'` and `'right'` values are not.
*/
@Prop() side: PositionSide = 'bottom';
/**
* Describes how to align the popover content with the `reference` point.
*/
@Prop() alignment: PositionAlign = 'start';
/**
* If `true`, the popover will display an arrow
* that points at the `reference` when running in `ios` mode
* on mobile. Does not apply in `md` mode or on desktop.
*/
@Prop() arrow = true;
/**
* If `true`, the popover will open. If `false`, the popover will close.
* Use this if you need finer grained control over presentation, otherwise
* just use the popoverController or the `trigger` property.
* Note: `isOpen` will not automatically be set back to `false` when
* the popover dismisses. You will need to do that in your code.
*/
@Prop() isOpen = false;
@Watch('trigger')
@Watch('triggerAction')
onTriggerChange() {
this.configureTriggerInteraction();
}
@Watch('isOpen')
onIsOpenChange(newValue: boolean, oldValue: boolean) {
if (newValue === true && oldValue === false) {
this.present();
} else if (newValue === false && oldValue === true) {
this.dismiss();
}
}
/**
* Emitted after the popover has presented.
*/
@Event({ eventName: 'ionPopoverDidPresent' }) didPresent!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
*/
@Event({ eventName: 'ionPopoverWillPresent' }) willPresent!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has presented.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'didPresent' }) didPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
* Shorthand for ionPopoverWillPresent.
*/
@Event({ eventName: 'willPresent' }) willPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'willDismiss' }) willDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
* Shorthand for ionPopoverDidDismiss.
*/
@Event({ eventName: 'didDismiss' }) didDismissShorthand!: EventEmitter<OverlayEventDetail>;
connectedCallback() {
prepareOverlay(this.el);
}
componentWillLoad() {
/**
* If user has custom ID set then we should
* not assign the default incrementing ID.
*/
this.popoverId = (this.el.hasAttribute('id')) ? this.el.getAttribute('id')! : `ion-popover-${this.popoverIndex}`;
this.parentPopover = this.el.closest(`ion-popover:not(#${this.popoverId})`) as HTMLIonPopoverElement | null;
}
componentDidLoad() {
const { parentPopover, isOpen } = this;
/**
* If popover was rendered with isOpen="true"
* then we should open popover immediately.
*/
if (isOpen === true) {
raf(() => this.present());
}
if (parentPopover) {
addEventListener(parentPopover, 'ionPopoverWillDismiss', () => {
this.dismiss(undefined, undefined, false);
});
}
this.configureTriggerInteraction();
}
/**
* When opening a popover from a trigger, we should not be
* modifying the `event` prop from inside the component.
* Additionally, when pressing the "Right" arrow key, we need
* to shift focus to the first descendant in the newly presented
* popover.
*
* @internal
*/
@Method()
async presentFromTrigger(event?: any, focusDescendant = false) {
this.focusDescendantOnPresent = focusDescendant;
await this.present(event);
this.focusDescendantOnPresent = false;
}
/**
* Determines whether or not an overlay
* is being used inline or via a controller/JS
* and returns the correct delegate.
* By default, subsequent calls to getDelegate
* will use a cached version of the delegate.
* This is useful for calling dismiss after
* present so that the correct delegate is given.
*/
private getDelegate(force = false) {
if (this.workingDelegate && !force) {
return {
delegate: this.workingDelegate,
inline: this.inline
}
}
/**
* If using overlay inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps.
* If a developer has presented this component
* via a controller, then we can assume
* the component is already in the
* correct place.
*/
const parentEl = this.el.parentNode as HTMLElement | null;
const inline = this.inline = parentEl !== null && !this.hasController;
const delegate = this.workingDelegate = (inline) ? this.delegate || this.coreDelegate : this.delegate
return { inline, delegate }
}
/**
* Present the popover overlay after it has been created.
* Developers can pass a mouse, touch, or pointer event
* to position the popover relative to where that event
* was dispatched.
*/
@Method()
async present(event?: MouseEvent | TouchEvent | PointerEvent): Promise<void> {
if (this.presented) {
return;
}
/**
* When using an inline popover
* and dismissing a popover it is possible to
* quickly present the popover while it is
* dismissing. We need to await any current
* transition to allow the dismiss to finish
* before presenting again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const data = {
...this.componentProps,
popover: this.el
};
const { inline, delegate } = this.getDelegate(true);
this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);
await deepReady(this.usersElement);
this.configureKeyboardInteraction();
this.configureDismissInteraction();
this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {
event: event || this.event,
size: this.size,
trigger: this.triggerEl,
reference: this.reference,
side: this.side,
align: this.alignment
});
await this.currentTransition;
this.currentTransition = undefined;
/**
* If popover is nested and was
* presented using the "Right" arrow key,
* we need to move focus to the first
* descendant inside of the popover.
*/
if (this.focusDescendantOnPresent) {
focusFirstDescendant(this.el, this.el);
}
}
/**
* Dismiss the popover overlay after it has been presented.
*
* @param data Any data to emit in the dismiss events.
* @param role The role of the element that is dismissing the popover. For example, 'cancel' or 'backdrop'.
* @param dismissParentPopover If `true`, dismissing this popover will also dismiss
* a parent popover if this popover is nested. Defaults to `true`.
*/
@Method()
async dismiss(data?: any, role?: string, dismissParentPopover = true): Promise<boolean> {
/**
* When using an inline popover
* and presenting a popover it is possible to
* quickly dismiss the popover while it is
* presenting. We need to await any current
* transition to allow the present to finish
* before dismissing again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const { destroyKeyboardInteraction, destroyDismissInteraction } = this;
if (dismissParentPopover && this.parentPopover) {
this.parentPopover.dismiss(data, role, dismissParentPopover)
}
this.currentTransition = dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
const shouldDismiss = await this.currentTransition;
if (shouldDismiss) {
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
this.destroyKeyboardInteraction = undefined;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
this.destroyDismissInteraction = undefined;
}
/**
* If using popover inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps
*/
const { delegate } = this.getDelegate();
await detachComponent(delegate, this.usersElement);
}
this.currentTransition = undefined;
return shouldDismiss;
}
/**
* @internal
*/
@Method()
async getParentPopover(): Promise<HTMLIonPopoverElement | null> {
return this.parentPopover;
}
/**
* Returns a promise that resolves when the popover did dismiss.
*/
@Method()
onDidDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverDidDismiss');
}
/**
* Returns a promise that resolves when the popover will dismiss.
*/
@Method()
onWillDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverWillDismiss');
}
private onDismiss = (ev: UIEvent) => {
ev.stopPropagation();
ev.preventDefault();
this.dismiss();
}
private onBackdropTap = () => {
this.dismiss(undefined, BACKDROP);
}
private onLifecycle = (modalEvent: CustomEvent) => {
const el = this.usersElement;
const name = LIFECYCLE_MAP[modalEvent.type];
if (el && name) {
const event = new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: modalEvent.detail
});
el.dispatchEvent(event);
}
}
private configureTriggerInteraction = () => {
const { trigger, triggerAction, el, destroyTriggerInteraction } = this;
if (destroyTriggerInteraction) {
destroyTriggerInteraction();
}
const triggerEl = this.triggerEl = (trigger !== undefined) ? document.getElementById(trigger) : null;
if (!triggerEl) { return; }
this.destroyTriggerInteraction = configureTriggerInteraction(triggerEl, triggerAction, el);
}
private configureKeyboardInteraction = () => {
const { destroyKeyboardInteraction, el } = this;
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
}
this.destroyKeyboardInteraction = configureKeyboardInteraction(el);
}
private configureDismissInteraction = () => {
const { destroyDismissInteraction, parentPopover, triggerAction, triggerEl, el } = this;
if (!parentPopover || !triggerEl) { return; }
if (destroyDismissInteraction) {
destroyDismissInteraction();
}
this.destroyDismissInteraction = configureDismissInteraction(triggerEl, triggerAction, el, parentPopover);
}
render() {
const mode = getIonMode(this);
const { onLifecycle, popoverId, parentPopover, dismissOnSelect, presented, side, arrow, htmlAttributes } = this;
const desktop = isPlatform('desktop');
const enableArrow = arrow && !parentPopover && !desktop;
return (
<Host
aria-modal="true"
no-router
tabindex="-1"
{...htmlAttributes as any}
style={{
zIndex: `${20000 + this.overlayIndex}`,
}}
id={popoverId}
class={{
...getClassMap(this.cssClass),
[mode]: true,
'popover-translucent': this.translucent,
'overlay-hidden': true,
'popover-interactive': presented,
'popover-desktop': desktop,
[`popover-side-${side}`]: true,
'popover-nested': !!parentPopover
}}
onIonPopoverDidPresent={onLifecycle}
onIonPopoverWillPresent={onLifecycle}
onIonPopoverWillDismiss={onLifecycle}
onIonPopoverDidDismiss={onLifecycle}
onIonDismiss={this.onDismiss}
onIonBackdropTap={this.onBackdropTap}
>
{!parentPopover && <ion-backdrop tappable={this.backdropDismiss} visible={this.showBackdrop} part="backdrop" />}
<div
class="popover-wrapper ion-overlay-wrapper"
onClick={dismissOnSelect ? () => this.dismiss() : undefined}
>
{enableArrow && <div class="popover-arrow" part="arrow"></div>}
<div class="popover-content" part="content">
<slot></slot>
</div>
</div>
</Host>
);
}
}
const LIFECYCLE_MAP: any = {
'ionPopoverDidPresent': 'ionViewDidEnter',
'ionPopoverWillPresent': 'ionViewWillEnter',
'ionPopoverWillDismiss': 'ionViewWillLeave',
'ionPopoverDidDismiss': 'ionViewDidLeave',
};
let popoverIds = 0;
| core/src/components/popover/popover.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.9982492923736572,
0.04997125267982483,
0.00015886491746641695,
0.0002596786362119019,
0.21262863278388977
] |
{
"id": 4,
"code_window": [
" const { inline, delegate } = this.getDelegate(true);\n",
" this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);\n",
" await deepReady(this.usersElement);\n",
"\n",
" this.configureKeyboardInteraction();\n",
" this.configureDismissInteraction();\n",
"\n",
" this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {\n",
" event: event || this.event,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this.keyboardEvents) {\n",
" this.configureKeyboardInteraction();\n",
" }\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "replace",
"edit_start_line_idx": 387
} | describe('Nested', () => {
beforeEach(() => {
cy.visit('http://localhost:8080/nested');
cy.ionPageVisible('nestedchild');
});
it('should show first page', () => {
cy.ionPageVisible('nestedchild');
});
it('should go to second page', () => {
cy.get('#nested-child-two').click();
cy.ionPageVisible('nestedchildtwo');
cy.ionPageHidden('nestedchild');
});
it('should go back to first page', () => {
cy.get('#nested-child-two').click();
cy.ionBackClick('nestedchildtwo');
cy.ionPageVisible('nestedchild');
});
it('should go navigate across nested outlet contexts', () => {
cy.ionPageVisible('nestedchild');
cy.get('#nested-tabs').click();
cy.ionPageHidden('routeroutlet');
cy.ionPageVisible('tab1');
cy.ionBackClick('tab1');
cy.ionPageDoesNotExist('tab1');
cy.ionPageVisible('routeroutlet');
});
})
| packages/vue/test-app/tests/e2e/specs/nested.js | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0001757119025569409,
0.0001750432711560279,
0.00017436851339880377,
0.0001750463416101411,
4.7497499622295436e-7
] |
{
"id": 4,
"code_window": [
" const { inline, delegate } = this.getDelegate(true);\n",
" this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);\n",
" await deepReady(this.usersElement);\n",
"\n",
" this.configureKeyboardInteraction();\n",
" this.configureDismissInteraction();\n",
"\n",
" this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {\n",
" event: event || this.event,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this.keyboardEvents) {\n",
" this.configureKeyboardInteraction();\n",
" }\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "replace",
"edit_start_line_idx": 387
} | import { newE2EPage } from '@stencil/core/testing';
test('grid: standalone', async () => {
const page = await newE2EPage({
url: '/src/components/grid/test/standalone?ionic:_testing=true'
});
const compare = await page.compareScreenshot();
expect(compare).toMatchScreenshot();
});
| core/src/components/grid/test/standalone/e2e.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017599073180463165,
0.00017323321662843227,
0.00017047568690031767,
0.00017323321662843227,
0.0000027575224521569908
] |
{
"id": 4,
"code_window": [
" const { inline, delegate } = this.getDelegate(true);\n",
" this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);\n",
" await deepReady(this.usersElement);\n",
"\n",
" this.configureKeyboardInteraction();\n",
" this.configureDismissInteraction();\n",
"\n",
" this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {\n",
" event: event || this.event,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!this.keyboardEvents) {\n",
" this.configureKeyboardInteraction();\n",
" }\n"
],
"file_path": "core/src/components/popover/popover.tsx",
"type": "replace",
"edit_start_line_idx": 387
} | ```html
<template>
<!-- uses "star" icon for both modes -->
<ion-icon :icon="star"></ion-icon>
<!-- explicitly set the icon for each mode -->
<ion-icon :ios="home" :md="star"></ion-icon>
<!-- use a custom svg icon -->
<ion-icon src="/path/to/external/file.svg"></ion-icon>
<!-- set the icon size -->
<ion-icon size="small" :icon="heart"></ion-icon>
<ion-icon size="large" :icon="heart"></ion-icon>
</template>
<script>
import { IonIcon } from '@ionic/vue';
import { heart, home, star } from 'ionicons/icons';
import { defineComponent } from 'vue';
export default defineComponent({
components: { IonIcon },
setup() {
return { heart, home, star }
}
});
</script>
```
| core/src/components/icon/usage/vue.md | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017363220104016364,
0.000169854421983473,
0.0001637252134969458,
0.0001722058077575639,
0.0000043729405660997145
] |
{
"id": 5,
"code_window": [
" /**\n",
" * ArrowDown should move focus to the next focusable ion-item.\n",
" */\n",
" case 'ArrowDown':\n",
" ev.preventDefault();\n",
" const nextItem = getNextItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n",
" if (nextItem !== undefined) {\n",
" focusItem(nextItem);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 374
} | import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, State, Watch, h, writeTask } from '@stencil/core';
import {
caretDownSharp,
caretUpSharp,
chevronBack,
chevronDown,
chevronForward
} from 'ionicons/icons';
import { getIonMode } from '../../global/ionic-global';
import { Color, DatetimeChangeEventDetail, DatetimeParts, Mode, StyleEventDetail } from '../../interface';
import { startFocusVisible } from '../../utils/focus-visible';
import { getElementRoot, renderHiddenInput } from '../../utils/helpers';
import { createColorClasses } from '../../utils/theme';
import { PickerColumnItem } from '../picker-column-internal/picker-column-internal-interfaces';
import {
generateMonths,
generateTime,
getCalendarYears,
getDaysOfMonth,
getDaysOfWeek,
getPickerMonths,
getToday
} from './utils/data';
import {
addTimePadding,
getFormattedHour,
getFormattedTime,
getMonthAndDay,
getMonthAndYear
} from './utils/format';
import {
is24Hour
} from './utils/helpers';
import {
calculateHourFromAMPM,
convertDataToISO,
getEndOfWeek,
getInternalHourValue,
getNextDay,
getNextMonth,
getNextWeek,
getNextYear,
getPreviousDay,
getPreviousMonth,
getPreviousWeek,
getPreviousYear,
getStartOfWeek
} from './utils/manipulation';
import {
convertToArrayOfNumbers,
getPartsFromCalendarDay,
parseDate
} from './utils/parse';
import {
getCalendarDayState,
isDayDisabled
} from './utils/state';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot title - The title of the datetime.
* @slot buttons - The buttons in the datetime.
* @slot time-label - The label for the time selector in the datetime.
*/
@Component({
tag: 'ion-datetime',
styleUrls: {
ios: 'datetime.ios.scss',
md: 'datetime.md.scss'
},
shadow: true
})
export class Datetime implements ComponentInterface {
private inputId = `ion-dt-${datetimeIds++}`;
private calendarBodyRef?: HTMLElement;
private popoverRef?: HTMLIonPopoverElement;
private clearFocusVisible?: () => void;
private overlayIsPresenting = false;
private parsedMinuteValues?: number[];
private parsedHourValues?: number[];
private parsedMonthValues?: number[];
private parsedYearValues?: number[];
private parsedDayValues?: number[];
private destroyCalendarIO?: () => void;
private destroyKeyboardMO?: () => void;
private minParts?: any;
private maxParts?: any;
/**
* Duplicate reference to `activeParts` that does not trigger a re-render of the component.
* Allows caching an instance of the `activeParts` in between render cycles.
*/
private activePartsClone!: DatetimeParts;
@State() showMonthAndYear = false;
@State() activeParts: DatetimeParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm'
}
@State() workingParts: DatetimeParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm'
}
private todayParts = parseDate(getToday())
@Element() el!: HTMLIonDatetimeElement;
@State() isPresented = false;
@State() isTimePopoverOpen = false;
/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
* For more information on colors, see [theming](/docs/theming/basics).
*/
@Prop() color?: Color = 'primary';
/**
* The name of the control, which is submitted with the form data.
*/
@Prop() name: string = this.inputId;
/**
* If `true`, the user cannot interact with the datetime.
*/
@Prop() disabled = false;
/**
* If `true`, the datetime appears normal but is not interactive.
*/
@Prop() readonly = false;
@Watch('disabled')
protected disabledChanged() {
this.emitStyle();
}
/**
* The minimum datetime allowed. Value must be a date string
* following the
* [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
* such as `1996-12-19`. The format does not have to be specific to an exact
* datetime. For example, the minimum could just be the year, such as `1994`.
* Defaults to the beginning of the year, 100 years ago from today.
*/
@Prop({ mutable: true }) min?: string;
@Watch('min')
protected minChanged() {
this.processMinParts();
}
/**
* The maximum datetime allowed. Value must be a date string
* following the
* [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
* `1996-12-19`. The format does not have to be specific to an exact
* datetime. For example, the maximum could just be the year, such as `1994`.
* Defaults to the end of this year.
*/
@Prop({ mutable: true }) max?: string;
@Watch('max')
protected maxChanged() {
this.processMaxParts();
}
/**
* Which values you want to select. `'date'` will show
* a calendar picker to select the month, day, and year. `'time'`
* will show a time picker to select the hour, minute, and (optionally)
* AM/PM. `'date-time'` will show the date picker first and time picker second.
* `'time-date'` will show the time picker first and date picker second.
*/
@Prop() presentation: 'date-time' | 'time-date' | 'date' | 'time' | 'month' | 'year' | 'month-year' = 'date-time';
/**
* The text to display on the picker's cancel button.
*/
@Prop() cancelText = 'Cancel';
/**
* The text to display on the picker's "Done" button.
*/
@Prop() doneText = 'Done';
/**
* The text to display on the picker's "Clear" button.
*/
@Prop() clearText = 'Clear';
/**
* Values used to create the list of selectable years. By default
* the year values range between the `min` and `max` datetime inputs. However, to
* control exactly which years to display, the `yearValues` input can take a number, an array
* of numbers, or string of comma separated numbers. For example, to show upcoming and
* recent leap years, then this input's value would be `yearValues="2024,2020,2016,2012,2008"`.
*/
@Prop() yearValues?: number[] | number | string;
@Watch('yearValues')
protected yearValuesChanged() {
this.parsedYearValues = convertToArrayOfNumbers(this.yearValues);
}
/**
* Values used to create the list of selectable months. By default
* the month values range from `1` to `12`. However, to control exactly which months to
* display, the `monthValues` input can take a number, an array of numbers, or a string of
* comma separated numbers. For example, if only summer months should be shown, then this
* input value would be `monthValues="6,7,8"`. Note that month numbers do *not* have a
* zero-based index, meaning January's value is `1`, and December's is `12`.
*/
@Prop() monthValues?: number[] | number | string;
@Watch('monthValues')
protected monthValuesChanged() {
this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues);
}
/**
* Values used to create the list of selectable days. By default
* every day is shown for the given month. However, to control exactly which days of
* the month to display, the `dayValues` input can take a number, an array of numbers, or
* a string of comma separated numbers. Note that even if the array days have an invalid
* number for the selected month, like `31` in February, it will correctly not show
* days which are not valid for the selected month.
*/
@Prop() dayValues?: number[] | number | string;
@Watch('dayValues')
protected dayValuesChanged() {
this.parsedDayValues = convertToArrayOfNumbers(this.dayValues);
}
/**
* Values used to create the list of selectable hours. By default
* the hour values range from `0` to `23` for 24-hour, or `1` to `12` for 12-hour. However,
* to control exactly which hours to display, the `hourValues` input can take a number, an
* array of numbers, or a string of comma separated numbers.
*/
@Prop() hourValues?: number[] | number | string;
@Watch('hourValues')
protected hourValuesChanged() {
this.parsedHourValues = convertToArrayOfNumbers(this.hourValues);
}
/**
* Values used to create the list of selectable minutes. By default
* the minutes range from `0` to `59`. However, to control exactly which minutes to display,
* the `minuteValues` input can take a number, an array of numbers, or a string of comma
* separated numbers. For example, if the minute selections should only be every 15 minutes,
* then this input value would be `minuteValues="0,15,30,45"`.
*/
@Prop() minuteValues?: number[] | number | string;
@Watch('minuteValues')
protected minuteValuesChanged() {
this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues);
}
/**
* The locale to use for `ion-datetime`. This
* impacts month and day name formatting.
* The `'default'` value refers to the default
* locale set by your device.
*/
@Prop() locale = 'default';
/**
* The first day of the week to use for `ion-datetime`. The
* default value is `0` and represents Sunday.
*/
@Prop() firstDayOfWeek = 0;
/**
* The value of the datetime as a valid ISO 8601 datetime string.
*/
@Prop({ mutable: true }) value?: string | null;
/**
* Update the datetime value when the value changes
*/
@Watch('value')
protected valueChanged() {
if (this.hasValue()) {
/**
* Clones the value of the `activeParts` to the private clone, to update
* the date display on the current render cycle without causing another render.
*
* This allows us to update the current value's date/time display without
* refocusing or shifting the user's display (leaves the user in place).
*/
const { month, day, year, hour, minute } = parseDate(this.value);
this.activePartsClone = {
...this.activeParts,
month,
day,
year,
hour,
minute
}
}
this.emitStyle();
this.ionChange.emit({
value: this.value
});
}
/**
* If `true`, a header will be shown above the calendar
* picker. On `ios` mode this will include the
* slotted title, and on `md` mode this will include
* the slotted title and the selected date.
*/
@Prop() showDefaultTitle = false;
/**
* If `true`, the default "Cancel" and "OK" buttons
* will be rendered at the bottom of the `ion-datetime`
* component. Developers can also use the `button` slot
* if they want to customize these buttons. If custom
* buttons are set in the `button` slot then the
* default buttons will not be rendered.
*/
@Prop() showDefaultButtons = false;
/**
* If `true`, a "Clear" button will be rendered alongside
* the default "Cancel" and "OK" buttons at the bottom of the `ion-datetime`
* component. Developers can also use the `button` slot
* if they want to customize these buttons. If custom
* buttons are set in the `button` slot then the
* default buttons will not be rendered.
*/
@Prop() showClearButton = false;
/**
* If `true`, the default "Time" label will be rendered
* for the time selector of the `ion-datetime` component.
* Developers can also use the `time-label` slot
* if they want to customize this label. If a custom
* label is set in the `time-label` slot then the
* default label will not be rendered.
*/
@Prop() showDefaultTimeLabel = true;
/**
* The hour cycle of the `ion-datetime`. If no value is set, this is
* specified by the current locale.
*/
@Prop() hourCycle?: 'h23' | 'h12';
/**
* If `cover`, the `ion-datetime` will expand to cover the full width of its container.
* If `fixed`, the `ion-datetime` will have a fixed width.
*/
@Prop() size: 'cover' | 'fixed' = 'fixed';
/**
* Emitted when the datetime selection was cancelled.
*/
@Event() ionCancel!: EventEmitter<void>;
/**
* Emitted when the value (selected date) has changed.
*/
@Event() ionChange!: EventEmitter<DatetimeChangeEventDetail>;
/**
* Emitted when the datetime has focus.
*/
@Event() ionFocus!: EventEmitter<void>;
/**
* Emitted when the datetime loses focus.
*/
@Event() ionBlur!: EventEmitter<void>;
/**
* Emitted when the styles change.
* @internal
*/
@Event() ionStyle!: EventEmitter<StyleEventDetail>;
/**
* Confirms the selected datetime value, updates the
* `value` property, and optionally closes the popover
* or modal that the datetime was presented in.
*/
@Method()
async confirm(closeOverlay = false) {
/**
* Prevent convertDataToISO from doing any
* kind of transformation based on timezone
* This cancels out any change it attempts to make
*
* Important: Take the timezone offset based on
* the date that is currently selected, otherwise
* there can be 1 hr difference when dealing w/ DST
*/
const date = new Date(convertDataToISO(this.workingParts));
this.workingParts.tzOffset = date.getTimezoneOffset() * -1;
this.value = convertDataToISO(this.workingParts);
if (closeOverlay) {
this.closeParentOverlay();
}
}
/**
* Resets the internal state of the datetime but does not update the value.
* Passing a valid ISO-8601 string will reset the state of the component to the provided date.
* If no value is provided, the internal state will be reset to today.
*/
@Method()
async reset(startDate?: string) {
this.processValue(startDate);
}
/**
* Emits the ionCancel event and
* optionally closes the popover
* or modal that the datetime was
* presented in.
*/
@Method()
async cancel(closeOverlay = false) {
this.ionCancel.emit();
if (closeOverlay) {
this.closeParentOverlay();
}
}
private closeParentOverlay = () => {
const popoverOrModal = this.el.closest('ion-modal, ion-popover') as HTMLIonModalElement | HTMLIonPopoverElement | null;
if (popoverOrModal) {
popoverOrModal.dismiss();
}
}
private setWorkingParts = (parts: DatetimeParts) => {
this.workingParts = {
...parts
}
}
private setActiveParts = (parts: DatetimeParts) => {
this.activeParts = {
...parts
}
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (hasSlottedButtons || this.showDefaultButtons) { return; }
this.confirm();
}
private initializeKeyboardListeners = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const root = this.el!.shadowRoot!;
/**
* Get a reference to the month
* element we are currently viewing.
*/
const currentMonth = calendarBodyRef.querySelector('.calendar-month:nth-of-type(2)')!;
/**
* When focusing the calendar body, we want to pass focus
* to the working day, but other days should
* only be accessible using the arrow keys. Pressing
* Tab should jump between bodies of selectable content.
*/
const checkCalendarBodyFocus = (ev: MutationRecord[]) => {
const record = ev[0];
/**
* If calendar body was already focused
* when this fired or if the calendar body
* if not currently focused, we should not re-focus
* the inner day.
*/
if (
record.oldValue?.includes('ion-focused') ||
!calendarBodyRef.classList.contains('ion-focused')
) {
return;
}
this.focusWorkingDay(currentMonth);
}
const mo = new MutationObserver(checkCalendarBodyFocus);
mo.observe(calendarBodyRef, { attributeFilter: ['class'], attributeOldValue: true });
this.destroyKeyboardMO = () => {
mo?.disconnect();
}
/**
* We must use keydown not keyup as we want
* to prevent scrolling when using the arrow keys.
*/
this.calendarBodyRef!.addEventListener('keydown', (ev: KeyboardEvent) => {
const activeElement = root.activeElement;
if (!activeElement || !activeElement.classList.contains('calendar-day')) { return; }
const parts = getPartsFromCalendarDay(activeElement as HTMLElement)
let partsToFocus: DatetimeParts | undefined;
switch (ev.key) {
case 'ArrowDown':
ev.preventDefault();
partsToFocus = getNextWeek(parts);
break;
case 'ArrowUp':
ev.preventDefault();
partsToFocus = getPreviousWeek(parts);
break;
case 'ArrowRight':
ev.preventDefault();
partsToFocus = getNextDay(parts);
break;
case 'ArrowLeft':
ev.preventDefault();
partsToFocus = getPreviousDay(parts);
break;
case 'Home':
ev.preventDefault();
partsToFocus = getStartOfWeek(parts);
break;
case 'End':
ev.preventDefault();
partsToFocus = getEndOfWeek(parts);
break;
case 'PageUp':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getPreviousYear(parts) : getPreviousMonth(parts);
break;
case 'PageDown':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getNextYear(parts) : getNextMonth(parts);
break;
/**
* Do not preventDefault here
* as we do not want to override other
* browser defaults such as pressing Enter/Space
* to select a day.
*/
default:
return;
}
/**
* If the day we want to move focus to is
* disabled, do not do anything.
*/
if (isDayDisabled(partsToFocus, this.minParts, this.maxParts)) {
return;
}
this.setWorkingParts({
...this.workingParts,
...partsToFocus
})
/**
* Give view a chance to re-render
* then move focus to the new working day
*/
requestAnimationFrame(() => this.focusWorkingDay(currentMonth));
})
}
private focusWorkingDay = (currentMonth: Element) => {
/**
* Get the number of padding days so
* we know how much to offset our next selector by
* to grab the correct calenday-day element.
*/
const padding = currentMonth.querySelectorAll('.calendar-day-padding');
const { day } = this.workingParts;
if (day === null) { return; }
/**
* Get the calendar day element
* and focus it.
*/
const dayEl = currentMonth.querySelector(`.calendar-day:nth-of-type(${padding.length + day})`) as HTMLElement | null;
if (dayEl) {
dayEl.focus();
}
}
private processMinParts = () => {
if (this.min === undefined) {
this.minParts = undefined;
return;
}
const { month, day, year, hour, minute } = parseDate(this.min);
this.minParts = {
month,
day,
year,
hour,
minute
}
}
private processMaxParts = () => {
if (this.max === undefined) {
this.maxParts = undefined;
return;
}
const { month, day, year, hour, minute } = parseDate(this.max);
this.maxParts = {
month,
day,
year,
hour,
minute
}
}
private initializeCalendarIOListeners = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const mode = getIonMode(this);
/**
* For performance reasons, we only render 3
* months at a time: The current month, the previous
* month, and the next month. We have IntersectionObservers
* on the previous and next month elements to append/prepend
* new months.
*
* We can do this because Stencil is smart enough to not
* re-create the .calendar-month containers, but rather
* update the content within those containers.
*
* As an added bonus, WebKit has some troubles with
* scroll-snap-stop: always, so not rendering all of
* the months in a row allows us to mostly sidestep
* that issue.
*/
const months = calendarBodyRef.querySelectorAll('.calendar-month');
const startMonth = months[0] as HTMLElement;
const workingMonth = months[1] as HTMLElement;
const endMonth = months[2] as HTMLElement;
/**
* Before setting up the IntersectionObserver,
* scroll the middle month into view.
* scrollIntoView() will scroll entire page
* if element is not in viewport. Use scrollLeft instead.
*/
writeTask(() => {
calendarBodyRef.scrollLeft = startMonth.clientWidth;
let endIO: IntersectionObserver | undefined;
let startIO: IntersectionObserver | undefined;
const ioCallback = (callbackType: 'start' | 'end', entries: IntersectionObserverEntry[]) => {
const refIO = (callbackType === 'start') ? startIO : endIO;
const refMonth = (callbackType === 'start') ? startMonth : endMonth;
const refMonthFn = (callbackType === 'start') ? getPreviousMonth : getNextMonth;
/**
* If the month is not fully in view, do not do anything
*/
const ev = entries[0];
if (!ev.isIntersecting) { return; }
/**
* When presenting an inline overlay,
* subsequent presentations will cause
* the IO to fire again (since the overlay
* is now visible and therefore the calendar
* months are intersecting).
*/
if (this.overlayIsPresenting) {
this.overlayIsPresenting = false;
return;
}
/**
* On iOS, we need to set pointer-events: none
* when the user is almost done with the gesture
* so that they cannot quickly swipe while
* the scrollable container is snapping.
* Updating the container while snapping
* causes WebKit to snap incorrectly.
*/
if (mode === 'ios') {
const ratio = ev.intersectionRatio;
const shouldDisable = Math.abs(ratio - 0.7) <= 0.1;
if (shouldDisable) {
calendarBodyRef.style.setProperty('pointer-events', 'none');
return;
}
}
/**
* Prevent scrolling for other browsers
* to give the DOM time to update and the container
* time to properly snap.
*/
calendarBodyRef.style.setProperty('overflow', 'hidden');
/**
* Remove the IO temporarily
* otherwise you can sometimes get duplicate
* events when rubber banding.
*/
if (refIO === undefined) { return; }
refIO.disconnect();
/**
* Use a writeTask here to ensure
* that the state is updated and the
* correct month is scrolled into view
* in the same frame. This is not
* typically a problem on newer devices
* but older/slower device may have a flicker
* if we did not do this.
*/
writeTask(() => {
const { month, year, day } = refMonthFn(this.workingParts);
this.setWorkingParts({
...this.workingParts,
month,
day: day!,
year
});
calendarBodyRef.scrollLeft = workingMonth.clientWidth;
calendarBodyRef.style.removeProperty('overflow');
calendarBodyRef.style.removeProperty('pointer-events');
/**
* Now that state has been updated
* and the correct month is in view,
* we can resume the IO.
*/
// tslint:disable-next-line
if (refIO === undefined) { return; }
refIO.observe(refMonth);
});
}
/**
* Listen on the first month to
* prepend a new month and on the last
* month to append a new month.
* The 0.7 threshold is required on ios
* so that we can remove pointer-events
* when adding new months.
* Adding to a scroll snapping container
* while the container is snapping does not
* completely work as expected in WebKit.
* Adding pointer-events: none allows us to
* avoid these issues.
*
* This should be fine on Chromium, but
* when you set pointer-events: none
* it applies to active gestures which is not
* something WebKit does.
*/
endIO = new IntersectionObserver(ev => ioCallback('end', ev), {
threshold: mode === 'ios' ? [0.7, 1] : 1,
root: calendarBodyRef
});
endIO.observe(endMonth);
startIO = new IntersectionObserver(ev => ioCallback('start', ev), {
threshold: mode === 'ios' ? [0.7, 1] : 1,
root: calendarBodyRef
});
startIO.observe(startMonth);
this.destroyCalendarIO = () => {
endIO?.disconnect();
startIO?.disconnect();
}
});
}
connectedCallback() {
this.clearFocusVisible = startFocusVisible(this.el).destroy;
}
disconnectedCallback() {
if (this.clearFocusVisible) {
this.clearFocusVisible();
this.clearFocusVisible = undefined;
}
}
/**
* Clean up all listeners except for the overlay
* listener. This is so that we can re-create the listeners
* if the datetime has been hidden/presented by a modal or popover.
*/
private destroyListeners = () => {
const { destroyCalendarIO, destroyKeyboardMO } = this;
if (destroyCalendarIO !== undefined) {
destroyCalendarIO();
}
if (destroyKeyboardMO !== undefined) {
destroyKeyboardMO();
}
}
componentDidLoad() {
/**
* If a scrollable element is hidden using `display: none`,
* it will not have a scroll height meaning we cannot scroll elements
* into view. As a result, we will need to wait for the datetime to become
* visible if used inside of a modal or a popover otherwise the scrollable
* areas will not have the correct values snapped into place.
*/
let visibleIO: IntersectionObserver | undefined;
const visibleCallback = (entries: IntersectionObserverEntry[]) => {
const ev = entries[0];
if (!ev.isIntersecting) { return; }
this.initializeCalendarIOListeners();
this.initializeKeyboardListeners();
this.initializeOverlayListener();
/**
* TODO: Datetime needs a frame to ensure that it
* can properly scroll contents into view. As a result
* we hide the scrollable content until after that frame
* so users do not see the content quickly shifting. The downside
* is that the content will pop into view a frame after. Maybe there
* is a better way to handle this?
*/
writeTask(() => {
this.el.classList.add('datetime-ready');
});
}
visibleIO = new IntersectionObserver(visibleCallback, { threshold: 0.01 });
visibleIO.observe(this.el);
/**
* We need to clean up listeners when the datetime is hidden
* in a popover/modal so that we can properly scroll containers
* back into view if they are re-presented. When the datetime is hidden
* the scroll areas have scroll widths/heights of 0px, so any snapping
* we did originally has been lost.
*/
let hiddenIO: IntersectionObserver | undefined;
const hiddenCallback = (entries: IntersectionObserverEntry[]) => {
const ev = entries[0];
if (ev.isIntersecting) { return; }
this.destroyListeners();
writeTask(() => {
this.el.classList.remove('datetime-ready');
});
}
hiddenIO = new IntersectionObserver(hiddenCallback, { threshold: 0 });
hiddenIO.observe(this.el);
/**
* Datetime uses Ionic components that emit
* ionFocus and ionBlur. These events are
* composed meaning they will cross
* the shadow dom boundary. We need to
* stop propagation on these events otherwise
* developers will see 2 ionFocus or 2 ionBlur
* events at a time.
*/
const root = getElementRoot(this.el);
root.addEventListener('ionFocus', (ev: Event) => ev.stopPropagation());
root.addEventListener('ionBlur', (ev: Event) => ev.stopPropagation());
}
/**
* When doing subsequent presentations of an inline
* overlay, the IO callback will fire again causing
* the calendar to go back one month. We need to listen
* for the presentation of the overlay so we can properly
* cancel that IO callback.
*/
private initializeOverlayListener = () => {
const overlay = this.el.closest('ion-popover, ion-modal');
if (overlay === null) { return; }
overlay.addEventListener('willPresent', () => {
this.overlayIsPresenting = true;
});
}
private processValue = (value?: string | null) => {
const valueToProcess = value || getToday();
const { month, day, year, hour, minute, tzOffset } = parseDate(valueToProcess);
this.workingParts = {
month,
day,
year,
hour,
minute,
tzOffset,
ampm: hour >= 12 ? 'pm' : 'am'
}
this.activePartsClone = this.activeParts = {
month,
day,
year,
hour,
minute,
tzOffset,
ampm: hour >= 12 ? 'pm' : 'am'
}
}
componentWillLoad() {
this.processValue(this.value);
this.processMinParts();
this.processMaxParts();
this.parsedHourValues = convertToArrayOfNumbers(this.hourValues);
this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues);
this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues);
this.parsedYearValues = convertToArrayOfNumbers(this.yearValues);
this.parsedDayValues = convertToArrayOfNumbers(this.dayValues);
this.emitStyle();
}
private emitStyle() {
this.ionStyle.emit({
'interactive': true,
'datetime': true,
'interactive-disabled': this.disabled,
});
}
private onFocus = () => {
this.ionFocus.emit();
}
private onBlur = () => {
this.ionBlur.emit();
}
private hasValue = () => {
return this.value != null && this.value !== '';
}
private nextMonth = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const nextMonth = calendarBodyRef.querySelector('.calendar-month:last-of-type');
if (!nextMonth) { return; }
calendarBodyRef.scrollTo({
top: 0,
left: (nextMonth as HTMLElement).offsetWidth * 2,
behavior: 'smooth'
});
}
private prevMonth = () => {
const { calendarBodyRef } = this;
if (!calendarBodyRef) { return; }
const prevMonth = calendarBodyRef.querySelector('.calendar-month:first-of-type');
if (!prevMonth) { return; }
calendarBodyRef.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
});
}
private renderFooter() {
const { showDefaultButtons, showClearButton } = this;
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (!hasSlottedButtons && !showDefaultButtons && !showClearButton) { return; }
const clearButtonClick = () => {
this.reset();
this.value = undefined;
}
/**
* By default we render two buttons:
* Cancel - Dismisses the datetime and
* does not update the `value` prop.
* OK - Dismisses the datetime and
* updates the `value` prop.
*/
return (
<div class="datetime-footer">
<div class="datetime-buttons">
<div class={{
['datetime-action-buttons']: true,
['has-clear-button']: this.showClearButton
}}>
<slot name="buttons">
<ion-buttons>
{showDefaultButtons && <ion-button id="cancel-button" color={this.color} onClick={() => this.cancel(true)}>{this.cancelText}</ion-button>}
<div>
{showClearButton && <ion-button id="clear-button" color={this.color} onClick={() => clearButtonClick()}>{this.clearText}</ion-button>}
{showDefaultButtons && <ion-button id="confirm-button" color={this.color} onClick={() => this.confirm(true)}>{this.doneText}</ion-button>}
</div>
</ion-buttons>
</slot>
</div>
</div>
</div>
);
}
private toggleMonthAndYearView = () => {
this.showMonthAndYear = !this.showMonthAndYear;
}
private renderYearView() {
const { presentation, workingParts } = this;
const calendarYears = getCalendarYears(this.todayParts, this.minParts, this.maxParts, this.parsedYearValues);
const showMonth = presentation !== 'year';
const showYear = presentation !== 'month';
const months = getPickerMonths(this.locale, workingParts, this.minParts, this.maxParts, this.parsedMonthValues);
const years = calendarYears.map(year => {
return {
text: `${year}`,
value: year
}
})
return (
<div class="datetime-year">
<div class="datetime-year-body">
<ion-picker-internal>
{
showMonth &&
<ion-picker-column-internal
color={this.color}
items={months}
value={workingParts.month}
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...this.workingParts,
month: ev.detail.value
});
if (presentation === 'month' || presentation === 'month-year') {
this.setActiveParts({
...this.activeParts,
month: ev.detail.value
});
}
ev.stopPropagation();
}}
></ion-picker-column-internal>
}
{
showYear &&
<ion-picker-column-internal
color={this.color}
items={years}
value={workingParts.year}
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...this.workingParts,
year: ev.detail.value
});
if (presentation === 'year' || presentation === 'month-year') {
this.setActiveParts({
...this.activeParts,
year: ev.detail.value
});
}
ev.stopPropagation();
}}
></ion-picker-column-internal>
}
</ion-picker-internal>
</div>
</div>
);
}
private renderCalendarHeader(mode: Mode) {
const expandedIcon = mode === 'ios' ? chevronDown : caretUpSharp;
const collapsedIcon = mode === 'ios' ? chevronForward : caretDownSharp;
return (
<div class="calendar-header">
<div class="calendar-action-buttons">
<div class="calendar-month-year">
<ion-item button detail={false} lines="none" onClick={() => this.toggleMonthAndYearView()}>
<ion-label>
{getMonthAndYear(this.locale, this.workingParts)} <ion-icon icon={this.showMonthAndYear ? expandedIcon : collapsedIcon} lazy={false}></ion-icon>
</ion-label>
</ion-item>
</div>
<div class="calendar-next-prev">
<ion-buttons>
<ion-button onClick={() => this.prevMonth()}>
<ion-icon slot="icon-only" icon={chevronBack} lazy={false}></ion-icon>
</ion-button>
<ion-button onClick={() => this.nextMonth()}>
<ion-icon slot="icon-only" icon={chevronForward} lazy={false}></ion-icon>
</ion-button>
</ion-buttons>
</div>
</div>
<div class="calendar-days-of-week">
{getDaysOfWeek(this.locale, mode, this.firstDayOfWeek % 7).map(d => {
return <div class="day-of-week">{d}</div>
})}
</div>
</div>
)
}
private renderMonth(month: number, year: number) {
const yearAllowed = this.parsedYearValues === undefined || this.parsedYearValues.includes(year);
const monthAllowed = this.parsedMonthValues === undefined || this.parsedMonthValues.includes(month);
const isMonthDisabled = !yearAllowed || !monthAllowed;
return (
<div class="calendar-month">
<div class="calendar-month-grid">
{getDaysOfMonth(month, year, this.firstDayOfWeek % 7).map((dateObject, index) => {
const { day, dayOfWeek } = dateObject;
const referenceParts = { month, day, year };
const { isActive, isToday, ariaLabel, ariaSelected, disabled } = getCalendarDayState(this.locale, referenceParts, this.activePartsClone, this.todayParts, this.minParts, this.maxParts, this.parsedDayValues);
return (
<button
tabindex="-1"
data-day={day}
data-month={month}
data-year={year}
data-index={index}
data-day-of-week={dayOfWeek}
disabled={isMonthDisabled || disabled}
class={{
'calendar-day-padding': day === null,
'calendar-day': true,
'calendar-day-active': isActive,
'calendar-day-today': isToday
}}
aria-selected={ariaSelected}
aria-label={ariaLabel}
onClick={() => {
if (day === null) { return; }
this.setWorkingParts({
...this.workingParts,
month,
day,
year
});
this.setActiveParts({
...this.activeParts,
month,
day,
year
})
}}
>{day}</button>
)
})}
</div>
</div>
)
}
private renderCalendarBody() {
return (
<div class="calendar-body ion-focusable" ref={el => this.calendarBodyRef = el} tabindex="0">
{generateMonths(this.workingParts).map(({ month, year }) => {
return this.renderMonth(month, year);
})}
</div>
)
}
private renderCalendar(mode: Mode) {
return (
<div class="datetime-calendar">
{this.renderCalendarHeader(mode)}
{this.renderCalendarBody()}
</div>
)
}
private renderTimeLabel() {
const hasSlottedTimeLabel = this.el.querySelector('[slot="time-label"]') !== null;
if (!hasSlottedTimeLabel && !this.showDefaultTimeLabel) { return; }
return (
<slot name="time-label">Time</slot>
);
}
private renderTimePicker(
hoursItems: PickerColumnItem[],
minutesItems: PickerColumnItem[],
ampmItems: PickerColumnItem[],
use24Hour: boolean
) {
const { color, activePartsClone, workingParts } = this;
return (
<ion-picker-internal>
<ion-picker-column-internal
color={color}
value={activePartsClone.hour}
items={hoursItems}
numericInput
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...workingParts,
hour: ev.detail.value
});
this.setActiveParts({
...activePartsClone,
hour: ev.detail.value
});
ev.stopPropagation();
}}
></ion-picker-column-internal>
<ion-picker-column-internal
color={color}
value={activePartsClone.minute}
items={minutesItems}
numericInput
onIonChange={(ev: CustomEvent) => {
this.setWorkingParts({
...workingParts,
minute: ev.detail.value
});
this.setActiveParts({
...activePartsClone,
minute: ev.detail.value
});
ev.stopPropagation();
}}
></ion-picker-column-internal>
{ !use24Hour && <ion-picker-column-internal
color={color}
value={activePartsClone.ampm}
items={ampmItems}
onIonChange={(ev: CustomEvent) => {
const hour = calculateHourFromAMPM(workingParts, ev.detail.value);
this.setWorkingParts({
...workingParts,
ampm: ev.detail.value,
hour
});
this.setActiveParts({
...activePartsClone,
ampm: ev.detail.value,
hour
});
ev.stopPropagation();
}}
></ion-picker-column-internal> }
</ion-picker-internal>
)
}
private renderTimeOverlay(
hoursItems: PickerColumnItem[],
minutesItems: PickerColumnItem[],
ampmItems: PickerColumnItem[],
use24Hour: boolean
) {
return [
<div class="time-header">
{this.renderTimeLabel()}
</div>,
<button
class={{
'time-body': true,
'time-body-active': this.isTimePopoverOpen
}}
aria-expanded="false"
aria-haspopup="true"
onClick={async ev => {
const { popoverRef } = this;
if (popoverRef) {
this.isTimePopoverOpen = true;
popoverRef.present(ev);
await popoverRef.onWillDismiss();
this.isTimePopoverOpen = false;
}
}}
>
{getFormattedTime(this.activePartsClone, use24Hour)}
</button>,
<ion-popover
alignment="center"
translucent
overlayIndex={1}
arrow={false}
style={{
'--offset-y': '-10px'
}}
ref={el => this.popoverRef = el}
>
{this.renderTimePicker(hoursItems, minutesItems, ampmItems, use24Hour)}
</ion-popover>
]
}
/**
* Render time picker inside of datetime.
* Do not pass color prop to segment on
* iOS mode. MD segment has been customized and
* should take on the color prop, but iOS
* should just be the default segment.
*/
private renderTime() {
const { workingParts, presentation } = this;
const timeOnlyPresentation = presentation === 'time';
const use24Hour = is24Hour(this.locale, this.hourCycle);
const { hours, minutes, am, pm } = generateTime(this.workingParts, use24Hour ? 'h23' : 'h12', this.minParts, this.maxParts, this.parsedHourValues, this.parsedMinuteValues);
const hoursItems = hours.map(hour => {
return {
text: getFormattedHour(hour, use24Hour),
value: getInternalHourValue(hour, use24Hour, workingParts.ampm)
}
});
const minutesItems = minutes.map(minute => {
return {
text: addTimePadding(minute),
value: minute
}
});
const ampmItems = [];
if (am) {
ampmItems.push({
text: 'AM',
value: 'am'
})
}
if (pm) {
ampmItems.push({
text: 'PM',
value: 'pm'
})
}
return (
<div class="datetime-time">
{timeOnlyPresentation ? this.renderTimePicker(hoursItems, minutesItems, ampmItems, use24Hour) : this.renderTimeOverlay(hoursItems, minutesItems, ampmItems, use24Hour)}
</div>
)
}
private renderCalendarViewHeader(mode: Mode) {
const hasSlottedTitle = this.el.querySelector('[slot="title"]') !== null;
if (!hasSlottedTitle && !this.showDefaultTitle) { return; }
return (
<div class="datetime-header">
<div class="datetime-title">
<slot name="title">Select Date</slot>
</div>
{mode === 'md' && <div class="datetime-selected-date">
{getMonthAndDay(this.locale, this.activeParts)}
</div>}
</div>
);
}
private renderDatetime(mode: Mode) {
const { presentation } = this;
switch (presentation) {
case 'date-time':
return [
this.renderCalendarViewHeader(mode),
this.renderCalendar(mode),
this.renderYearView(),
this.renderTime(),
this.renderFooter()
]
case 'time-date':
return [
this.renderCalendarViewHeader(mode),
this.renderTime(),
this.renderCalendar(mode),
this.renderYearView(),
this.renderFooter()
]
case 'time':
return [
this.renderTime(),
this.renderFooter()
]
case 'month':
case 'month-year':
case 'year':
return [
this.renderYearView(),
this.renderFooter()
]
default:
return [
this.renderCalendarViewHeader(mode),
this.renderCalendar(mode),
this.renderYearView(),
this.renderFooter()
]
}
}
render() {
const { name, value, disabled, el, color, isPresented, readonly, showMonthAndYear, presentation, size } = this;
const mode = getIonMode(this);
const isMonthAndYearPresentation = presentation === 'year' || presentation === 'month' || presentation === 'month-year';
const shouldShowMonthAndYear = showMonthAndYear || isMonthAndYearPresentation;
renderHiddenInput(true, el, name, value, disabled);
return (
<Host
aria-disabled={disabled ? 'true' : null}
onFocus={this.onFocus}
onBlur={this.onBlur}
class={{
...createColorClasses(color, {
[mode]: true,
['datetime-presented']: isPresented,
['datetime-readonly']: readonly,
['datetime-disabled']: disabled,
'show-month-and-year': shouldShowMonthAndYear,
[`datetime-presentation-${presentation}`]: true,
[`datetime-size-${size}`]: true
})
}}
>
{this.renderDatetime(mode)}
</Host>
);
}
}
let datetimeIds = 0;
| core/src/components/datetime/datetime.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.9837391972541809,
0.0071791778318583965,
0.00016133660392370075,
0.0001710974465822801,
0.08009836822748184
] |
{
"id": 5,
"code_window": [
" /**\n",
" * ArrowDown should move focus to the next focusable ion-item.\n",
" */\n",
" case 'ArrowDown':\n",
" ev.preventDefault();\n",
" const nextItem = getNextItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n",
" if (nextItem !== undefined) {\n",
" focusItem(nextItem);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 374
} | # ion-alert
An Alert is a dialog that presents users with information or collects information from the user using inputs. An alert appears on top of the app's content, and must be manually dismissed by the user before they can resume interaction with the app. It can also optionally have a `header`, `subHeader` and `message`.
## Buttons
In the array of `buttons`, each button includes properties for its `text`, and optionally a `handler`. If a handler returns `false` then the alert will not automatically be dismissed when the button is clicked. All buttons will show up in the order they have been added to the `buttons` array from left to right. Note: The right most button (the last one in the array) is the main button.
Optionally, a `role` property can be added to a button, such as `cancel`. If a `cancel` role is on one of the buttons, then if the alert is dismissed by tapping the backdrop, then it will fire the handler from the button with a cancel role.
## Inputs
Alerts can also include several different inputs whose data can be passed back to the app. Inputs can be used as a simple way to prompt users for information. Radios, checkboxes and text inputs are all accepted, but they cannot be mixed. For example, an alert could have all radio button inputs, or all checkbox inputs, but the same alert cannot mix radio and checkbox inputs. Do note however, different types of "text" inputs can be mixed, such as `url`, `email`, `text`, `textarea` etc. If you require a complex form UI which doesn't fit within the guidelines of an alert then we recommend building the form within a modal instead.
## Customization
Alert uses scoped encapsulation, which means it will automatically scope its CSS by appending each of the styles with an additional class at runtime. Overriding scoped selectors in CSS requires a [higher specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) selector.
We recommend passing a custom class to `cssClass` in the `create` method and using that to add custom styles to the host and inner elements. This property can also accept multiple classes separated by spaces. View the [Usage](#usage) section for an example of how to pass a class using `cssClass`.
```css
/* DOES NOT WORK - not specific enough */
.alert-wrapper {
background: #e5e5e5;
}
/* Works - pass "my-custom-class" in cssClass to increase specificity */
.my-custom-class .alert-wrapper {
background: #e5e5e5;
}
```
Any of the defined [CSS Custom Properties](#css-custom-properties) can be used to style the Alert without needing to target individual elements:
```css
.my-custom-class {
--background: #e5e5e5;
}
```
> If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information.
## Interfaces
### AlertButton
```typescript
interface AlertButton {
text: string;
role?: 'cancel' | 'destructive' | string;
cssClass?: string | string[];
handler?: (value: any) => boolean | void | {[key: string]: any};
}
```
### AlertInput
```typescript
interface AlertInput {
type?: TextFieldTypes | 'checkbox' | 'radio' | 'textarea';
name?: string;
placeholder?: string;
value?: any;
label?: string;
checked?: boolean;
disabled?: boolean;
id?: string;
handler?: (input: AlertInput) => void;
min?: string | number;
max?: string | number;
cssClass?: string | string[];
attributes?: AlertInputAttributes | AlertTextareaAttributes;
tabindex?: number;
}
```
### AlertInputAttributes
```typescript
interface AlertInputAttributes extends JSXBase.InputHTMLAttributes<HTMLInputElement> {}
```
### AlertOptions
```typescript
interface AlertOptions {
header?: string;
subHeader?: string;
message?: string | IonicSafeString;
cssClass?: string | string[];
inputs?: AlertInput[];
buttons?: (AlertButton | string)[];
backdropDismiss?: boolean;
translucent?: boolean;
animated?: boolean;
htmlAttributes?: AlertAttributes;
mode?: Mode;
keyboardClose?: boolean;
id?: string;
enterAnimation?: AnimationBuilder;
leaveAnimation?: AnimationBuilder;
}
```
### AlertAttributes
```typescript
interface AlertAttributes extends JSXBase.HTMLAttributes<HTMLElement> {}
```
### AlertTextareaAttributes
```typescript
interface AlertTextareaAttributes extends JSXBase.TextareaHTMLAttributes<HTMLTextAreaElement> {}
```
<!-- Auto Generated Below -->
## Usage
### Angular
```typescript
import { Component } from '@angular/core';
import { AlertController } from '@ionic/angular';
@Component({
selector: 'alert-example',
templateUrl: 'alert-example.html',
styleUrls: ['./alert-example.css'],
})
export class AlertExample {
constructor(public alertController: AlertController) {}
async presentAlert() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Alert',
subHeader: 'Subtitle',
message: 'This is an alert message.',
buttons: ['OK']
});
await alert.present();
const { role } = await alert.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
}
async presentAlertMultipleButtons() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Alert',
subHeader: 'Subtitle',
message: 'This is an alert message.',
buttons: ['Cancel', 'Open Modal', 'Delete']
});
await alert.present();
}
async presentAlertConfirm() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Confirm!',
message: 'Message <strong>text</strong>!!!',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
id: 'cancel-button',
handler: (blah) => {
console.log('Confirm Cancel: blah');
}
}, {
text: 'Okay',
id: 'confirm-button',
handler: () => {
console.log('Confirm Okay');
}
}
]
});
await alert.present();
}
async presentAlertPrompt() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Prompt!',
inputs: [
{
name: 'name1',
type: 'text',
placeholder: 'Placeholder 1'
},
{
name: 'name2',
type: 'text',
id: 'name2-id',
value: 'hello',
placeholder: 'Placeholder 2'
},
// multiline input.
{
name: 'paragraph',
id: 'paragraph',
type: 'textarea',
placeholder: 'Placeholder 3'
},
{
name: 'name3',
value: 'http://ionicframework.com',
type: 'url',
placeholder: 'Favorite site ever'
},
// input date with min & max
{
name: 'name4',
type: 'date',
min: '2017-03-01',
max: '2018-01-12'
},
// input date without min nor max
{
name: 'name5',
type: 'date'
},
{
name: 'name6',
type: 'number',
min: -5,
max: 10
},
{
name: 'name7',
type: 'number'
},
{
name: 'name8',
type: 'password',
placeholder: 'Advanced Attributes',
cssClass: 'specialClass',
attributes: {
maxlength: 4,
inputmode: 'decimal'
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
async presentAlertRadio() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Radio',
inputs: [
{
name: 'radio1',
type: 'radio',
label: 'Radio 1',
value: 'value1',
handler: () => {
console.log('Radio 1 selected');
},
checked: true
},
{
name: 'radio2',
type: 'radio',
label: 'Radio 2',
value: 'value2',
handler: () => {
console.log('Radio 2 selected');
}
},
{
name: 'radio3',
type: 'radio',
label: 'Radio 3',
value: 'value3',
handler: () => {
console.log('Radio 3 selected');
}
},
{
name: 'radio4',
type: 'radio',
label: 'Radio 4',
value: 'value4',
handler: () => {
console.log('Radio 4 selected');
}
},
{
name: 'radio5',
type: 'radio',
label: 'Radio 5',
value: 'value5',
handler: () => {
console.log('Radio 5 selected');
}
},
{
name: 'radio6',
type: 'radio',
label: 'Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 ',
value: 'value6',
handler: () => {
console.log('Radio 6 selected');
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
async presentAlertCheckbox() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Checkbox',
inputs: [
{
name: 'checkbox1',
type: 'checkbox',
label: 'Checkbox 1',
value: 'value1',
handler: () => {
console.log('Checkbox 1 selected');
},
checked: true
},
{
name: 'checkbox2',
type: 'checkbox',
label: 'Checkbox 2',
value: 'value2',
handler: () => {
console.log('Checkbox 2 selected');
}
},
{
name: 'checkbox3',
type: 'checkbox',
label: 'Checkbox 3',
value: 'value3',
handler: () => {
console.log('Checkbox 3 selected');
}
},
{
name: 'checkbox4',
type: 'checkbox',
label: 'Checkbox 4',
value: 'value4',
handler: () => {
console.log('Checkbox 4 selected');
}
},
{
name: 'checkbox5',
type: 'checkbox',
label: 'Checkbox 5',
value: 'value5',
handler: () => {
console.log('Checkbox 5 selected');
}
},
{
name: 'checkbox6',
type: 'checkbox',
label: 'Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6',
value: 'value6',
handler: () => {
console.log('Checkbox 6 selected');
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
}
```
### Style Placement
In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Alert can be presented from within a page, the `ion-alert` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config).
### Javascript
```javascript
function presentAlert() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Alert';
alert.subHeader = 'Subtitle';
alert.message = 'This is an alert message.';
alert.buttons = ['OK'];
document.body.appendChild(alert);
await alert.present();
const { role } = await alert.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
}
function presentAlertMultipleButtons() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Alert';
alert.subHeader = 'Subtitle';
alert.message = 'This is an alert message.';
alert.buttons = ['Cancel', 'Open Modal', 'Delete'];
document.body.appendChild(alert);
return alert.present();
}
function presentAlertConfirm() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Confirm!';
alert.message = 'Message <strong>text</strong>!!!';
alert.buttons = [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
id: 'cancel-button',
handler: (blah) => {
console.log('Confirm Cancel: blah');
}
}, {
text: 'Okay',
id: 'confirm-button',
handler: () => {
console.log('Confirm Okay')
}
}
];
document.body.appendChild(alert);
return alert.present();
}
function presentAlertPrompt() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Prompt!';
alert.inputs = [
{
placeholder: 'Placeholder 1'
},
{
name: 'name2',
id: 'name2-id',
value: 'hello',
placeholder: 'Placeholder 2'
},
// multiline input.
{
name: 'paragraph',
id: 'paragraph',
type: 'textarea',
placeholder: 'Placeholder 3'
},
{
name: 'name3',
value: 'http://ionicframework.com',
type: 'url',
placeholder: 'Favorite site ever'
},
// input date with min & max
{
name: 'name4',
type: 'date',
min: '2017-03-01',
max: '2018-01-12'
},
// input date without min nor max
{
name: 'name5',
type: 'date'
},
{
name: 'name6',
type: 'number',
min: -5,
max: 10
},
{
name: 'name7',
type: 'number'
},
{
name: 'name8',
type: 'password',
placeholder: 'Advanced Attributes',
cssClass: 'specialClass',
attributes: {
maxlength: 4,
inputmode: 'decimal'
}
}
];
alert.buttons = [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel')
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok')
}
}
];
document.body.appendChild(alert);
return alert.present();
}
function presentAlertRadio() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Radio';
alert.inputs = [
{
type: 'radio',
label: 'Radio 1',
value: 'value1',
handler: () => {
console.log('Radio 1 selected');
},
checked: true
},
{
type: 'radio',
label: 'Radio 2',
value: 'value2',
handler: () => {
console.log('Radio 2 selected');
}
},
{
type: 'radio',
label: 'Radio 3',
value: 'value3',
handler: () => {
console.log('Radio 3 selected');
}
},
{
type: 'radio',
label: 'Radio 4',
value: 'value4',
handler: () => {
console.log('Radio 4 selected');
}
},
{
type: 'radio',
label: 'Radio 5',
value: 'value5',
handler: () => {
console.log('Radio 5 selected');
}
},
{
type: 'radio',
label: 'Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 ',
value: 'value6',
handler: () => {
console.log('Radio 6 selected');
}
}
];
alert.buttons = [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel')
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok')
}
}
];
document.body.appendChild(alert);
return alert.present();
}
function presentAlertCheckbox() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Checkbox';
alert.inputs = [
{
type: 'checkbox',
label: 'Checkbox 1',
value: 'value1',
handler: () => {
console.log('Checkbox 1 selected');
},
checked: true
},
{
type: 'checkbox',
label: 'Checkbox 2',
value: 'value2',
handler: () => {
console.log('Checkbox 2 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 3',
value: 'value3',
handler: () => {
console.log('Checkbox 3 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 4',
value: 'value4',
handler: () => {
console.log('Checkbox 4 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 5',
value: 'value5',
handler: () => {
console.log('Checkbox 5 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6',
value: 'value6',
handler: () => {
console.log('Checkbox 6 selected');
}
}
];
alert.buttons = [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel')
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok')
}
}
];
document.body.appendChild(alert);
return alert.present();
}
```
### React
```tsx
/* Using with useIonAlert Hook */
import React from 'react';
import { IonButton, IonContent, IonPage, useIonAlert } from '@ionic/react';
const AlertExample: React.FC = () => {
const [present] = useIonAlert();
return (
<IonPage>
<IonContent fullscreen>
<IonButton
expand="block"
onClick={() =>
present({
cssClass: 'my-css',
header: 'Alert',
message: 'alert from hook',
buttons: [
'Cancel',
{ text: 'Ok', handler: (d) => console.log('ok pressed') },
],
onDidDismiss: (e) => console.log('did dismiss'),
})
}
>
Show Alert
</IonButton>
<IonButton
expand="block"
onClick={() => present('hello with params', [{ text: 'Ok' }])}
>
Show Alert using params
</IonButton>
</IonContent>
</IonPage>
);
};
```
```tsx
/* Using with IonAlert Component */
import React, { useState } from 'react';
import { IonAlert, IonButton, IonContent } from '@ionic/react';
export const AlertExample: React.FC = () => {
const [showAlert1, setShowAlert1] = useState(false);
const [showAlert2, setShowAlert2] = useState(false);
const [showAlert3, setShowAlert3] = useState(false);
const [showAlert4, setShowAlert4] = useState(false);
const [showAlert5, setShowAlert5] = useState(false);
const [showAlert6, setShowAlert6] = useState(false);
return (
<IonContent>
<IonButton onClick={() => setShowAlert1(true)} expand="block">Show Alert 1</IonButton>
<IonButton onClick={() => setShowAlert2(true)} expand="block">Show Alert 2</IonButton>
<IonButton onClick={() => setShowAlert3(true)} expand="block">Show Alert 3</IonButton>
<IonButton onClick={() => setShowAlert4(true)} expand="block">Show Alert 4</IonButton>
<IonButton onClick={() => setShowAlert5(true)} expand="block">Show Alert 5</IonButton>
<IonButton onClick={() => setShowAlert6(true)} expand="block">Show Alert 6</IonButton>
<IonAlert
isOpen={showAlert1}
onDidDismiss={() => setShowAlert1(false)}
cssClass='my-custom-class'
header={'Alert'}
subHeader={'Subtitle'}
message={'This is an alert message.'}
buttons={['OK']}
/>
<IonAlert
isOpen={showAlert2}
onDidDismiss={() => setShowAlert2(false)}
cssClass='my-custom-class'
header={'Alert'}
subHeader={'Subtitle'}
message={'This is an alert message.'}
buttons={['Cancel', 'Open Modal', 'Delete']}
/>
<IonAlert
isOpen={showAlert3}
onDidDismiss={() => setShowAlert3(false)}
cssClass='my-custom-class'
header={'Confirm!'}
message={'Message <strong>text</strong>!!!'}
buttons={[
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
id: 'cancel-button',
handler: blah => {
console.log('Confirm Cancel: blah');
}
},
{
text: 'Okay',
id: 'confirm-button',
handler: () => {
console.log('Confirm Okay');
}
}
]}
/>
<IonAlert
isOpen={showAlert4}
onDidDismiss={() => setShowAlert4(false)}
cssClass='my-custom-class'
header={'Prompt!'}
inputs={[
{
name: 'name1',
type: 'text',
placeholder: 'Placeholder 1'
},
{
name: 'name2',
type: 'text',
id: 'name2-id',
value: 'hello',
placeholder: 'Placeholder 2'
},
{
name: 'name3',
value: 'http://ionicframework.com',
type: 'url',
placeholder: 'Favorite site ever'
},
// input date with min & max
{
name: 'name4',
type: 'date',
min: '2017-03-01',
max: '2018-01-12'
},
// input date without min nor max
{
name: 'name5',
type: 'date'
},
{
name: 'name6',
type: 'number',
min: -5,
max: 10
},
{
name: 'name7',
type: 'number'
},
{
name: 'name8',
type: 'password',
placeholder: 'Advanced Attributes',
cssClass: 'specialClass',
attributes: {
maxlength: 4,
inputmode: 'decimal'
}
}
]}
buttons={[
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
},
{
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]}
/>
<IonAlert
isOpen={showAlert5}
onDidDismiss={() => setShowAlert5(false)}
cssClass='my-custom-class'
header={'Radio'}
inputs={[
{
name: 'radio1',
type: 'radio',
label: 'Radio 1',
value: 'value1',
handler: () => {
console.log('Radio 1 selected');
},
checked: true
},
{
name: 'radio2',
type: 'radio',
label: 'Radio 2',
value: 'value2',
handler: () => {
console.log('Radio 2 selected');
}
},
{
name: 'radio3',
type: 'radio',
label: 'Radio 3',
value: 'value3',
handler: () => {
console.log('Radio 3 selected');
}
},
{
name: 'radio4',
type: 'radio',
label: 'Radio 4',
value: 'value4',
handler: () => {
console.log('Radio 4 selected');
}
},
{
name: 'radio5',
type: 'radio',
label: 'Radio 5',
value: 'value5',
handler: () => {
console.log('Radio 5 selected');
}
},
{
name: 'radio6',
type: 'radio',
label: 'Radio 6',
value: 'value6',
handler: () => {
console.log('Radio 6 selected');
}
}
]}
buttons={[
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
},
{
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]}
/>
<IonAlert
isOpen={showAlert6}
onDidDismiss={() => setShowAlert6(false)}
cssClass='my-custom-class'
header={'Checkbox'}
inputs={[
{
name: 'checkbox1',
type: 'checkbox',
label: 'Checkbox 1',
value: 'value1',
handler: () => {
console.log('Checkbox 1 selected');
},
checked: true
},
{
name: 'checkbox2',
type: 'checkbox',
label: 'Checkbox 2',
value: 'value2',
handler: () => {
console.log('Checkbox 2 selected');
}
},
{
name: 'checkbox3',
type: 'checkbox',
label: 'Checkbox 3',
value: 'value3',
handler: () => {
console.log('Checkbox 3 selected');
}
},
{
name: 'checkbox4',
type: 'checkbox',
label: 'Checkbox 4',
value: 'value4',
handler: () => {
console.log('Checkbox 4 selected');
}
},
{
name: 'checkbox5',
type: 'checkbox',
label: 'Checkbox 5',
value: 'value5',
handler: () => {
console.log('Checkbox 5 selected');
}
},
{
name: 'checkbox6',
type: 'checkbox',
label: 'Checkbox 6',
value: 'value6',
handler: () => {
console.log('Checkbox 6 selected');
}
}
]}
buttons={[
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
},
{
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]}
/>
</IonContent>
);
}
export default AlertExample;
```
### Stencil
```tsx
import { Component, h } from '@stencil/core';
import { alertController } from '@ionic/core';
@Component({
tag: 'alert-example',
styleUrl: 'alert-example.css'
})
export class AlertExample {
async presentAlert() {
const alert = await alertController.create({
cssClass: 'my-custom-class',
header: 'Alert',
subHeader: 'Subtitle',
message: 'This is an alert message.',
buttons: ['OK']
});
await alert.present();
const { role } = await alert.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
}
async presentAlertMultipleButtons() {
const alert = await alertController.create({
cssClass: 'my-custom-class',
header: 'Alert',
subHeader: 'Subtitle',
message: 'This is an alert message.',
buttons: ['Cancel', 'Open Modal', 'Delete']
});
await alert.present();
}
async presentAlertConfirm() {
const alert = await alertController.create({
cssClass: 'my-custom-class',
header: 'Confirm!',
message: 'Message <strong>text</strong>!!!',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
id: 'cancel-button',
handler: (blah) => {
console.log('Confirm Cancel: blah');
}
}, {
text: 'Okay',
id: 'confirm-button',
handler: () => {
console.log('Confirm Okay');
}
}
]
});
await alert.present();
}
async presentAlertPrompt() {
const alert = await alertController.create({
cssClass: 'my-custom-class',
header: 'Prompt!',
inputs: [
{
name: 'name1',
type: 'text',
placeholder: 'Placeholder 1'
},
{
name: 'name2',
type: 'text',
id: 'name2-id',
value: 'hello',
placeholder: 'Placeholder 2'
},
// multiline input.
{
name: 'paragraph',
id: 'paragraph',
type: 'textarea',
placeholder: 'Placeholder 3'
},
{
name: 'name3',
value: 'http://ionicframework.com',
type: 'url',
placeholder: 'Favorite site ever'
},
// input date with min & max
{
name: 'name4',
type: 'date',
min: '2017-03-01',
max: '2018-01-12'
},
// input date without min nor max
{
name: 'name5',
type: 'date'
},
{
name: 'name6',
type: 'number',
min: -5,
max: 10
},
{
name: 'name7',
type: 'number'
},
{
name: 'name8',
type: 'password',
placeholder: 'Advanced Attributes',
cssClass: 'specialClass',
attributes: {
maxlength: 4,
inputmode: 'decimal'
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
async presentAlertRadio() {
const alert = await alertController.create({
cssClass: 'my-custom-class',
header: 'Radio',
inputs: [
{
name: 'radio1',
type: 'radio',
label: 'Radio 1',
value: 'value1',
handler: () => {
console.log('Radio 1 selected');
},
checked: true
},
{
name: 'radio2',
type: 'radio',
label: 'Radio 2',
value: 'value2',
handler: () => {
console.log('Radio 2 selected');
}
},
{
name: 'radio3',
type: 'radio',
label: 'Radio 3',
value: 'value3',
handler: () => {
console.log('Radio 3 selected');
}
},
{
name: 'radio4',
type: 'radio',
label: 'Radio 4',
value: 'value4',
handler: () => {
console.log('Radio 4 selected');
}
},
{
name: 'radio5',
type: 'radio',
label: 'Radio 5',
value: 'value5',
handler: () => {
console.log('Radio 5 selected');
}
},
{
name: 'radio6',
type: 'radio',
label: 'Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 Radio 6 ',
value: 'value6',
handler: () => {
console.log('Radio 6 selected');
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
async presentAlertCheckbox() {
const alert = await alertController.create({
cssClass: 'my-custom-class',
header: 'Checkbox',
inputs: [
{
name: 'checkbox1',
type: 'checkbox',
label: 'Checkbox 1',
value: 'value1',
handler: () => {
console.log('Checkbox 1 selected');
},
checked: true
},
{
name: 'checkbox2',
type: 'checkbox',
label: 'Checkbox 2',
value: 'value2',
handler: () => {
console.log('Checkbox 2 selected');
}
},
{
name: 'checkbox3',
type: 'checkbox',
label: 'Checkbox 3',
value: 'value3',
handler: () => {
console.log('Checkbox 3 selected');
}
},
{
name: 'checkbox4',
type: 'checkbox',
label: 'Checkbox 4',
value: 'value4',
handler: () => {
console.log('Checkbox 4 selected');
}
},
{
name: 'checkbox5',
type: 'checkbox',
label: 'Checkbox 5',
value: 'value5',
handler: () => {
console.log('Checkbox 5 selected');
}
},
{
name: 'checkbox6',
type: 'checkbox',
label: 'Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6 Checkbox 6',
value: 'value6',
handler: () => {
console.log('Checkbox 6 selected');
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
render() {
return [
<ion-content>
<ion-button onClick={() => this.presentAlert()}>Present Alert</ion-button>
<ion-button onClick={() => this.presentAlertMultipleButtons()}>Present Alert: Multiple Buttons</ion-button>
<ion-button onClick={() => this.presentAlertConfirm()}>Present Alert: Confirm</ion-button>
<ion-button onClick={() => this.presentAlertPrompt()}>Present Alert: Prompt</ion-button>
<ion-button onClick={() => this.presentAlertRadio()}>Present Alert: Radio</ion-button>
<ion-button onClick={() => this.presentAlertCheckbox()}>Present Alert: Checkbox</ion-button>
</ion-content>
];
}
}
```
### Vue
```html
<template>
<ion-button @click="presentAlert">Show Alert</ion-button>
<ion-button @click="presentAlertMultipleButtons">Show Alert (multiple buttons)</ion-button>
<ion-button @click="presentAlertConfirm">Show Alert (confirm)</ion-button>
<ion-button @click="presentAlertPrompt">Show Alert (prompt)</ion-button>
<ion-button @click="presentAlertRadio">Show Alert (radio)</ion-button>
<ion-button @click="presentAlertCheckbox">Show Alert (checkbox)</ion-button>
</template>
<script>
import { IonButton, alertController } from '@ionic/vue';
import { defineComponent } from 'vue';
export default defineComponent({
components: { IonButton },
methods: {
async presentAlert() {
const alert = await alertController
.create({
cssClass: 'my-custom-class',
header: 'Alert',
subHeader: 'Subtitle',
message: 'This is an alert message.',
buttons: ['OK'],
});
await alert.present();
const { role } = await alert.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
},
async presentAlertMultipleButtons() {
const alert = await alertController
.create({
cssClass: 'my-custom-class',
header: 'Alert',
subHeader: 'Subtitle',
message: 'This is an alert message.',
buttons: ['Cancel', 'Open Modal', 'Delete'],
});
return alert.present();
},
async presentAlertConfirm() {
const alert = await alertController
.create({
cssClass: 'my-custom-class',
header: 'Confirm!',
message: 'Message <strong>text</strong>!!!',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
id: 'cancel-button',
handler: blah => {
console.log('Confirm Cancel:', blah)
},
},
{
text: 'Okay',
id: 'confirm-button',
handler: () => {
console.log('Confirm Okay')
},
},
],
});
return alert.present();
},
async presentAlertPrompt() {
const alert = await alertController
.create({
cssClass: 'my-custom-class',
header: 'Prompt!',
inputs: [
{
placeholder: 'Placeholder 1',
},
{
name: 'name2',
id: 'name2-id',
value: 'hello',
placeholder: 'Placeholder 2',
},
{
name: 'name3',
value: 'http://ionicframework.com',
type: 'url',
placeholder: 'Favorite site ever',
},
// input date with min & max
{
name: 'name4',
type: 'date',
min: '2017-03-01',
max: '2018-01-12',
},
// input date without min nor max
{
name: 'name5',
type: 'date',
},
{
name: 'name6',
type: 'number',
min: -5,
max: 10,
},
{
name: 'name7',
type: 'number',
},
{
name: 'name8',
type: 'password',
placeholder: 'Advanced Attributes',
cssClass: 'specialClass',
attributes: {
maxlength: 4,
inputmode: 'decimal'
}
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel')
},
},
{
text: 'Ok',
handler: () => {
console.log('Confirm Ok')
},
},
],
});
return alert.present();
},
async presentAlertRadio() {
const alert = await alertController
.create({
cssClass: 'my-custom-class',
header: 'Radio',
inputs: [
{
type: 'radio',
label: 'Radio 1',
value: 'value1',
handler: () => {
console.log('Radio 1 selected');
},
checked: true,
},
{
type: 'radio',
label: 'Radio 2',
value: 'value2',
handler: () => {
console.log('Radio 2 selected');
}
},
{
type: 'radio',
label: 'Radio 3',
value: 'value3',
handler: () => {
console.log('Radio 3 selected');
}
},
{
type: 'radio',
label: 'Radio 4',
value: 'value4',
handler: () => {
console.log('Radio 4 selected');
}
},
{
type: 'radio',
label: 'Radio 5',
value: 'value5',
handler: () => {
console.log('Radio 5 selected');
}
},
{
type: 'radio',
label: 'Radio 6',
value: 'value6',
handler: () => {
console.log('Radio 6 selected');
}
},
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel')
},
},
{
text: 'Ok',
handler: () => {
console.log('Confirm Ok')
},
},
],
});
return alert.present();
},
async presentAlertCheckbox() {
const alert = await alertController
.create({
cssClass: 'my-custom-class',
header: 'Checkbox',
inputs: [
{
type: 'checkbox',
label: 'Checkbox 1',
value: 'value1',
handler: () => {
console.log('Checkbox 1 selected');
},
checked: true,
},
{
type: 'checkbox',
label: 'Checkbox 2',
value: 'value2',
handler: () => {
console.log('Checkbox 2 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 3',
value: 'value3',
handler: () => {
console.log('Checkbox 3 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 4',
value: 'value4',
handler: () => {
console.log('Checkbox 4 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 5',
value: 'value5',
handler: () => {
console.log('Checkbox 5 selected');
}
},
{
type: 'checkbox',
label: 'Checkbox 6',
value: 'value6',
handler: () => {
console.log('Checkbox 6 selected');
}
},
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: () => {
console.log('Confirm Cancel')
},
},
{
text: 'Ok',
handler: () => {
console.log('Confirm Ok')
},
},
],
});
return alert.present();
},
},
});
</script>
```
Developers can also use this component directly in their template:
```html
<template>
<ion-button @click="setOpen(true)">Show Alert</ion-button>
<ion-alert
:is-open="isOpenRef"
header="Alert"
sub-header="Subtitle"
message="This is an alert message."
css-class="my-custom-class"
:buttons="buttons"
@didDismiss="setOpen(false)"
>
</ion-alert>
</template>
<script>
import { IonAlert, IonButton } from '@ionic/vue';
import { defineComponent, ref } from 'vue';
export default defineComponent({
components: { IonAlert, IonButton },
setup() {
const isOpenRef = ref(false);
const setOpen = (state: boolean) => isOpenRef.value = state;
const buttons = ['Ok'];
return { buttons, isOpenRef, setOpen }
}
});
</script>
```
## Properties
| Property | Attribute | Description | Type | Default |
| ----------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ----------- |
| `animated` | `animated` | If `true`, the alert will animate. | `boolean` | `true` |
| `backdropDismiss` | `backdrop-dismiss` | If `true`, the alert will be dismissed when the backdrop is clicked. | `boolean` | `true` |
| `buttons` | -- | Array of buttons to be added to the alert. | `(string \| AlertButton)[]` | `[]` |
| `cssClass` | `css-class` | Additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces. | `string \| string[] \| undefined` | `undefined` |
| `enterAnimation` | -- | Animation to use when the alert is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` |
| `header` | `header` | The main title in the heading of the alert. | `string \| undefined` | `undefined` |
| `htmlAttributes` | -- | Additional attributes to pass to the alert. | `AlertAttributes \| undefined` | `undefined` |
| `inputs` | -- | Array of input to show in the alert. | `AlertInput[]` | `[]` |
| `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` |
| `leaveAnimation` | -- | Animation to use when the alert is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` |
| `message` | `message` | The main message to be displayed in the alert. `message` can accept either plaintext or HTML as a string. To display characters normally reserved for HTML, they must be escaped. For example `<Ionic>` would become `<Ionic>` For more information: [Security Documentation](https://ionicframework.com/docs/faq/security) | `IonicSafeString \| string \| undefined` | `undefined` |
| `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` |
| `subHeader` | `sub-header` | The subtitle in the heading of the alert. Displayed under the title. | `string \| undefined` | `undefined` |
| `translucent` | `translucent` | If `true`, the alert will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` |
## Events
| Event | Description | Type |
| --------------------- | --------------------------------------- | -------------------------------------- |
| `ionAlertDidDismiss` | Emitted after the alert has dismissed. | `CustomEvent<OverlayEventDetail<any>>` |
| `ionAlertDidPresent` | Emitted after the alert has presented. | `CustomEvent<void>` |
| `ionAlertWillDismiss` | Emitted before the alert has dismissed. | `CustomEvent<OverlayEventDetail<any>>` |
| `ionAlertWillPresent` | Emitted before the alert has presented. | `CustomEvent<void>` |
## Methods
### `dismiss(data?: any, role?: string | undefined) => Promise<boolean>`
Dismiss the alert overlay after it has been presented.
#### Returns
Type: `Promise<boolean>`
### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>`
Returns a promise that resolves when the alert did dismiss.
#### Returns
Type: `Promise<OverlayEventDetail<T>>`
### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>`
Returns a promise that resolves when the alert will dismiss.
#### Returns
Type: `Promise<OverlayEventDetail<T>>`
### `present() => Promise<void>`
Present the alert overlay after it has been created.
#### Returns
Type: `Promise<void>`
## CSS Custom Properties
| Name | Description |
| -------------------- | --------------------------- |
| `--backdrop-opacity` | Opacity of the backdrop |
| `--background` | Background of the alert |
| `--height` | Height of the alert |
| `--max-height` | Maximum height of the alert |
| `--max-width` | Maximum width of the alert |
| `--min-height` | Minimum height of the alert |
| `--min-width` | Minimum width of the alert |
| `--width` | Width of the alert |
## Dependencies
### Depends on
- [ion-ripple-effect](../ripple-effect)
- [ion-backdrop](../backdrop)
### Graph
```mermaid
graph TD;
ion-alert --> ion-ripple-effect
ion-alert --> ion-backdrop
style ion-alert fill:#f9f,stroke:#333,stroke-width:4px
```
----------------------------------------------
*Built with [StencilJS](https://stenciljs.com/)*
| core/src/components/alert/readme.md | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017678644508123398,
0.0001722111483104527,
0.00016188473091460764,
0.00017272433615289629,
0.0000026180798613495426
] |
{
"id": 5,
"code_window": [
" /**\n",
" * ArrowDown should move focus to the next focusable ion-item.\n",
" */\n",
" case 'ArrowDown':\n",
" ev.preventDefault();\n",
" const nextItem = getNextItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n",
" if (nextItem !== undefined) {\n",
" focusItem(nextItem);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 374
} | @import "./accordion.vars.scss";
// Accordion
// --------------------------------------------------
:host {
display: block;
position: relative;
width: 100%;
background-color: $accordion-background-color;
overflow: hidden;
/**
* This is required to force WebKit
* to create a new stacking context
* otherwise the border radius is
* temporarily lost when hovering over
* the ion-item or expanding/collapsing
* the accordion.
*/
z-index: 0;
}
:host(.accordion-expanding) ::slotted(ion-item[slot="header"]),
:host(.accordion-expanded) ::slotted(ion-item[slot="header"]) {
--border-width: 0px;
}
:host(.accordion-animated) {
transition: all $accordion-transition-duration $accordion-transition-easing;
}
:host(.accordion-animated) #content {
transition: max-height $accordion-transition-duration $accordion-transition-easing;
}
#content {
overflow: hidden;
will-change: max-height;
}
:host(.accordion-collapsing) #content {
/* stylelint-disable-next-line declaration-no-important */
max-height: 0 !important;
}
:host(.accordion-collapsed) #content {
display: none;
}
:host(.accordion-expanding) #content {
max-height: 0;
}
:host(.accordion-disabled) #header,
:host(.accordion-readonly) #header {
pointer-events: none;
}
/**
* We do not set the opacity on the
* host otherwise you would see the
* box-shadow behind it.
*/
:host(.accordion-disabled) #header,
:host(.accordion-disabled) #content {
opacity: $accordion-disabled-opacity;
}
@media (prefers-reduced-motion: reduce) {
:host,
#content {
/* stylelint-disable declaration-no-important */
transition: none !important;
}
}
| core/src/components/accordion/accordion.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017748922982718796,
0.00017032794130500406,
0.00016134367615450174,
0.00017104099970310926,
0.0000049996324378298596
] |
{
"id": 5,
"code_window": [
" /**\n",
" * ArrowDown should move focus to the next focusable ion-item.\n",
" */\n",
" case 'ArrowDown':\n",
" ev.preventDefault();\n",
" const nextItem = getNextItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n",
" if (nextItem !== undefined) {\n",
" focusItem(nextItem);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 374
} | import { ModalAnimationOptions } from '../../../interface';
import { createAnimation } from '../../../utils/animation/animation';
import { getBackdropValueForSheet } from '../utils';
export const createSheetEnterAnimation = (opts: ModalAnimationOptions) => {
const { currentBreakpoint, backdropBreakpoint } = opts;
/**
* If the backdropBreakpoint is undefined, then the backdrop
* should always fade in. If the backdropBreakpoint came before the
* current breakpoint, then the backdrop should be fading in.
*/
const shouldShowBackdrop = backdropBreakpoint === undefined || backdropBreakpoint < currentBreakpoint!;
const initialBackdrop = shouldShowBackdrop ? `calc(var(--backdrop-opacity) * ${currentBreakpoint!})` : '0';
const backdropAnimation = createAnimation('backdropAnimation')
.fromTo('opacity', 0, initialBackdrop);
const wrapperAnimation = createAnimation('wrapperAnimation')
.keyframes([
{ offset: 0, opacity: 1, transform: 'translateY(100%)' },
{ offset: 1, opacity: 1, transform: `translateY(${100 - (currentBreakpoint! * 100)}%)` }
]);
return { wrapperAnimation, backdropAnimation };
}
export const createSheetLeaveAnimation = (opts: ModalAnimationOptions) => {
const { currentBreakpoint, backdropBreakpoint } = opts;
/**
* Backdrop does not always fade in from 0 to 1 if backdropBreakpoint
* is defined, so we need to account for that offset by figuring out
* what the current backdrop value should be.
*/
const backdropValue = `calc(var(--backdrop-opacity) * ${getBackdropValueForSheet(currentBreakpoint!, backdropBreakpoint!)})`;
const defaultBackdrop = [
{ offset: 0, opacity: backdropValue },
{ offset: 1, opacity: 0 }
]
const customBackdrop = [
{ offset: 0, opacity: backdropValue },
{ offset: backdropBreakpoint!, opacity: 0 },
{ offset: 1, opacity: 0 }
]
const backdropAnimation = createAnimation('backdropAnimation')
.keyframes(backdropBreakpoint !== 0 ? customBackdrop : defaultBackdrop);
const wrapperAnimation = createAnimation('wrapperAnimation')
.keyframes([
{ offset: 0, opacity: 1, transform: `translateY(${100 - (currentBreakpoint! * 100)}%)` },
{ offset: 1, opacity: 1, transform: `translateY(100%)` }
]);
return { wrapperAnimation, backdropAnimation };
}
| core/src/components/modal/animations/sheet.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017403064703103155,
0.00017172341176774353,
0.00017017150821629912,
0.0001717216509860009,
0.0000013381344388108118
] |
{
"id": 6,
"code_window": [
" /**\n",
" * ArrowUp should move focus to the previous focusable ion-item.\n",
" */\n",
" case 'ArrowUp':\n",
" ev.preventDefault();\n",
" const prevItem = getPrevItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 385
} | import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, State, Watch, h } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
import { AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, OverlayEventDetail, PopoverAttributes, PopoverInterface, PopoverSize, PositionAlign, PositionReference, PositionSide, TriggerAction } from '../../interface';
import { CoreDelegate, attachComponent, detachComponent } from '../../utils/framework-delegate';
import { addEventListener, raf } from '../../utils/helpers';
import { BACKDROP, dismiss, eventMethod, focusFirstDescendant, prepareOverlay, present } from '../../utils/overlays';
import { isPlatform } from '../../utils/platform';
import { getClassMap } from '../../utils/theme';
import { deepReady } from '../../utils/transition';
import { iosEnterAnimation } from './animations/ios.enter';
import { iosLeaveAnimation } from './animations/ios.leave';
import { mdEnterAnimation } from './animations/md.enter';
import { mdLeaveAnimation } from './animations/md.leave';
import { configureDismissInteraction, configureKeyboardInteraction, configureTriggerInteraction } from './utils';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - Content is placed inside of the `.popover-content` element.
*
* @part backdrop - The `ion-backdrop` element.
* @part arrow - The arrow that points to the reference element. Only applies on `ios` mode.
* @part content - The wrapper element for the default slot.
*/
@Component({
tag: 'ion-popover',
styleUrls: {
ios: 'popover.ios.scss',
md: 'popover.md.scss'
},
shadow: true
})
export class Popover implements ComponentInterface, PopoverInterface {
private usersElement?: HTMLElement;
private triggerEl?: HTMLElement | null;
private parentPopover: HTMLIonPopoverElement | null = null;
private popoverIndex = popoverIds++;
private popoverId?: string;
private coreDelegate: FrameworkDelegate = CoreDelegate();
private currentTransition?: Promise<any>;
private destroyTriggerInteraction?: () => void;
private destroyKeyboardInteraction?: () => void;
private destroyDismissInteraction?: () => void;
private inline = false;
private workingDelegate?: FrameworkDelegate;
private focusDescendantOnPresent = false;
lastFocus?: HTMLElement;
@State() presented = false;
@Element() el!: HTMLIonPopoverElement;
/** @internal */
@Prop() hasController = false;
/** @internal */
@Prop() delegate?: FrameworkDelegate;
/** @internal */
@Prop() overlayIndex!: number;
/**
* Animation to use when the popover is presented.
*/
@Prop() enterAnimation?: AnimationBuilder;
/**
* Animation to use when the popover is dismissed.
*/
@Prop() leaveAnimation?: AnimationBuilder;
/**
* The component to display inside of the popover.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* slot your component inside of `ion-popover`.
*/
@Prop() component?: ComponentRef;
/**
* The data to pass to the popover component.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* set the props directly on your component.
*/
@Prop() componentProps?: ComponentProps;
/**
* If `true`, the keyboard will be automatically dismissed when the overlay is presented.
*/
@Prop() keyboardClose = true;
/**
* Additional classes to apply for custom CSS. If multiple classes are
* provided they should be separated by spaces.
* @internal
*/
@Prop() cssClass?: string | string[];
/**
* If `true`, the popover will be dismissed when the backdrop is clicked.
*/
@Prop() backdropDismiss = true;
/**
* The event to pass to the popover animation.
*/
@Prop() event: any;
/**
* If `true`, a backdrop will be displayed behind the popover.
*/
@Prop() showBackdrop = true;
/**
* If `true`, the popover will be translucent.
* Only applies when the mode is `"ios"` and the device supports
* [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility).
*/
@Prop() translucent = false;
/**
* If `true`, the popover will animate.
*/
@Prop() animated = true;
/**
* Additional attributes to pass to the popover.
*/
@Prop() htmlAttributes?: PopoverAttributes;
/**
* Describes what kind of interaction with the trigger that
* should cause the popover to open. Does not apply when the `trigger`
* property is `undefined`.
* If `'click'`, the popover will be presented when the trigger is left clicked.
* If `'hover'`, the popover will be presented when a pointer hovers over the trigger.
* If `'context-menu'`, the popover will be presented when the trigger is right
* clicked on desktop and long pressed on mobile. This will also prevent your
* device's normal context menu from appearing.
*/
@Prop() triggerAction: TriggerAction = 'click';
/**
* An ID corresponding to the trigger element that
* causes the popover to open. Use the `trigger-action`
* property to customize the interaction that results in
* the popover opening.
*/
@Prop() trigger: string | undefined;
/**
* Describes how to calculate the popover width.
* If `'cover'`, the popover width will match the width of the trigger.
* If `'auto'`, the popover width will be determined by the content in
* the popover.
*/
@Prop() size: PopoverSize = 'auto';
/**
* If `true`, the popover will be automatically
* dismissed when the content has been clicked.
*/
@Prop() dismissOnSelect = false;
/**
* Describes what to position the popover relative to.
* If `'trigger'`, the popover will be positioned relative
* to the trigger button. If passing in an event, this is
* determined via event.target.
* If `'event'`, the popover will be positioned relative
* to the x/y coordinates of the trigger action. If passing
* in an event, this is determined via event.clientX and event.clientY.
*/
@Prop() reference: PositionReference = 'trigger';
/**
* Describes which side of the `reference` point to position
* the popover on. The `'start'` and `'end'` values are RTL-aware,
* and the `'left'` and `'right'` values are not.
*/
@Prop() side: PositionSide = 'bottom';
/**
* Describes how to align the popover content with the `reference` point.
*/
@Prop() alignment: PositionAlign = 'start';
/**
* If `true`, the popover will display an arrow
* that points at the `reference` when running in `ios` mode
* on mobile. Does not apply in `md` mode or on desktop.
*/
@Prop() arrow = true;
/**
* If `true`, the popover will open. If `false`, the popover will close.
* Use this if you need finer grained control over presentation, otherwise
* just use the popoverController or the `trigger` property.
* Note: `isOpen` will not automatically be set back to `false` when
* the popover dismisses. You will need to do that in your code.
*/
@Prop() isOpen = false;
@Watch('trigger')
@Watch('triggerAction')
onTriggerChange() {
this.configureTriggerInteraction();
}
@Watch('isOpen')
onIsOpenChange(newValue: boolean, oldValue: boolean) {
if (newValue === true && oldValue === false) {
this.present();
} else if (newValue === false && oldValue === true) {
this.dismiss();
}
}
/**
* Emitted after the popover has presented.
*/
@Event({ eventName: 'ionPopoverDidPresent' }) didPresent!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
*/
@Event({ eventName: 'ionPopoverWillPresent' }) willPresent!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has presented.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'didPresent' }) didPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
* Shorthand for ionPopoverWillPresent.
*/
@Event({ eventName: 'willPresent' }) willPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'willDismiss' }) willDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
* Shorthand for ionPopoverDidDismiss.
*/
@Event({ eventName: 'didDismiss' }) didDismissShorthand!: EventEmitter<OverlayEventDetail>;
connectedCallback() {
prepareOverlay(this.el);
}
componentWillLoad() {
/**
* If user has custom ID set then we should
* not assign the default incrementing ID.
*/
this.popoverId = (this.el.hasAttribute('id')) ? this.el.getAttribute('id')! : `ion-popover-${this.popoverIndex}`;
this.parentPopover = this.el.closest(`ion-popover:not(#${this.popoverId})`) as HTMLIonPopoverElement | null;
}
componentDidLoad() {
const { parentPopover, isOpen } = this;
/**
* If popover was rendered with isOpen="true"
* then we should open popover immediately.
*/
if (isOpen === true) {
raf(() => this.present());
}
if (parentPopover) {
addEventListener(parentPopover, 'ionPopoverWillDismiss', () => {
this.dismiss(undefined, undefined, false);
});
}
this.configureTriggerInteraction();
}
/**
* When opening a popover from a trigger, we should not be
* modifying the `event` prop from inside the component.
* Additionally, when pressing the "Right" arrow key, we need
* to shift focus to the first descendant in the newly presented
* popover.
*
* @internal
*/
@Method()
async presentFromTrigger(event?: any, focusDescendant = false) {
this.focusDescendantOnPresent = focusDescendant;
await this.present(event);
this.focusDescendantOnPresent = false;
}
/**
* Determines whether or not an overlay
* is being used inline or via a controller/JS
* and returns the correct delegate.
* By default, subsequent calls to getDelegate
* will use a cached version of the delegate.
* This is useful for calling dismiss after
* present so that the correct delegate is given.
*/
private getDelegate(force = false) {
if (this.workingDelegate && !force) {
return {
delegate: this.workingDelegate,
inline: this.inline
}
}
/**
* If using overlay inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps.
* If a developer has presented this component
* via a controller, then we can assume
* the component is already in the
* correct place.
*/
const parentEl = this.el.parentNode as HTMLElement | null;
const inline = this.inline = parentEl !== null && !this.hasController;
const delegate = this.workingDelegate = (inline) ? this.delegate || this.coreDelegate : this.delegate
return { inline, delegate }
}
/**
* Present the popover overlay after it has been created.
* Developers can pass a mouse, touch, or pointer event
* to position the popover relative to where that event
* was dispatched.
*/
@Method()
async present(event?: MouseEvent | TouchEvent | PointerEvent): Promise<void> {
if (this.presented) {
return;
}
/**
* When using an inline popover
* and dismissing a popover it is possible to
* quickly present the popover while it is
* dismissing. We need to await any current
* transition to allow the dismiss to finish
* before presenting again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const data = {
...this.componentProps,
popover: this.el
};
const { inline, delegate } = this.getDelegate(true);
this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);
await deepReady(this.usersElement);
this.configureKeyboardInteraction();
this.configureDismissInteraction();
this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {
event: event || this.event,
size: this.size,
trigger: this.triggerEl,
reference: this.reference,
side: this.side,
align: this.alignment
});
await this.currentTransition;
this.currentTransition = undefined;
/**
* If popover is nested and was
* presented using the "Right" arrow key,
* we need to move focus to the first
* descendant inside of the popover.
*/
if (this.focusDescendantOnPresent) {
focusFirstDescendant(this.el, this.el);
}
}
/**
* Dismiss the popover overlay after it has been presented.
*
* @param data Any data to emit in the dismiss events.
* @param role The role of the element that is dismissing the popover. For example, 'cancel' or 'backdrop'.
* @param dismissParentPopover If `true`, dismissing this popover will also dismiss
* a parent popover if this popover is nested. Defaults to `true`.
*/
@Method()
async dismiss(data?: any, role?: string, dismissParentPopover = true): Promise<boolean> {
/**
* When using an inline popover
* and presenting a popover it is possible to
* quickly dismiss the popover while it is
* presenting. We need to await any current
* transition to allow the present to finish
* before dismissing again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const { destroyKeyboardInteraction, destroyDismissInteraction } = this;
if (dismissParentPopover && this.parentPopover) {
this.parentPopover.dismiss(data, role, dismissParentPopover)
}
this.currentTransition = dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
const shouldDismiss = await this.currentTransition;
if (shouldDismiss) {
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
this.destroyKeyboardInteraction = undefined;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
this.destroyDismissInteraction = undefined;
}
/**
* If using popover inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps
*/
const { delegate } = this.getDelegate();
await detachComponent(delegate, this.usersElement);
}
this.currentTransition = undefined;
return shouldDismiss;
}
/**
* @internal
*/
@Method()
async getParentPopover(): Promise<HTMLIonPopoverElement | null> {
return this.parentPopover;
}
/**
* Returns a promise that resolves when the popover did dismiss.
*/
@Method()
onDidDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverDidDismiss');
}
/**
* Returns a promise that resolves when the popover will dismiss.
*/
@Method()
onWillDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverWillDismiss');
}
private onDismiss = (ev: UIEvent) => {
ev.stopPropagation();
ev.preventDefault();
this.dismiss();
}
private onBackdropTap = () => {
this.dismiss(undefined, BACKDROP);
}
private onLifecycle = (modalEvent: CustomEvent) => {
const el = this.usersElement;
const name = LIFECYCLE_MAP[modalEvent.type];
if (el && name) {
const event = new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: modalEvent.detail
});
el.dispatchEvent(event);
}
}
private configureTriggerInteraction = () => {
const { trigger, triggerAction, el, destroyTriggerInteraction } = this;
if (destroyTriggerInteraction) {
destroyTriggerInteraction();
}
const triggerEl = this.triggerEl = (trigger !== undefined) ? document.getElementById(trigger) : null;
if (!triggerEl) { return; }
this.destroyTriggerInteraction = configureTriggerInteraction(triggerEl, triggerAction, el);
}
private configureKeyboardInteraction = () => {
const { destroyKeyboardInteraction, el } = this;
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
}
this.destroyKeyboardInteraction = configureKeyboardInteraction(el);
}
private configureDismissInteraction = () => {
const { destroyDismissInteraction, parentPopover, triggerAction, triggerEl, el } = this;
if (!parentPopover || !triggerEl) { return; }
if (destroyDismissInteraction) {
destroyDismissInteraction();
}
this.destroyDismissInteraction = configureDismissInteraction(triggerEl, triggerAction, el, parentPopover);
}
render() {
const mode = getIonMode(this);
const { onLifecycle, popoverId, parentPopover, dismissOnSelect, presented, side, arrow, htmlAttributes } = this;
const desktop = isPlatform('desktop');
const enableArrow = arrow && !parentPopover && !desktop;
return (
<Host
aria-modal="true"
no-router
tabindex="-1"
{...htmlAttributes as any}
style={{
zIndex: `${20000 + this.overlayIndex}`,
}}
id={popoverId}
class={{
...getClassMap(this.cssClass),
[mode]: true,
'popover-translucent': this.translucent,
'overlay-hidden': true,
'popover-interactive': presented,
'popover-desktop': desktop,
[`popover-side-${side}`]: true,
'popover-nested': !!parentPopover
}}
onIonPopoverDidPresent={onLifecycle}
onIonPopoverWillPresent={onLifecycle}
onIonPopoverWillDismiss={onLifecycle}
onIonPopoverDidDismiss={onLifecycle}
onIonDismiss={this.onDismiss}
onIonBackdropTap={this.onBackdropTap}
>
{!parentPopover && <ion-backdrop tappable={this.backdropDismiss} visible={this.showBackdrop} part="backdrop" />}
<div
class="popover-wrapper ion-overlay-wrapper"
onClick={dismissOnSelect ? () => this.dismiss() : undefined}
>
{enableArrow && <div class="popover-arrow" part="arrow"></div>}
<div class="popover-content" part="content">
<slot></slot>
</div>
</div>
</Host>
);
}
}
const LIFECYCLE_MAP: any = {
'ionPopoverDidPresent': 'ionViewDidEnter',
'ionPopoverWillPresent': 'ionViewWillEnter',
'ionPopoverWillDismiss': 'ionViewWillLeave',
'ionPopoverDidDismiss': 'ionViewDidLeave',
};
let popoverIds = 0;
| core/src/components/popover/popover.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0005540882120840251,
0.00017919290985446423,
0.00016160034283529967,
0.0001713568635750562,
0.00005026771759730764
] |
{
"id": 6,
"code_window": [
" /**\n",
" * ArrowUp should move focus to the previous focusable ion-item.\n",
" */\n",
" case 'ArrowUp':\n",
" ev.preventDefault();\n",
" const prevItem = getPrevItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 385
} | @import "../../themes/ionic.globals.ios";
/// @prop - Color of the refresher icon
$refresher-ios-icon-color: $text-color !default;
/// @prop - Text color of the refresher content
$refresher-ios-text-color: $text-color !default;
/// @prop - Color of the native refresher spinner
$refresher-ios-native-spinner-color: var(--ion-color-step-450, #747577) !default;
/// @prop - Width of the native refresher spinner
$refresher-ios-native-spinner-width: 32px !default;
/// @prop - Height of the native refresher spinner
$refresher-ios-native-spinner-height: 32px !default;
| core/src/components/refresher/refresher.ios.vars.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.00017550494521856308,
0.0001750623487168923,
0.00017461975221522152,
0.0001750623487168923,
4.425965016707778e-7
] |
{
"id": 6,
"code_window": [
" /**\n",
" * ArrowUp should move focus to the previous focusable ion-item.\n",
" */\n",
" case 'ArrowUp':\n",
" ev.preventDefault();\n",
" const prevItem = getPrevItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 385
} | import { newSpecPage } from '@stencil/core/testing';
import { Breadcrumbs } from '../breadcrumbs.tsx';
import { Breadcrumb } from '../../breadcrumb/breadcrumb.tsx';
it('should correctly provide the collapsed breadcrumbs in the event payload', async () => {
const page = await newSpecPage({
components: [Breadcrumbs, Breadcrumb],
html: `
<ion-breadcrumbs max-items="2" items-before-collapse="1" items-after-collapse="1">
<ion-breadcrumb>First</ion-breadcrumb>
<ion-breadcrumb>Second</ion-breadcrumb>
<ion-breadcrumb>Third</ion-breadcrumb>
<ion-breadcrumb>Fourth</ion-breadcrumb>
<ion-breadcrumb>Fifth</ion-breadcrumb>
</ion-breadcrumbs>
`
});
const onCollapsedClick = jest.fn((ev) => ev);
const breadcrumbs = page.body.querySelector('ion-breadcrumbs');
const breadcrumb = page.body.querySelectorAll('ion-breadcrumb');
breadcrumbs.addEventListener('ionCollapsedClick', onCollapsedClick);
const event = new CustomEvent('collapsedClick');
breadcrumbs.dispatchEvent(event);
expect(onCollapsedClick).toHaveBeenCalledTimes(1);
const collapsedBreadcrumbs = onCollapsedClick.mock.calls[0][0].detail.collapsedBreadcrumbs;
expect(collapsedBreadcrumbs.length).toEqual(3);
expect(collapsedBreadcrumbs[0]).toBe(breadcrumb[1]);
expect(collapsedBreadcrumbs[1]).toBe(breadcrumb[2]);
expect(collapsedBreadcrumbs[2]).toBe(breadcrumb[3]);
});
| core/src/components/breadcrumbs/test/breadcrumbs.spec.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0001779571030056104,
0.00017472298350185156,
0.0001691223296802491,
0.00017590628704056144,
0.0000034855490866902983
] |
{
"id": 6,
"code_window": [
" /**\n",
" * ArrowUp should move focus to the previous focusable ion-item.\n",
" */\n",
" case 'ArrowUp':\n",
" ev.preventDefault();\n",
" const prevItem = getPrevItem(items, activeElement);\n",
" // tslint:disable-next-line:strict-type-predicates\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Disable movement/scroll with keyboard\n"
],
"file_path": "core/src/components/popover/utils.ts",
"type": "add",
"edit_start_line_idx": 385
} | @import "../../themes/ionic.globals";
:host {
@include position(0, 0, 0, 0);
position: absolute;
contain: layout size style;
overflow: hidden;
z-index: $z-index-page-container;
}
| core/src/components/router-outlet/route-outlet.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/8bdcd3c6c99d84a0a46b0f08dceca6b6929fd8f8 | [
0.0001769422524375841,
0.00017679971642792225,
0.0001766571804182604,
0.00017679971642792225,
1.4253600966185331e-7
] |
{
"id": 0,
"code_window": [
"\t * Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.\n",
"\t * Also saves all files, manages if compounds are present in the configuration\n",
"\t * and resolveds configurations via DebugConfigurationProviders.\n",
"\t */\n",
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<any>;\n",
"\n",
"\t/**\n",
"\t * Restarts a process or creates a new one if there is no active session.\n",
"\t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<void>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 630
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import * as resources from 'vs/base/common/resources';
import * as strings from 'vs/base/common/strings';
import { generateUuid } from 'vs/base/common/uuid';
import uri from 'vs/base/common/uri';
import * as platform from 'vs/base/common/platform';
import { first, distinct } from 'vs/base/common/arrays';
import { isObject, isUndefinedOrNull } from 'vs/base/common/types';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { TPromise } from 'vs/base/common/winjs.base';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import * as debug from 'vs/workbench/parts/debug/common/debug';
import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import { Model, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, RawObjectReplElement, ExpressionContainer, Process } from 'vs/workbench/parts/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/parts/debug/electron-browser/debugConfigurationManager';
import Constants from 'vs/workbench/parts/markers/electron-browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService';
import { TaskError } from 'vs/workbench/parts/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL, EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL, EXTENSION_RELOAD_BROADCAST_CHANNEL } from 'vs/platform/extensions/common/extensionHost';
import { IBroadcastService, IBroadcast } from 'vs/platform/broadcast/electron-browser/broadcastService';
import { IRemoteConsoleLog, parse, getFirstFrame } from 'vs/base/node/console';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { TaskEvent, TaskEventKind } from 'vs/workbench/parts/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { RunOnceScheduler } from 'vs/base/common/async';
import product from 'vs/platform/node/product';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private sessionStates: Map<string, debug.State>;
private readonly _onDidChangeState: Emitter<debug.State>;
private readonly _onDidNewProcess: Emitter<debug.IProcess>;
private readonly _onDidEndProcess: Emitter<debug.IProcess>;
private readonly _onDidCustomEvent: Emitter<debug.DebugEvent>;
private model: Model;
private viewModel: ViewModel;
private allProcesses: Map<string, debug.IProcess>;
private configurationManager: ConfigurationManager;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: Map<string, lifecycle.IDisposable[]>;
private inDebugMode: IContextKey<boolean>;
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private breakpointsToSendOnResourceSaved: Set<string>;
private launchJsonChanged: boolean;
private firstSessionStart: boolean;
private skipRunningTask: boolean;
private previousState: debug.State;
private fetchThreadsSchedulers: Map<string, RunOnceScheduler>;
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@INotificationService private notificationService: INotificationService,
@IDialogService private dialogService: IDialogService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@IBroadcastService private broadcastService: IBroadcastService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = new Map<string, lifecycle.IDisposable[]>();
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<debug.State>();
this._onDidNewProcess = new Emitter<debug.IProcess>();
this._onDidEndProcess = new Emitter<debug.IProcess>();
this._onDidCustomEvent = new Emitter<debug.DebugEvent>();
this.sessionStates = new Map<string, debug.State>();
this.allProcesses = new Map<string, debug.IProcess>();
this.fetchThreadsSchedulers = new Map<string, RunOnceScheduler>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
this.toDispose.push(this.configurationManager);
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.debugType = debug.CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = debug.CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.model = new Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.firstSessionStart = true;
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.store, this);
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.broadcastService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
const process = this.allProcesses.get(broadcast.payload.debugId);
if (!process) {
// Ignore attach events for sessions that never existed (wrong vscode windows)
return;
}
const session = <RawDebugSession>process.session;
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
process.configuration.request = 'attach';
process.configuration.port = broadcast.payload.port;
this.doCreateProcess(process.session.root, process.configuration, process.getId());
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
return;
}
// an extension logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: IRemoteConsoleLog = broadcast.payload.logEntry;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(extensionOutput);
let source: debug.IReplElementSource;
if (stack) {
const frame = getFirstFrame(stack);
if (frame) {
source = {
column: frame.column,
lineNumber: frame.line,
source: process.getSource({
name: resources.basenameOrAuthority(frame.uri),
path: frame.uri.fsPath
})
};
}
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev, source);
simpleVals = [];
}
// show object
this.logToRepl(new RawObjectReplElement((<any>a).prototype, a, undefined, nls.localize('snapshotObj', "Only primitive values are shown for this object.")), sev, source);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
// always append a new line for output coming from an extension such that separate logs go to separate lines #23695
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' ') + '\n', sev, source);
}
}
}
private tryToAutoFocusStackFrame(thread: debug.IThread): TPromise<any> {
const callStack = thread.getCallStack();
if (!callStack.length || (this.viewModel.focusedStackFrame && this.viewModel.focusedStackFrame.thread.getId() === thread.getId())) {
return TPromise.as(null);
}
// focus first stack frame from top that has source location if no other stack frame is focused
const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, undefined);
if (!stackFrameToFocus) {
return TPromise.as(null);
}
this.focusStackFrame(stackFrameToFocus);
if (thread.stoppedDetails) {
this.windowService.focusWindow();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", thread.stoppedDetails.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.range.startLineNumber));
}
return stackFrameToFocus.openInEditor(this.editorService, true);
}
private registerSessionListeners(process: Process, session: RawDebugSession): void {
this.toDisposeOnSessionEnd.get(session.getId()).push(session);
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
const sendConfigurationDone = () => {
if (session && session.capabilities.supportsConfigurationDoneRequest) {
return session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (session) {
session.disconnect().done(null, errors.onUnexpectedError);
}
this.notificationService.error(e.message);
});
}
};
this.sendAllBreakpoints(process).then(sendConfigurationDone, sendConfigurationDone)
.done(() => this.fetchThreads(session), errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidStop(event => {
this.updateStateAndEmit(session.getId(), debug.State.Stopped);
this.fetchThreads(session, event.body).done(() => {
const thread = process && process.getThread(event.body.threadId);
if (thread) {
// Call fetch call stack twice, the first only return the top stack frame.
// Second retrieves the rest of the call stack. For performance reasons #25605
this.model.fetchCallStack(thread).then(() => {
return this.tryToAutoFocusStackFrame(thread);
});
}
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidThread(event => {
if (event.body.reason === 'started') {
// debounce to reduce threadsRequest frequency and improve performance
let scheduler = this.fetchThreadsSchedulers.get(session.getId());
if (!scheduler) {
scheduler = new RunOnceScheduler(() => {
this.fetchThreads(session).done(undefined, errors.onUnexpectedError);
}, 100);
this.fetchThreadsSchedulers.set(session.getId(), scheduler);
this.toDisposeOnSessionEnd.get(session.getId()).push(scheduler);
}
if (!scheduler.isScheduled()) {
scheduler.schedule();
}
} else if (event.body.reason === 'exited') {
this.model.clearThreads(session.getId(), true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (session && session.getId() === event.sessionId) {
if (event.body && event.body.restart && process) {
this.restartProcess(process, event.body.restart).done(null, err => this.notificationService.error(err.message));
} else {
session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidContinued(event => {
const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
this.model.clearThreads(session.getId(), false, threadId);
if (this.viewModel.focusedProcess.getId() === session.getId()) {
this.focusStackFrame(undefined, this.viewModel.focusedThread, this.viewModel.focusedProcess);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
}));
let outputPromises: TPromise<void>[] = [];
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidOutput(event => {
if (!event.body) {
return;
}
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
if (event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (session.customTelemetryService && this.telemetryService.isOptedIn) {
// __GDPR__TODO__ We're sending events in the name of the debug adapter and we can not ensure that those are declared correctly.
session.customTelemetryService.publicLog(event.body.output, event.body.data);
}
return;
}
// Make sure to append output in the correct order by properly waiting on preivous promises #33822
const waitFor = outputPromises.slice();
const source = event.body.source ? {
lineNumber: event.body.line,
column: event.body.column,
source: process.getSource(event.body.source)
} : undefined;
if (event.body.variablesReference) {
const container = new ExpressionContainer(process, event.body.variablesReference, generateUuid());
outputPromises.push(container.getChildren().then(children => {
return TPromise.join(waitFor).then(() => children.forEach(child => {
// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
child.name = null;
this.logToRepl(child, outputSeverity, source);
}));
}));
} else if (typeof event.body.output === 'string') {
TPromise.join(waitFor).then(() => this.logToRepl(event.body.output, outputSeverity, source));
}
TPromise.join(outputPromises).then(() => outputPromises = []);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (event.body.reason === 'new' && event.body.breakpoint.source) {
const source = process.getSource(event.body.breakpoint.source);
const bps = this.model.addBreakpoints(source.uri, [{
column: event.body.breakpoint.column,
enabled: true,
lineNumber: event.body.breakpoint.line,
}], false);
if (bps.length === 1) {
this.model.updateBreakpoints({ [bps[0].getId()]: event.body.breakpoint });
}
}
if (event.body.reason === 'removed') {
if (breakpoint) {
this.model.removeBreakpoints([breakpoint]);
}
if (functionBreakpoint) {
this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
}
}
if (event.body.reason === 'changed') {
if (breakpoint) {
if (!breakpoint.column) {
event.body.breakpoint.column = undefined;
}
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
}
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionhost') && this.sessionStates.get(session.getId()) === debug.State.Running &&
process && process.session.root && process.configuration.noDebug) {
this.broadcastService.broadcast({
channel: EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
if (session && session.getId() === event.sessionId) {
this.onSessionEnd(session);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidCustomEvent(event => {
this._onDidCustomEvent.fire(event);
}));
}
private fetchThreads(session: RawDebugSession, stoppedDetails?: debug.IRawStoppedDetails): TPromise<any> {
return session.threads().then(response => {
if (response && response.body && response.body.threads) {
response.body.threads.forEach(thread => {
this.model.rawUpdate({
sessionId: session.getId(),
threadId: thread.id,
thread,
stoppedDetails: stoppedDetails && thread.id === stoppedDetails.threadId ? stoppedDetails : undefined
});
});
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.adapterData);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
const focusedThread = this.viewModel.focusedThread;
if (focusedThread && focusedThread.stopped) {
return debug.State.Stopped;
}
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && this.sessionStates.has(focusedProcess.getId())) {
return this.sessionStates.get(focusedProcess.getId());
}
if (this.sessionStates.size > 0) {
return debug.State.Initializing;
}
return debug.State.Inactive;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
public get onDidNewProcess(): Event<debug.IProcess> {
return this._onDidNewProcess.event;
}
public get onDidEndProcess(): Event<debug.IProcess> {
return this._onDidEndProcess.event;
}
public get onDidCustomEvent(): Event<debug.DebugEvent> {
return this._onDidCustomEvent.event;
}
private updateStateAndEmit(sessionId?: string, newState?: debug.State): void {
if (sessionId) {
if (newState === debug.State.Inactive) {
this.sessionStates.delete(sessionId);
} else {
this.sessionStates.set(sessionId, newState);
}
}
const state = this.state;
if (this.previousState !== state) {
const stateLabel = debug.State[state];
if (stateLabel) {
this.debugState.set(stateLabel.toLowerCase());
}
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
public focusStackFrame(stackFrame: debug.IStackFrame, thread?: debug.IThread, process?: debug.IProcess, explicit?: boolean): void {
if (!process) {
if (stackFrame || thread) {
process = stackFrame ? stackFrame.thread.process : thread.process;
} else {
const processes = this.model.getProcesses();
process = processes.length ? processes[0] : undefined;
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = process ? process.getAllThreads() : undefined;
thread = threads && threads.length ? threads[0] : undefined;
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = callStack && callStack.length ? callStack[0] : null;
}
}
this.viewModel.setFocus(stackFrame, thread, process, explicit);
this.updateStateAndEmit();
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
return this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(uri: uri, rawBreakpoints: debug.IBreakpointData[]): TPromise<void> {
this.model.addBreakpoints(uri, rawBreakpoints);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, uri.fsPath)));
return this.sendBreakpoints(uri);
}
public updateBreakpoints(uri: uri, data: { [id: string]: DebugProtocol.Breakpoint }, sendOnResourceSaved: boolean): void {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
this.sendBreakpoints(uri);
}
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
return this.model.addReplExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name)
// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
.then(() => this.focusStackFrame(this.viewModel.focusedStackFrame, this.viewModel.focusedThread, this.viewModel.focusedProcess));
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public logToRepl(value: string | debug.IExpression, sev = severity.Info, source?: debug.IReplElementSource): void {
if (typeof value === 'string' && '[2J'.localeCompare(value) === 0) {
// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
this.model.removeReplExpressions();
} else {
this.model.appendToRepl(value, sev, source);
}
}
public addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name);
this.viewModel.setSelectedExpression(we);
}
public renameWatchExpression(id: string, newName: string): void {
return this.model.renameWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, id, newName);
}
public moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
if (this.model.getProcesses().length === 0) {
this.removeReplExpressions();
this.allProcesses.clear();
this.model.getBreakpoints().forEach(bp => bp.verified = false);
}
this.launchJsonChanged = false;
let config: debug.IConfig, compound: debug.ICompound;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
if (!compound.configurations) {
return TPromise.wrapError(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return TPromise.join(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound.name) {
return TPromise.as(null);
}
let launchForName: debug.ILaunch;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return TPromise.wrapError(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return TPromise.wrapError(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
}
}
return this.startDebugging(launchForName, name, noDebug);
}));
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", configOrName) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return TPromise.wrapError(new Error(message));
}
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = <debug.IConfig>{};
}
if (noDebug) {
config.noDebug = true;
}
const sessionId = generateUuid();
this.updateStateAndEmit(sessionId, debug.State.Initializing);
const wrapUpState = () => {
if (this.sessionStates.get(sessionId) === debug.State.Initializing) {
this.updateStateAndEmit(sessionId, debug.State.Inactive);
}
};
return (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>
(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>
this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.createProcess(launch, config, sessionId);
}
if (launch) {
return launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);
}
})
).then(() => wrapUpState(), err => {
wrapUpState();
return <any>TPromise.wrapError(err);
}));
})
)));
}
private createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {
return this.textFileService.saveAll().then(() =>
(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return undefined;
}
if (!this.configurationManager.getAdapter(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message);
}
this.toDisposeOnSessionEnd.set(sessionId, []);
const workspace = launch ? launch.workspace : undefined;
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
});
return this.runTask(sessionId, workspace, resolvedConfig.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = resolvedConfig.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
}
const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", resolvedConfig.preLaunchTask, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => undefined);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}, err => {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved on disk and that you have a debug extension installed for that file type."));
}
return launch && launch.openConfigFile(false).then(editor => void 0);
})
);
}
private doCreateProcess(root: IWorkspaceFolder, configuration: debug.IConfig, sessionId: string): TPromise<debug.IProcess> {
configuration.__sessionId = sessionId;
this.inDebugMode.set(true);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const adapter = this.configurationManager.getAdapter(configuration.type);
const { aiKey, type } = adapter;
const publisher = adapter.extensionDescription.publisher;
let client: TelemetryClient;
let customTelemetryService: TelemetryService;
if (aiKey) {
client = new TelemetryClient(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${publisher}.${type}`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, customTelemetryService, root);
const process = this.model.addProcess(configuration, session);
this.allProcesses.set(process.getId(), process);
if (client) {
this.toDisposeOnSessionEnd.get(session.getId()).push(client);
}
this.registerSessionListeners(process, session);
return session.initialize({
clientID: 'vscode',
clientName: product.nameLong,
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true, // #10574
locale: platform.locale
}).then((result: DebugProtocol.InitializeResponse) => {
this.model.setExceptionBreakpoints(session.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (session.disconnected) {
return TPromise.as(null);
}
this.focusStackFrame(undefined, undefined, process);
this._onDidNewProcess.fire(process);
const internalConsoleOptions = configuration.internalConsoleOptions || this.configurationService.getValue<debug.IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const openDebugOptions = this.configurationService.getValue<debug.IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting
if (openDebugOptions === 'openOnSessionStart' || (openDebugOptions === 'openOnFirstSessionStart' && this.firstSessionStart)) {
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
this.firstSessionStart = false;
this.debugType.set(configuration.type);
if (this.model.getProcesses().length > 1) {
this.viewModel.setMultiProcessView(true);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: adapter.extensionDescription.id,
isBuiltin: adapter.extensionDescription.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<debug.IGlobalConfig>('launch', { resource: root.uri })
});
}).then(() => process, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
const errorMessage = error instanceof Error ? error.message : error;
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined, error: errorMessage });
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (!session.disconnected) {
session.disconnect().done(null, errors.onUnexpectedError);
} else if (process) {
this.model.removeProcess(process.getId());
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (this.model.getReplElements().length === 0) {
this.inDebugMode.reset();
}
this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []);
return undefined;
});
});
}
private showError(message: string, actions: IAction[] = []): TPromise<any> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
actions.push(configureAction);
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return TPromise.as(null);
});
}
private runTask(sessionId: string, root: IWorkspaceFolder, taskName: string): TPromise<ITaskSummary> {
if (!taskName || this.skipRunningTask) {
this.skipRunningTask = false;
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskName).then(task => {
if (!task) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the task \'{0}\'.", taskName)));
}
function once(kind: TaskEventKind, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (e.kind === kind) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return TPromise.as(null);
}
this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Active, this.taskService.onDidStateChange)(() => {
taskStarted = true;
})
);
const taskPromise = this.taskService.run(task);
if (task.isBackground) {
return new TPromise((c, e) => this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => c(null)))
);
}
return taskPromise;
});
return new TPromise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
e({ severity: severity.Error, message: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", taskName) });
}
}, 10000);
});
});
}
public sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
public restartProcess(process: debug.IProcess, restartData?: any): TPromise<any> {
return this.textFileService.saveAll().then(() => {
if (process.session.capabilities.supportsRestartRequest) {
return <TPromise>process.session.custom('restart', null);
}
const focusedProcess = this.viewModel.focusedProcess;
const preserveFocus = focusedProcess && process.getId() === focusedProcess.getId();
// Do not run preLaunch and postDebug tasks for automatic restarts
this.skipRunningTask = !!restartData;
return process.session.disconnect(true).then(() => {
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionHost') && process.session.root) {
return this.broadcastService.broadcast({
channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
return new TPromise<void>((c, e) => {
setTimeout(() => {
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let config = process.configuration;
const launch = process.session.root ? this.configurationManager.getLaunch(process.session.root.uri) : undefined;
if (this.launchJsonChanged && launch) {
this.launchJsonChanged = false;
config = launch.getConfiguration(process.configuration.name) || config;
// Take the type from the process since the debug extension might overwrite it #21316
config.type = process.configuration.type;
config.noDebug = process.configuration.noDebug;
}
config.__restart = restartData;
this.skipRunningTask = !!restartData;
this.startDebugging(launch, config).then(() => c(null), err => e(err));
}, 300);
});
}).then(() => {
if (preserveFocus) {
// Restart should preserve the focused process
const restartedProcess = this.model.getProcesses().filter(p => p.configuration.name === process.configuration.name).pop();
if (restartedProcess && restartedProcess !== this.viewModel.focusedProcess) {
this.focusStackFrame(undefined, undefined, restartedProcess);
}
}
});
});
}
public stopProcess(process: debug.IProcess): TPromise<any> {
if (process) {
return process.session.disconnect(false, true);
}
const processes = this.model.getProcesses();
if (processes.length) {
return TPromise.join(processes.map(p => p.session.disconnect(false, true)));
}
this.sessionStates.clear();
this._onDidChangeState.fire();
return undefined;
}
private onSessionEnd(session: RawDebugSession): void {
const bpsExist = this.model.getBreakpoints().length > 0;
const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('debugSessionStop', {
type: process && process.configuration.type,
success: session.emittedStopped || !bpsExist,
sessionLengthInSeconds: session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
this.model.removeProcess(session.getId());
if (process) {
process.inactive = true;
this._onDidEndProcess.fire(process);
if (process.configuration.postDebugTask) {
this.runTask(process.getId(), process.session.root, process.configuration.postDebugTask);
}
}
this.toDisposeOnSessionEnd.set(session.getId(), lifecycle.dispose(this.toDisposeOnSessionEnd.get(session.getId())));
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && focusedProcess.getId() === session.getId()) {
this.focusStackFrame(null);
}
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (this.model.getProcesses().length === 0) {
// set breakpoints back to unverified since the session ended.
const data: { [id: string]: { line: number, verified: boolean, column: number, endLine: number, endColumn: number } } = {};
this.model.getBreakpoints().forEach(bp => {
data[bp.getId()] = { line: bp.lineNumber, verified: false, column: bp.column, endLine: bp.endLineNumber, endColumn: bp.endColumn };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
this.debugType.reset();
this.viewModel.setMultiProcessView(false);
if (this.partService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);
}
}
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
private sendAllBreakpoints(process?: debug.IProcess): TPromise<any> {
return TPromise.join(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, process)))
.then(() => this.sendFunctionBreakpoints(process))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(process));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, targetProcess?: debug.IProcess): TPromise<void> {
const sendBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.uri.toString() === modelUri.toString());
const source = process.sources.get(modelUri.toString());
let rawSource: DebugProtocol.Source;
if (source) {
rawSource = source.raw;
} else {
const data = Source.getEncodedDebugData(modelUri);
rawSource = { name: data.name, path: data.path, sourceReference: data.sourceReference };
}
if (breakpointsToSend.length && !rawSource.adapterData) {
rawSource.adapterData = breakpointsToSend[0].adapterData;
}
// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
rawSource.path = normalizeDriveLetter(rawSource.path);
return session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.lineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.lineNumber, column: bp.column, condition: bp.condition, hitCondition: bp.hitCondition })),
sourceModified
}).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: DebugProtocol.Breakpoint } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
if (!breakpointsToSend[i].column) {
// If there was no column sent ignore the breakpoint column response from the adapter
data[breakpointsToSend[i].getId()].column = undefined;
}
}
this.model.updateBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendBreakpointsToProcess);
}
private sendFunctionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendFunctionBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || !session.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendFunctionBreakpointsToProcess);
}
private sendExceptionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendExceptionBreakpointsToProcess = (process: debug.IProcess): TPromise<any> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
};
return this.sendToOneOrAllProcesses(targetProcess, sendExceptionBreakpointsToProcess);
}
private sendToOneOrAllProcesses(process: debug.IProcess, send: (process: debug.IProcess) => TPromise<void>): TPromise<void> {
if (process) {
return send(process);
}
return TPromise.join(this.model.getProcesses().map(p => send(p))).then(() => void 0);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.has(event.resource.toString())) {
this.breakpointsToSendOnResourceSaved.delete(event.resource.toString());
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
if (event.resource.toString().indexOf('.vscode/launch.json') >= 0) {
this.launchJsonChanged = true;
}
});
}
private store(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
if (!this.model.areBreakpointsActivated()) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
public dispose(): void {
this.toDisposeOnSessionEnd.forEach(toDispose => lifecycle.dispose(toDispose));
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.9954462051391602,
0.02224523387849331,
0.00016591028543189168,
0.00023849673743825406,
0.14293062686920166
] |
{
"id": 0,
"code_window": [
"\t * Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.\n",
"\t * Also saves all files, manages if compounds are present in the configuration\n",
"\t * and resolveds configurations via DebugConfigurationProviders.\n",
"\t */\n",
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<any>;\n",
"\n",
"\t/**\n",
"\t * Restarts a process or creates a new one if there is no active session.\n",
"\t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<void>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 630
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"toggleGitViewlet": "显示 Git",
"source control": "源代码管理",
"toggleSCMViewlet": "显示源代码管理",
"view": "查看",
"scmConfigurationTitle": "源代码管理",
"alwaysShowProviders": "是否总是显示源代码管理提供程序部分。",
"diffDecorations": "控制编辑器中差异的显示效果。",
"diffGutterWidth": "控制导航线上已添加和已修改差异图标的宽度 (px)。"
} | i18n/chs/src/vs/workbench/parts/scm/electron-browser/scm.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.0001729256910039112,
0.00016992568271234632,
0.00016692567442078143,
0.00016992568271234632,
0.000003000008291564882
] |
{
"id": 0,
"code_window": [
"\t * Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.\n",
"\t * Also saves all files, manages if compounds are present in the configuration\n",
"\t * and resolveds configurations via DebugConfigurationProviders.\n",
"\t */\n",
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<any>;\n",
"\n",
"\t/**\n",
"\t * Restarts a process or creates a new one if there is no active session.\n",
"\t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<void>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 630
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"errorKeybindingsFileDirty": "Schreiben nicht möglich, da die Tastenbindungskonfiguration geändert wurde. Speichern Sie die Datei, und versuchen Sie es noch mal.",
"parseErrors": "In die configuration\n\nIn die Tastenbindungskonfigurationsdatei kann nicht geschrieben werden. Öffnen Sie die Datei, um Fehler/Warnungen darin zu beheben, und versuchen Sie es noch mal.",
"errorInvalidConfiguration": "In die Tastenbindungskonfigurationsdatei kann nicht geschrieben werden. Sie enthält ein Objekt, bei dem es sich nicht um ein Array handelt. Öffnen Sie die Datei, um das Problem zu beheben, und versuchen Sie es dann nochmal.",
"emptyKeybindingsHeader": "Platzieren Sie Ihre Tastenzuordnungen in dieser Datei, um die Standardwerte zu überschreiben."
} | i18n/deu/src/vs/workbench/services/keybinding/common/keybindingEditing.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017005065456032753,
0.0001686009345576167,
0.0001671512145549059,
0.0001686009345576167,
0.0000014497200027108192
] |
{
"id": 0,
"code_window": [
"\t * Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.\n",
"\t * Also saves all files, manages if compounds are present in the configuration\n",
"\t * and resolveds configurations via DebugConfigurationProviders.\n",
"\t */\n",
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<any>;\n",
"\n",
"\t/**\n",
"\t * Restarts a process or creates a new one if there is no active session.\n",
"\t */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tstartDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<void>;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debug.ts",
"type": "replace",
"edit_start_line_idx": 630
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"dirtyFile": "1 nem mentett fájl",
"dirtyFiles": "{0} nem mentett fájl"
} | i18n/hun/src/vs/workbench/parts/files/common/dirtyFilesTracker.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017322093481197953,
0.00017175757966469973,
0.00017029422451741993,
0.00017175757966469973,
0.000001463355147279799
] |
{
"id": 1,
"code_window": [
"\t\tthis.model.removeWatchExpressions(id);\n",
"\t}\n",
"\n",
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {\n",
"\n",
"\t\t// make sure to save all files and that the configuration is up to date\n",
"\t\treturn this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<void> {\n",
"\t\tconst sessionId = generateUuid();\n",
"\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\tconst wrapUpState = () => {\n",
"\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t}\n",
"\t\t};\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 683
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import * as resources from 'vs/base/common/resources';
import * as strings from 'vs/base/common/strings';
import { generateUuid } from 'vs/base/common/uuid';
import uri from 'vs/base/common/uri';
import * as platform from 'vs/base/common/platform';
import { first, distinct } from 'vs/base/common/arrays';
import { isObject, isUndefinedOrNull } from 'vs/base/common/types';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { TPromise } from 'vs/base/common/winjs.base';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import * as debug from 'vs/workbench/parts/debug/common/debug';
import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import { Model, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, RawObjectReplElement, ExpressionContainer, Process } from 'vs/workbench/parts/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/parts/debug/electron-browser/debugConfigurationManager';
import Constants from 'vs/workbench/parts/markers/electron-browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService';
import { TaskError } from 'vs/workbench/parts/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL, EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL, EXTENSION_RELOAD_BROADCAST_CHANNEL } from 'vs/platform/extensions/common/extensionHost';
import { IBroadcastService, IBroadcast } from 'vs/platform/broadcast/electron-browser/broadcastService';
import { IRemoteConsoleLog, parse, getFirstFrame } from 'vs/base/node/console';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { TaskEvent, TaskEventKind } from 'vs/workbench/parts/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { RunOnceScheduler } from 'vs/base/common/async';
import product from 'vs/platform/node/product';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private sessionStates: Map<string, debug.State>;
private readonly _onDidChangeState: Emitter<debug.State>;
private readonly _onDidNewProcess: Emitter<debug.IProcess>;
private readonly _onDidEndProcess: Emitter<debug.IProcess>;
private readonly _onDidCustomEvent: Emitter<debug.DebugEvent>;
private model: Model;
private viewModel: ViewModel;
private allProcesses: Map<string, debug.IProcess>;
private configurationManager: ConfigurationManager;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: Map<string, lifecycle.IDisposable[]>;
private inDebugMode: IContextKey<boolean>;
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private breakpointsToSendOnResourceSaved: Set<string>;
private launchJsonChanged: boolean;
private firstSessionStart: boolean;
private skipRunningTask: boolean;
private previousState: debug.State;
private fetchThreadsSchedulers: Map<string, RunOnceScheduler>;
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@INotificationService private notificationService: INotificationService,
@IDialogService private dialogService: IDialogService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@IBroadcastService private broadcastService: IBroadcastService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = new Map<string, lifecycle.IDisposable[]>();
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<debug.State>();
this._onDidNewProcess = new Emitter<debug.IProcess>();
this._onDidEndProcess = new Emitter<debug.IProcess>();
this._onDidCustomEvent = new Emitter<debug.DebugEvent>();
this.sessionStates = new Map<string, debug.State>();
this.allProcesses = new Map<string, debug.IProcess>();
this.fetchThreadsSchedulers = new Map<string, RunOnceScheduler>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
this.toDispose.push(this.configurationManager);
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.debugType = debug.CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = debug.CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.model = new Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.firstSessionStart = true;
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.store, this);
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.broadcastService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
const process = this.allProcesses.get(broadcast.payload.debugId);
if (!process) {
// Ignore attach events for sessions that never existed (wrong vscode windows)
return;
}
const session = <RawDebugSession>process.session;
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
process.configuration.request = 'attach';
process.configuration.port = broadcast.payload.port;
this.doCreateProcess(process.session.root, process.configuration, process.getId());
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
return;
}
// an extension logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: IRemoteConsoleLog = broadcast.payload.logEntry;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(extensionOutput);
let source: debug.IReplElementSource;
if (stack) {
const frame = getFirstFrame(stack);
if (frame) {
source = {
column: frame.column,
lineNumber: frame.line,
source: process.getSource({
name: resources.basenameOrAuthority(frame.uri),
path: frame.uri.fsPath
})
};
}
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev, source);
simpleVals = [];
}
// show object
this.logToRepl(new RawObjectReplElement((<any>a).prototype, a, undefined, nls.localize('snapshotObj', "Only primitive values are shown for this object.")), sev, source);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
// always append a new line for output coming from an extension such that separate logs go to separate lines #23695
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' ') + '\n', sev, source);
}
}
}
private tryToAutoFocusStackFrame(thread: debug.IThread): TPromise<any> {
const callStack = thread.getCallStack();
if (!callStack.length || (this.viewModel.focusedStackFrame && this.viewModel.focusedStackFrame.thread.getId() === thread.getId())) {
return TPromise.as(null);
}
// focus first stack frame from top that has source location if no other stack frame is focused
const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, undefined);
if (!stackFrameToFocus) {
return TPromise.as(null);
}
this.focusStackFrame(stackFrameToFocus);
if (thread.stoppedDetails) {
this.windowService.focusWindow();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", thread.stoppedDetails.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.range.startLineNumber));
}
return stackFrameToFocus.openInEditor(this.editorService, true);
}
private registerSessionListeners(process: Process, session: RawDebugSession): void {
this.toDisposeOnSessionEnd.get(session.getId()).push(session);
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
const sendConfigurationDone = () => {
if (session && session.capabilities.supportsConfigurationDoneRequest) {
return session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (session) {
session.disconnect().done(null, errors.onUnexpectedError);
}
this.notificationService.error(e.message);
});
}
};
this.sendAllBreakpoints(process).then(sendConfigurationDone, sendConfigurationDone)
.done(() => this.fetchThreads(session), errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidStop(event => {
this.updateStateAndEmit(session.getId(), debug.State.Stopped);
this.fetchThreads(session, event.body).done(() => {
const thread = process && process.getThread(event.body.threadId);
if (thread) {
// Call fetch call stack twice, the first only return the top stack frame.
// Second retrieves the rest of the call stack. For performance reasons #25605
this.model.fetchCallStack(thread).then(() => {
return this.tryToAutoFocusStackFrame(thread);
});
}
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidThread(event => {
if (event.body.reason === 'started') {
// debounce to reduce threadsRequest frequency and improve performance
let scheduler = this.fetchThreadsSchedulers.get(session.getId());
if (!scheduler) {
scheduler = new RunOnceScheduler(() => {
this.fetchThreads(session).done(undefined, errors.onUnexpectedError);
}, 100);
this.fetchThreadsSchedulers.set(session.getId(), scheduler);
this.toDisposeOnSessionEnd.get(session.getId()).push(scheduler);
}
if (!scheduler.isScheduled()) {
scheduler.schedule();
}
} else if (event.body.reason === 'exited') {
this.model.clearThreads(session.getId(), true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (session && session.getId() === event.sessionId) {
if (event.body && event.body.restart && process) {
this.restartProcess(process, event.body.restart).done(null, err => this.notificationService.error(err.message));
} else {
session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidContinued(event => {
const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
this.model.clearThreads(session.getId(), false, threadId);
if (this.viewModel.focusedProcess.getId() === session.getId()) {
this.focusStackFrame(undefined, this.viewModel.focusedThread, this.viewModel.focusedProcess);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
}));
let outputPromises: TPromise<void>[] = [];
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidOutput(event => {
if (!event.body) {
return;
}
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
if (event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (session.customTelemetryService && this.telemetryService.isOptedIn) {
// __GDPR__TODO__ We're sending events in the name of the debug adapter and we can not ensure that those are declared correctly.
session.customTelemetryService.publicLog(event.body.output, event.body.data);
}
return;
}
// Make sure to append output in the correct order by properly waiting on preivous promises #33822
const waitFor = outputPromises.slice();
const source = event.body.source ? {
lineNumber: event.body.line,
column: event.body.column,
source: process.getSource(event.body.source)
} : undefined;
if (event.body.variablesReference) {
const container = new ExpressionContainer(process, event.body.variablesReference, generateUuid());
outputPromises.push(container.getChildren().then(children => {
return TPromise.join(waitFor).then(() => children.forEach(child => {
// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
child.name = null;
this.logToRepl(child, outputSeverity, source);
}));
}));
} else if (typeof event.body.output === 'string') {
TPromise.join(waitFor).then(() => this.logToRepl(event.body.output, outputSeverity, source));
}
TPromise.join(outputPromises).then(() => outputPromises = []);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (event.body.reason === 'new' && event.body.breakpoint.source) {
const source = process.getSource(event.body.breakpoint.source);
const bps = this.model.addBreakpoints(source.uri, [{
column: event.body.breakpoint.column,
enabled: true,
lineNumber: event.body.breakpoint.line,
}], false);
if (bps.length === 1) {
this.model.updateBreakpoints({ [bps[0].getId()]: event.body.breakpoint });
}
}
if (event.body.reason === 'removed') {
if (breakpoint) {
this.model.removeBreakpoints([breakpoint]);
}
if (functionBreakpoint) {
this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
}
}
if (event.body.reason === 'changed') {
if (breakpoint) {
if (!breakpoint.column) {
event.body.breakpoint.column = undefined;
}
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
}
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionhost') && this.sessionStates.get(session.getId()) === debug.State.Running &&
process && process.session.root && process.configuration.noDebug) {
this.broadcastService.broadcast({
channel: EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
if (session && session.getId() === event.sessionId) {
this.onSessionEnd(session);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidCustomEvent(event => {
this._onDidCustomEvent.fire(event);
}));
}
private fetchThreads(session: RawDebugSession, stoppedDetails?: debug.IRawStoppedDetails): TPromise<any> {
return session.threads().then(response => {
if (response && response.body && response.body.threads) {
response.body.threads.forEach(thread => {
this.model.rawUpdate({
sessionId: session.getId(),
threadId: thread.id,
thread,
stoppedDetails: stoppedDetails && thread.id === stoppedDetails.threadId ? stoppedDetails : undefined
});
});
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.adapterData);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
const focusedThread = this.viewModel.focusedThread;
if (focusedThread && focusedThread.stopped) {
return debug.State.Stopped;
}
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && this.sessionStates.has(focusedProcess.getId())) {
return this.sessionStates.get(focusedProcess.getId());
}
if (this.sessionStates.size > 0) {
return debug.State.Initializing;
}
return debug.State.Inactive;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
public get onDidNewProcess(): Event<debug.IProcess> {
return this._onDidNewProcess.event;
}
public get onDidEndProcess(): Event<debug.IProcess> {
return this._onDidEndProcess.event;
}
public get onDidCustomEvent(): Event<debug.DebugEvent> {
return this._onDidCustomEvent.event;
}
private updateStateAndEmit(sessionId?: string, newState?: debug.State): void {
if (sessionId) {
if (newState === debug.State.Inactive) {
this.sessionStates.delete(sessionId);
} else {
this.sessionStates.set(sessionId, newState);
}
}
const state = this.state;
if (this.previousState !== state) {
const stateLabel = debug.State[state];
if (stateLabel) {
this.debugState.set(stateLabel.toLowerCase());
}
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
public focusStackFrame(stackFrame: debug.IStackFrame, thread?: debug.IThread, process?: debug.IProcess, explicit?: boolean): void {
if (!process) {
if (stackFrame || thread) {
process = stackFrame ? stackFrame.thread.process : thread.process;
} else {
const processes = this.model.getProcesses();
process = processes.length ? processes[0] : undefined;
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = process ? process.getAllThreads() : undefined;
thread = threads && threads.length ? threads[0] : undefined;
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = callStack && callStack.length ? callStack[0] : null;
}
}
this.viewModel.setFocus(stackFrame, thread, process, explicit);
this.updateStateAndEmit();
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
return this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(uri: uri, rawBreakpoints: debug.IBreakpointData[]): TPromise<void> {
this.model.addBreakpoints(uri, rawBreakpoints);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, uri.fsPath)));
return this.sendBreakpoints(uri);
}
public updateBreakpoints(uri: uri, data: { [id: string]: DebugProtocol.Breakpoint }, sendOnResourceSaved: boolean): void {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
this.sendBreakpoints(uri);
}
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
return this.model.addReplExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name)
// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
.then(() => this.focusStackFrame(this.viewModel.focusedStackFrame, this.viewModel.focusedThread, this.viewModel.focusedProcess));
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public logToRepl(value: string | debug.IExpression, sev = severity.Info, source?: debug.IReplElementSource): void {
if (typeof value === 'string' && '[2J'.localeCompare(value) === 0) {
// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
this.model.removeReplExpressions();
} else {
this.model.appendToRepl(value, sev, source);
}
}
public addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name);
this.viewModel.setSelectedExpression(we);
}
public renameWatchExpression(id: string, newName: string): void {
return this.model.renameWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, id, newName);
}
public moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
if (this.model.getProcesses().length === 0) {
this.removeReplExpressions();
this.allProcesses.clear();
this.model.getBreakpoints().forEach(bp => bp.verified = false);
}
this.launchJsonChanged = false;
let config: debug.IConfig, compound: debug.ICompound;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
if (!compound.configurations) {
return TPromise.wrapError(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return TPromise.join(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound.name) {
return TPromise.as(null);
}
let launchForName: debug.ILaunch;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return TPromise.wrapError(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return TPromise.wrapError(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
}
}
return this.startDebugging(launchForName, name, noDebug);
}));
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", configOrName) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return TPromise.wrapError(new Error(message));
}
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = <debug.IConfig>{};
}
if (noDebug) {
config.noDebug = true;
}
const sessionId = generateUuid();
this.updateStateAndEmit(sessionId, debug.State.Initializing);
const wrapUpState = () => {
if (this.sessionStates.get(sessionId) === debug.State.Initializing) {
this.updateStateAndEmit(sessionId, debug.State.Inactive);
}
};
return (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>
(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>
this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.createProcess(launch, config, sessionId);
}
if (launch) {
return launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);
}
})
).then(() => wrapUpState(), err => {
wrapUpState();
return <any>TPromise.wrapError(err);
}));
})
)));
}
private createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {
return this.textFileService.saveAll().then(() =>
(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return undefined;
}
if (!this.configurationManager.getAdapter(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message);
}
this.toDisposeOnSessionEnd.set(sessionId, []);
const workspace = launch ? launch.workspace : undefined;
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
});
return this.runTask(sessionId, workspace, resolvedConfig.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = resolvedConfig.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
}
const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", resolvedConfig.preLaunchTask, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => undefined);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}, err => {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved on disk and that you have a debug extension installed for that file type."));
}
return launch && launch.openConfigFile(false).then(editor => void 0);
})
);
}
private doCreateProcess(root: IWorkspaceFolder, configuration: debug.IConfig, sessionId: string): TPromise<debug.IProcess> {
configuration.__sessionId = sessionId;
this.inDebugMode.set(true);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const adapter = this.configurationManager.getAdapter(configuration.type);
const { aiKey, type } = adapter;
const publisher = adapter.extensionDescription.publisher;
let client: TelemetryClient;
let customTelemetryService: TelemetryService;
if (aiKey) {
client = new TelemetryClient(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${publisher}.${type}`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, customTelemetryService, root);
const process = this.model.addProcess(configuration, session);
this.allProcesses.set(process.getId(), process);
if (client) {
this.toDisposeOnSessionEnd.get(session.getId()).push(client);
}
this.registerSessionListeners(process, session);
return session.initialize({
clientID: 'vscode',
clientName: product.nameLong,
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true, // #10574
locale: platform.locale
}).then((result: DebugProtocol.InitializeResponse) => {
this.model.setExceptionBreakpoints(session.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (session.disconnected) {
return TPromise.as(null);
}
this.focusStackFrame(undefined, undefined, process);
this._onDidNewProcess.fire(process);
const internalConsoleOptions = configuration.internalConsoleOptions || this.configurationService.getValue<debug.IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const openDebugOptions = this.configurationService.getValue<debug.IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting
if (openDebugOptions === 'openOnSessionStart' || (openDebugOptions === 'openOnFirstSessionStart' && this.firstSessionStart)) {
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
this.firstSessionStart = false;
this.debugType.set(configuration.type);
if (this.model.getProcesses().length > 1) {
this.viewModel.setMultiProcessView(true);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: adapter.extensionDescription.id,
isBuiltin: adapter.extensionDescription.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<debug.IGlobalConfig>('launch', { resource: root.uri })
});
}).then(() => process, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
const errorMessage = error instanceof Error ? error.message : error;
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined, error: errorMessage });
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (!session.disconnected) {
session.disconnect().done(null, errors.onUnexpectedError);
} else if (process) {
this.model.removeProcess(process.getId());
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (this.model.getReplElements().length === 0) {
this.inDebugMode.reset();
}
this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []);
return undefined;
});
});
}
private showError(message: string, actions: IAction[] = []): TPromise<any> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
actions.push(configureAction);
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return TPromise.as(null);
});
}
private runTask(sessionId: string, root: IWorkspaceFolder, taskName: string): TPromise<ITaskSummary> {
if (!taskName || this.skipRunningTask) {
this.skipRunningTask = false;
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskName).then(task => {
if (!task) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the task \'{0}\'.", taskName)));
}
function once(kind: TaskEventKind, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (e.kind === kind) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return TPromise.as(null);
}
this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Active, this.taskService.onDidStateChange)(() => {
taskStarted = true;
})
);
const taskPromise = this.taskService.run(task);
if (task.isBackground) {
return new TPromise((c, e) => this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => c(null)))
);
}
return taskPromise;
});
return new TPromise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
e({ severity: severity.Error, message: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", taskName) });
}
}, 10000);
});
});
}
public sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
public restartProcess(process: debug.IProcess, restartData?: any): TPromise<any> {
return this.textFileService.saveAll().then(() => {
if (process.session.capabilities.supportsRestartRequest) {
return <TPromise>process.session.custom('restart', null);
}
const focusedProcess = this.viewModel.focusedProcess;
const preserveFocus = focusedProcess && process.getId() === focusedProcess.getId();
// Do not run preLaunch and postDebug tasks for automatic restarts
this.skipRunningTask = !!restartData;
return process.session.disconnect(true).then(() => {
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionHost') && process.session.root) {
return this.broadcastService.broadcast({
channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
return new TPromise<void>((c, e) => {
setTimeout(() => {
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let config = process.configuration;
const launch = process.session.root ? this.configurationManager.getLaunch(process.session.root.uri) : undefined;
if (this.launchJsonChanged && launch) {
this.launchJsonChanged = false;
config = launch.getConfiguration(process.configuration.name) || config;
// Take the type from the process since the debug extension might overwrite it #21316
config.type = process.configuration.type;
config.noDebug = process.configuration.noDebug;
}
config.__restart = restartData;
this.skipRunningTask = !!restartData;
this.startDebugging(launch, config).then(() => c(null), err => e(err));
}, 300);
});
}).then(() => {
if (preserveFocus) {
// Restart should preserve the focused process
const restartedProcess = this.model.getProcesses().filter(p => p.configuration.name === process.configuration.name).pop();
if (restartedProcess && restartedProcess !== this.viewModel.focusedProcess) {
this.focusStackFrame(undefined, undefined, restartedProcess);
}
}
});
});
}
public stopProcess(process: debug.IProcess): TPromise<any> {
if (process) {
return process.session.disconnect(false, true);
}
const processes = this.model.getProcesses();
if (processes.length) {
return TPromise.join(processes.map(p => p.session.disconnect(false, true)));
}
this.sessionStates.clear();
this._onDidChangeState.fire();
return undefined;
}
private onSessionEnd(session: RawDebugSession): void {
const bpsExist = this.model.getBreakpoints().length > 0;
const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('debugSessionStop', {
type: process && process.configuration.type,
success: session.emittedStopped || !bpsExist,
sessionLengthInSeconds: session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
this.model.removeProcess(session.getId());
if (process) {
process.inactive = true;
this._onDidEndProcess.fire(process);
if (process.configuration.postDebugTask) {
this.runTask(process.getId(), process.session.root, process.configuration.postDebugTask);
}
}
this.toDisposeOnSessionEnd.set(session.getId(), lifecycle.dispose(this.toDisposeOnSessionEnd.get(session.getId())));
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && focusedProcess.getId() === session.getId()) {
this.focusStackFrame(null);
}
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (this.model.getProcesses().length === 0) {
// set breakpoints back to unverified since the session ended.
const data: { [id: string]: { line: number, verified: boolean, column: number, endLine: number, endColumn: number } } = {};
this.model.getBreakpoints().forEach(bp => {
data[bp.getId()] = { line: bp.lineNumber, verified: false, column: bp.column, endLine: bp.endLineNumber, endColumn: bp.endColumn };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
this.debugType.reset();
this.viewModel.setMultiProcessView(false);
if (this.partService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);
}
}
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
private sendAllBreakpoints(process?: debug.IProcess): TPromise<any> {
return TPromise.join(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, process)))
.then(() => this.sendFunctionBreakpoints(process))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(process));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, targetProcess?: debug.IProcess): TPromise<void> {
const sendBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.uri.toString() === modelUri.toString());
const source = process.sources.get(modelUri.toString());
let rawSource: DebugProtocol.Source;
if (source) {
rawSource = source.raw;
} else {
const data = Source.getEncodedDebugData(modelUri);
rawSource = { name: data.name, path: data.path, sourceReference: data.sourceReference };
}
if (breakpointsToSend.length && !rawSource.adapterData) {
rawSource.adapterData = breakpointsToSend[0].adapterData;
}
// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
rawSource.path = normalizeDriveLetter(rawSource.path);
return session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.lineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.lineNumber, column: bp.column, condition: bp.condition, hitCondition: bp.hitCondition })),
sourceModified
}).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: DebugProtocol.Breakpoint } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
if (!breakpointsToSend[i].column) {
// If there was no column sent ignore the breakpoint column response from the adapter
data[breakpointsToSend[i].getId()].column = undefined;
}
}
this.model.updateBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendBreakpointsToProcess);
}
private sendFunctionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendFunctionBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || !session.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendFunctionBreakpointsToProcess);
}
private sendExceptionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendExceptionBreakpointsToProcess = (process: debug.IProcess): TPromise<any> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
};
return this.sendToOneOrAllProcesses(targetProcess, sendExceptionBreakpointsToProcess);
}
private sendToOneOrAllProcesses(process: debug.IProcess, send: (process: debug.IProcess) => TPromise<void>): TPromise<void> {
if (process) {
return send(process);
}
return TPromise.join(this.model.getProcesses().map(p => send(p))).then(() => void 0);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.has(event.resource.toString())) {
this.breakpointsToSendOnResourceSaved.delete(event.resource.toString());
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
if (event.resource.toString().indexOf('.vscode/launch.json') >= 0) {
this.launchJsonChanged = true;
}
});
}
private store(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
if (!this.model.areBreakpointsActivated()) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
public dispose(): void {
this.toDisposeOnSessionEnd.forEach(toDispose => lifecycle.dispose(toDispose));
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.9989215135574341,
0.02310982719063759,
0.00016439003229606897,
0.0002075767843052745,
0.14626222848892212
] |
{
"id": 1,
"code_window": [
"\t\tthis.model.removeWatchExpressions(id);\n",
"\t}\n",
"\n",
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {\n",
"\n",
"\t\t// make sure to save all files and that the configuration is up to date\n",
"\t\treturn this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<void> {\n",
"\t\tconst sessionId = generateUuid();\n",
"\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\tconst wrapUpState = () => {\n",
"\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t}\n",
"\t\t};\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 683
} | /*---------------------------------------------------------------------------------------------
* 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 { Event, Emitter, once } from 'vs/base/common/event';
import { Extensions, IEditorInputFactoryRegistry, EditorInput, toResource, IEditorStacksModel, IEditorGroup, IEditorIdentifier, IEditorCloseEvent, GroupIdentifier, IStacksModelChangeEvent, EditorOpenPositioning, SideBySideEditorInput, OPEN_POSITIONING_CONFIG } from 'vs/workbench/common/editor';
import URI from 'vs/base/common/uri';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { Position, Direction } from 'vs/platform/editor/common/editor';
import { ResourceMap } from 'vs/base/common/map';
export interface EditorCloseEvent extends IEditorCloseEvent {
editor: EditorInput;
}
export interface EditorIdentifier extends IEditorIdentifier {
group: EditorGroup;
editor: EditorInput;
}
export interface IEditorOpenOptions {
pinned?: boolean;
active?: boolean;
index?: number;
}
export interface ISerializedEditorInput {
id: string;
value: string;
}
export interface ISerializedEditorGroup {
label: string;
editors: ISerializedEditorInput[];
mru: number[];
preview: number;
}
export class EditorGroup implements IEditorGroup {
private static IDS = 0;
private _id: GroupIdentifier;
private _label: string;
private editors: EditorInput[];
private mru: EditorInput[];
private mapResourceToEditorCount: ResourceMap<number>;
private preview: EditorInput; // editor in preview state
private active: EditorInput; // editor in active state
private toDispose: IDisposable[];
private editorOpenPositioning: 'left' | 'right' | 'first' | 'last';
private readonly _onEditorActivated: Emitter<EditorInput>;
private readonly _onEditorOpened: Emitter<EditorInput>;
private readonly _onEditorClosed: Emitter<EditorCloseEvent>;
private readonly _onEditorDisposed: Emitter<EditorInput>;
private readonly _onEditorDirty: Emitter<EditorInput>;
private readonly _onEditorLabelChange: Emitter<EditorInput>;
private readonly _onEditorMoved: Emitter<EditorInput>;
private readonly _onEditorPinned: Emitter<EditorInput>;
private readonly _onEditorUnpinned: Emitter<EditorInput>;
private readonly _onEditorStateChanged: Emitter<EditorInput>;
private readonly _onEditorsStructureChanged: Emitter<EditorInput>;
constructor(
arg1: string | ISerializedEditorGroup,
@IInstantiationService private instantiationService: IInstantiationService,
@IConfigurationService private configurationService: IConfigurationService
) {
this._id = EditorGroup.IDS++;
this.editors = [];
this.mru = [];
this.toDispose = [];
this.mapResourceToEditorCount = new ResourceMap<number>();
this.onConfigurationUpdated();
this._onEditorActivated = new Emitter<EditorInput>();
this._onEditorOpened = new Emitter<EditorInput>();
this._onEditorClosed = new Emitter<EditorCloseEvent>();
this._onEditorDisposed = new Emitter<EditorInput>();
this._onEditorDirty = new Emitter<EditorInput>();
this._onEditorLabelChange = new Emitter<EditorInput>();
this._onEditorMoved = new Emitter<EditorInput>();
this._onEditorPinned = new Emitter<EditorInput>();
this._onEditorUnpinned = new Emitter<EditorInput>();
this._onEditorStateChanged = new Emitter<EditorInput>();
this._onEditorsStructureChanged = new Emitter<EditorInput>();
this.toDispose.push(this._onEditorActivated, this._onEditorOpened, this._onEditorClosed, this._onEditorDisposed, this._onEditorDirty, this._onEditorLabelChange, this._onEditorMoved, this._onEditorPinned, this._onEditorUnpinned, this._onEditorStateChanged, this._onEditorsStructureChanged);
if (typeof arg1 === 'object') {
this.deserialize(arg1);
} else {
this._label = arg1;
}
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e)));
}
private onConfigurationUpdated(event?: IConfigurationChangeEvent): void {
this.editorOpenPositioning = this.configurationService.getValue(OPEN_POSITIONING_CONFIG);
}
public get id(): GroupIdentifier {
return this._id;
}
public get label(): string {
return this._label;
}
public set label(label: string) {
this._label = label;
}
public get count(): number {
return this.editors.length;
}
public get onEditorActivated(): Event<EditorInput> {
return this._onEditorActivated.event;
}
public get onEditorOpened(): Event<EditorInput> {
return this._onEditorOpened.event;
}
public get onEditorClosed(): Event<EditorCloseEvent> {
return this._onEditorClosed.event;
}
public get onEditorDisposed(): Event<EditorInput> {
return this._onEditorDisposed.event;
}
public get onEditorDirty(): Event<EditorInput> {
return this._onEditorDirty.event;
}
public get onEditorLabelChange(): Event<EditorInput> {
return this._onEditorLabelChange.event;
}
public get onEditorMoved(): Event<EditorInput> {
return this._onEditorMoved.event;
}
public get onEditorPinned(): Event<EditorInput> {
return this._onEditorPinned.event;
}
public get onEditorUnpinned(): Event<EditorInput> {
return this._onEditorUnpinned.event;
}
public get onEditorStateChanged(): Event<EditorInput> {
return this._onEditorStateChanged.event;
}
public get onEditorsStructureChanged(): Event<EditorInput> {
return this._onEditorsStructureChanged.event;
}
public getEditors(mru?: boolean): EditorInput[] {
return mru ? this.mru.slice(0) : this.editors.slice(0);
}
public getEditor(index: number): EditorInput;
public getEditor(resource: URI): EditorInput;
public getEditor(arg1: any): EditorInput {
if (typeof arg1 === 'number') {
return this.editors[arg1];
}
const resource: URI = arg1;
if (!this.contains(resource)) {
return null; // fast check for resource opened or not
}
for (let i = 0; i < this.editors.length; i++) {
const editor = this.editors[i];
const editorResource = toResource(editor, { supportSideBySide: true });
if (editorResource && editorResource.toString() === resource.toString()) {
return editor;
}
}
return null;
}
public get activeEditor(): EditorInput {
return this.active;
}
public isActive(editor: EditorInput): boolean {
return this.matches(this.active, editor);
}
public get previewEditor(): EditorInput {
return this.preview;
}
public isPreview(editor: EditorInput): boolean {
return this.matches(this.preview, editor);
}
public openEditor(editor: EditorInput, options?: IEditorOpenOptions): void {
const index = this.indexOf(editor);
const makePinned = options && options.pinned;
const makeActive = (options && options.active) || !this.activeEditor || (!makePinned && this.matches(this.preview, this.activeEditor));
// New editor
if (index === -1) {
let targetIndex: number;
const indexOfActive = this.indexOf(this.active);
// Insert into specific position
if (options && typeof options.index === 'number') {
targetIndex = options.index;
}
// Insert to the BEGINNING
else if (this.editorOpenPositioning === EditorOpenPositioning.FIRST) {
targetIndex = 0;
}
// Insert to the END
else if (this.editorOpenPositioning === EditorOpenPositioning.LAST) {
targetIndex = this.editors.length;
}
// Insert to the LEFT of active editor
else if (this.editorOpenPositioning === EditorOpenPositioning.LEFT) {
if (indexOfActive === 0 || !this.editors.length) {
targetIndex = 0; // to the left becoming first editor in list
} else {
targetIndex = indexOfActive; // to the left of active editor
}
}
// Insert to the RIGHT of active editor
else {
targetIndex = indexOfActive + 1;
}
// Insert into our list of editors if pinned or we have no preview editor
if (makePinned || !this.preview) {
this.splice(targetIndex, false, editor);
}
// Handle preview
if (!makePinned) {
// Replace existing preview with this editor if we have a preview
if (this.preview) {
const indexOfPreview = this.indexOf(this.preview);
if (targetIndex > indexOfPreview) {
targetIndex--; // accomodate for the fact that the preview editor closes
}
this.replaceEditor(this.preview, editor, targetIndex, !makeActive);
}
this.preview = editor;
}
// Listeners
this.hookEditorListeners(editor);
// Event
this.fireEvent(this._onEditorOpened, editor, true);
// Handle active
if (makeActive) {
this.setActive(editor);
}
}
// Existing editor
else {
// Pin it
if (makePinned) {
this.pin(editor);
}
// Activate it
if (makeActive) {
this.setActive(editor);
}
// Respect index
if (options && typeof options.index === 'number') {
this.moveEditor(editor, options.index);
}
}
}
private hookEditorListeners(editor: EditorInput): void {
const unbind: IDisposable[] = [];
// Re-emit disposal of editor input as our own event
const onceDispose = once(editor.onDispose);
unbind.push(onceDispose(() => {
if (this.indexOf(editor) >= 0) {
this._onEditorDisposed.fire(editor);
}
}));
// Re-Emit dirty state changes
unbind.push(editor.onDidChangeDirty(() => {
this.fireEvent(this._onEditorDirty, editor, false);
}));
// Re-Emit label changes
unbind.push(editor.onDidChangeLabel(() => {
this.fireEvent(this._onEditorLabelChange, editor, false);
}));
// Clean up dispose listeners once the editor gets closed
unbind.push(this.onEditorClosed(event => {
if (event.editor.matches(editor)) {
dispose(unbind);
}
}));
}
private replaceEditor(toReplace: EditorInput, replaceWidth: EditorInput, replaceIndex: number, openNext = true): void {
const event = this.doCloseEditor(toReplace, openNext, true); // optimization to prevent multiple setActive() in one call
// We want to first add the new editor into our model before emitting the close event because
// firing the close event can trigger a dispose on the same editor that is now being added.
// This can lead into opening a disposed editor which is not what we want.
this.splice(replaceIndex, false, replaceWidth);
if (event) {
this.fireEvent(this._onEditorClosed, event, true);
}
}
public closeEditor(editor: EditorInput, openNext = true): void {
const event = this.doCloseEditor(editor, openNext, false);
if (event) {
this.fireEvent(this._onEditorClosed, event, true);
}
}
private doCloseEditor(editor: EditorInput, openNext: boolean, replaced: boolean): EditorCloseEvent {
const index = this.indexOf(editor);
if (index === -1) {
return null; // not found
}
// Active Editor closed
if (openNext && this.matches(this.active, editor)) {
// More than one editor
if (this.mru.length > 1) {
this.setActive(this.mru[1]); // active editor is always first in MRU, so pick second editor after as new active
}
// One Editor
else {
this.active = null;
}
}
// Preview Editor closed
if (this.matches(this.preview, editor)) {
this.preview = null;
}
// Remove from arrays
this.splice(index, true);
// Event
return { editor, replaced, index, group: this };
}
public closeEditors(except: EditorInput, direction?: Direction): void {
const index = this.indexOf(except);
if (index === -1) {
return; // not found
}
// Close to the left
if (direction === Direction.LEFT) {
for (let i = index - 1; i >= 0; i--) {
this.closeEditor(this.editors[i]);
}
}
// Close to the right
else if (direction === Direction.RIGHT) {
for (let i = this.editors.length - 1; i > index; i--) {
this.closeEditor(this.editors[i]);
}
}
// Both directions
else {
this.mru.filter(e => !this.matches(e, except)).forEach(e => this.closeEditor(e));
}
}
public closeAllEditors(): void {
// Optimize: close all non active editors first to produce less upstream work
this.mru.filter(e => !this.matches(e, this.active)).forEach(e => this.closeEditor(e));
this.closeEditor(this.active);
}
public moveEditor(editor: EditorInput, toIndex: number): void {
const index = this.indexOf(editor);
if (index < 0) {
return;
}
// Move
this.editors.splice(index, 1);
this.editors.splice(toIndex, 0, editor);
// Event
this.fireEvent(this._onEditorMoved, editor, true);
}
public setActive(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
if (this.matches(this.active, editor)) {
return; // already active
}
this.active = editor;
// Bring to front in MRU list
this.setMostRecentlyUsed(editor);
// Event
this.fireEvent(this._onEditorActivated, editor, false);
}
public pin(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
if (!this.isPreview(editor)) {
return; // can only pin a preview editor
}
// Convert the preview editor to be a pinned editor
this.preview = null;
// Event
this.fireEvent(this._onEditorPinned, editor, false);
}
public unpin(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
if (!this.isPinned(editor)) {
return; // can only unpin a pinned editor
}
// Set new
const oldPreview = this.preview;
this.preview = editor;
// Event
this.fireEvent(this._onEditorUnpinned, editor, false);
// Close old preview editor if any
this.closeEditor(oldPreview);
}
public isPinned(editor: EditorInput): boolean;
public isPinned(index: number): boolean;
public isPinned(arg1: EditorInput | number): boolean {
let editor: EditorInput;
let index: number;
if (typeof arg1 === 'number') {
editor = this.editors[arg1];
index = arg1;
} else {
editor = arg1;
index = this.indexOf(editor);
}
if (index === -1 || !editor) {
return false; // editor not found
}
if (!this.preview) {
return true; // no preview editor
}
return !this.matches(this.preview, editor);
}
private fireEvent(emitter: Emitter<EditorInput | EditorCloseEvent>, arg2: EditorInput | EditorCloseEvent, isStructuralChange: boolean): void {
emitter.fire(arg2);
if (isStructuralChange) {
this._onEditorsStructureChanged.fire(arg2 instanceof EditorInput ? arg2 : arg2.editor);
} else {
this._onEditorStateChanged.fire(arg2 instanceof EditorInput ? arg2 : arg2.editor);
}
}
private splice(index: number, del: boolean, editor?: EditorInput): void {
const editorToDeleteOrReplace = this.editors[index];
const args: any[] = [index, del ? 1 : 0];
if (editor) {
args.push(editor);
}
// Perform on editors array
this.editors.splice.apply(this.editors, args);
// Add
if (!del && editor) {
this.mru.push(editor); // make it LRU editor
this.updateResourceMap(editor, false /* add */); // add new to resource map
}
// Remove / Replace
else {
const indexInMRU = this.indexOf(editorToDeleteOrReplace, this.mru);
// Remove
if (del && !editor) {
this.mru.splice(indexInMRU, 1); // remove from MRU
this.updateResourceMap(editorToDeleteOrReplace, true /* delete */); // remove from resource map
}
// Replace
else {
this.mru.splice(indexInMRU, 1, editor); // replace MRU at location
this.updateResourceMap(editor, false /* add */); // add new to resource map
this.updateResourceMap(editorToDeleteOrReplace, true /* delete */); // remove replaced from resource map
}
}
}
private updateResourceMap(editor: EditorInput, remove: boolean): void {
const resource = toResource(editor, { supportSideBySide: true });
if (resource) {
// It is possible to have the same resource opened twice (once as normal input and once as diff input)
// So we need to do ref counting on the resource to provide the correct picture
let counter = this.mapResourceToEditorCount.get(resource) || 0;
let newCounter: number;
if (remove) {
if (counter > 1) {
newCounter = counter - 1;
}
} else {
newCounter = counter + 1;
}
this.mapResourceToEditorCount.set(resource, newCounter);
}
}
public indexOf(candidate: EditorInput, editors = this.editors): number {
if (!candidate) {
return -1;
}
for (let i = 0; i < editors.length; i++) {
if (this.matches(editors[i], candidate)) {
return i;
}
}
return -1;
}
public contains(editorOrResource: EditorInput | URI): boolean {
if (editorOrResource instanceof EditorInput) {
return this.indexOf(editorOrResource) >= 0;
}
const counter = this.mapResourceToEditorCount.get(editorOrResource);
return typeof counter === 'number' && counter > 0;
}
private setMostRecentlyUsed(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // editor not found
}
const mruIndex = this.indexOf(editor, this.mru);
// Remove old index
this.mru.splice(mruIndex, 1);
// Set editor to front
this.mru.unshift(editor);
}
private matches(editorA: EditorInput, editorB: EditorInput): boolean {
return !!editorA && !!editorB && editorA.matches(editorB);
}
public serialize(): ISerializedEditorGroup {
const registry = Registry.as<IEditorInputFactoryRegistry>(Extensions.EditorInputFactories);
// Serialize all editor inputs so that we can store them.
// Editors that cannot be serialized need to be ignored
// from mru, active and preview if any.
let serializableEditors: EditorInput[] = [];
let serializedEditors: ISerializedEditorInput[] = [];
let serializablePreviewIndex: number;
this.editors.forEach(e => {
let factory = registry.getEditorInputFactory(e.getTypeId());
if (factory) {
let value = factory.serialize(e);
if (typeof value === 'string') {
serializedEditors.push({ id: e.getTypeId(), value });
serializableEditors.push(e);
if (this.preview === e) {
serializablePreviewIndex = serializableEditors.length - 1;
}
}
}
});
const serializableMru = this.mru.map(e => this.indexOf(e, serializableEditors)).filter(i => i >= 0);
return {
label: this.label,
editors: serializedEditors,
mru: serializableMru,
preview: serializablePreviewIndex,
};
}
private deserialize(data: ISerializedEditorGroup): void {
const registry = Registry.as<IEditorInputFactoryRegistry>(Extensions.EditorInputFactories);
this._label = data.label;
this.editors = data.editors.map(e => {
const factory = registry.getEditorInputFactory(e.id);
if (factory) {
const editor = factory.deserialize(this.instantiationService, e.value);
this.hookEditorListeners(editor);
this.updateResourceMap(editor, false /* add */);
return editor;
}
return null;
}).filter(e => !!e);
this.mru = data.mru.map(i => this.editors[i]);
this.active = this.mru[0];
this.preview = this.editors[data.preview];
}
public dispose(): void {
dispose(this.toDispose);
}
}
interface ISerializedEditorStacksModel {
groups: ISerializedEditorGroup[];
active: number;
}
export class EditorStacksModel implements IEditorStacksModel {
private static readonly STORAGE_KEY = 'editorStacks.model';
private toDispose: IDisposable[];
private loaded: boolean;
private _groups: EditorGroup[];
private _activeGroup: EditorGroup;
private groupToIdentifier: { [id: number]: EditorGroup };
private readonly _onGroupOpened: Emitter<EditorGroup>;
private readonly _onGroupClosed: Emitter<EditorGroup>;
private readonly _onGroupMoved: Emitter<EditorGroup>;
private readonly _onGroupActivated: Emitter<EditorGroup>;
private readonly _onGroupDeactivated: Emitter<EditorGroup>;
private readonly _onGroupRenamed: Emitter<EditorGroup>;
private readonly _onEditorDisposed: Emitter<EditorIdentifier>;
private readonly _onEditorDirty: Emitter<EditorIdentifier>;
private readonly _onEditorLabelChange: Emitter<EditorIdentifier>;
private readonly _onEditorOpened: Emitter<EditorIdentifier>;
private readonly _onWillCloseEditor: Emitter<EditorCloseEvent>;
private readonly _onEditorClosed: Emitter<EditorCloseEvent>;
private readonly _onModelChanged: Emitter<IStacksModelChangeEvent>;
constructor(
private restoreFromStorage: boolean,
@IStorageService private storageService: IStorageService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService
) {
this.toDispose = [];
this._groups = [];
this.groupToIdentifier = Object.create(null);
this._onGroupOpened = new Emitter<EditorGroup>();
this._onGroupClosed = new Emitter<EditorGroup>();
this._onGroupActivated = new Emitter<EditorGroup>();
this._onGroupDeactivated = new Emitter<EditorGroup>();
this._onGroupMoved = new Emitter<EditorGroup>();
this._onGroupRenamed = new Emitter<EditorGroup>();
this._onModelChanged = new Emitter<IStacksModelChangeEvent>();
this._onEditorDisposed = new Emitter<EditorIdentifier>();
this._onEditorDirty = new Emitter<EditorIdentifier>();
this._onEditorLabelChange = new Emitter<EditorIdentifier>();
this._onEditorOpened = new Emitter<EditorIdentifier>();
this._onWillCloseEditor = new Emitter<EditorCloseEvent>();
this._onEditorClosed = new Emitter<EditorCloseEvent>();
this.toDispose.push(this._onGroupOpened, this._onGroupClosed, this._onGroupActivated, this._onGroupDeactivated, this._onGroupMoved, this._onGroupRenamed, this._onModelChanged, this._onEditorDisposed, this._onEditorDirty, this._onEditorLabelChange, this._onEditorOpened, this._onEditorClosed, this._onWillCloseEditor);
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.lifecycleService.onShutdown(reason => this.onShutdown()));
}
public get onGroupOpened(): Event<EditorGroup> {
return this._onGroupOpened.event;
}
public get onGroupClosed(): Event<EditorGroup> {
return this._onGroupClosed.event;
}
public get onGroupActivated(): Event<EditorGroup> {
return this._onGroupActivated.event;
}
public get onGroupDeactivated(): Event<EditorGroup> {
return this._onGroupDeactivated.event;
}
public get onGroupMoved(): Event<EditorGroup> {
return this._onGroupMoved.event;
}
public get onGroupRenamed(): Event<EditorGroup> {
return this._onGroupRenamed.event;
}
public get onModelChanged(): Event<IStacksModelChangeEvent> {
return this._onModelChanged.event;
}
public get onEditorDisposed(): Event<EditorIdentifier> {
return this._onEditorDisposed.event;
}
public get onEditorDirty(): Event<EditorIdentifier> {
return this._onEditorDirty.event;
}
public get onEditorLabelChange(): Event<EditorIdentifier> {
return this._onEditorLabelChange.event;
}
public get onEditorOpened(): Event<EditorIdentifier> {
return this._onEditorOpened.event;
}
public get onWillCloseEditor(): Event<EditorCloseEvent> {
return this._onWillCloseEditor.event;
}
public get onEditorClosed(): Event<EditorCloseEvent> {
return this._onEditorClosed.event;
}
public get groups(): EditorGroup[] {
this.ensureLoaded();
return this._groups.slice(0);
}
public get activeGroup(): EditorGroup {
this.ensureLoaded();
return this._activeGroup;
}
public isActive(group: EditorGroup): boolean {
return this.activeGroup === group;
}
public getGroup(id: GroupIdentifier): EditorGroup {
this.ensureLoaded();
return this.groupToIdentifier[id];
}
public openGroup(label: string, activate = true, index?: number): EditorGroup {
this.ensureLoaded();
const group = this.doCreateGroup(label);
// Direct index provided
if (typeof index === 'number') {
this._groups[index] = group;
}
// First group
else if (!this._activeGroup) {
this._groups.push(group);
}
// Subsequent group (open to the right of active one)
else {
this._groups.splice(this.indexOf(this._activeGroup) + 1, 0, group);
}
// Event
this.fireEvent(this._onGroupOpened, group, true);
// Activate if we are first or set to activate groups
if (!this._activeGroup || activate) {
this.setActive(group);
}
return group;
}
public renameGroup(group: EditorGroup, label: string): void {
this.ensureLoaded();
if (group.label !== label) {
group.label = label;
this.fireEvent(this._onGroupRenamed, group, false);
}
}
public closeGroup(group: EditorGroup): void {
this.ensureLoaded();
const index = this.indexOf(group);
if (index < 0) {
return; // group does not exist
}
// Active group closed: Find a new active one to the right
if (group === this._activeGroup) {
// More than one group
if (this._groups.length > 1) {
let newActiveGroup: EditorGroup;
if (this._groups.length > index + 1) {
newActiveGroup = this._groups[index + 1]; // make next group to the right active
} else {
newActiveGroup = this._groups[index - 1]; // make next group to the left active
}
this.setActive(newActiveGroup);
}
// One group
else {
this._activeGroup = null;
}
}
// Close Editors in Group first and dispose then
group.closeAllEditors();
group.dispose();
// Splice from groups
this._groups.splice(index, 1);
this.groupToIdentifier[group.id] = void 0;
// Events
this.fireEvent(this._onGroupClosed, group, true);
for (let i = index; i < this._groups.length; i++) {
this.fireEvent(this._onGroupMoved, this._groups[i], true); // send move event for groups to the right that moved to the left into the closed group position
}
}
public closeGroups(except?: EditorGroup): void {
this.ensureLoaded();
// Optimize: close all non active groups first to produce less upstream work
this.groups.filter(g => g !== this._activeGroup && g !== except).forEach(g => this.closeGroup(g));
// Close active unless configured to skip
if (this._activeGroup !== except) {
this.closeGroup(this._activeGroup);
}
}
public setActive(group: EditorGroup): void {
this.ensureLoaded();
if (this._activeGroup === group) {
return;
}
const oldActiveGroup = this._activeGroup;
this._activeGroup = group;
this.fireEvent(this._onGroupActivated, group, false);
if (oldActiveGroup) {
this.fireEvent(this._onGroupDeactivated, oldActiveGroup, false);
}
}
public moveGroup(group: EditorGroup, toIndex: number): void {
this.ensureLoaded();
const index = this.indexOf(group);
if (index < 0) {
return;
}
// Move
this._groups.splice(index, 1);
this._groups.splice(toIndex, 0, group);
// Event
for (let i = Math.min(index, toIndex); i <= Math.max(index, toIndex) && i < this._groups.length; i++) {
this.fireEvent(this._onGroupMoved, this._groups[i], true); // send move event for groups to the right that moved to the left into the closed group position
}
}
private indexOf(group: EditorGroup): number {
return this._groups.indexOf(group);
}
public findGroup(editor: EditorInput, activeOnly?: boolean): EditorGroup {
const groupsToCheck = (this.activeGroup ? [this.activeGroup] : []).concat(this.groups.filter(g => g !== this.activeGroup));
for (let i = 0; i < groupsToCheck.length; i++) {
const group = groupsToCheck[i];
const editorsToCheck = (group.activeEditor ? [group.activeEditor] : []).concat(group.getEditors().filter(e => e !== group.activeEditor));
for (let j = 0; j < editorsToCheck.length; j++) {
const editorToCheck = editorsToCheck[j];
if ((!activeOnly || group.isActive(editorToCheck)) && editor.matches(editorToCheck)) {
return group;
}
}
}
return void 0;
}
public positionOfGroup(group: IEditorGroup): Position;
public positionOfGroup(group: EditorGroup): Position;
public positionOfGroup(group: EditorGroup): Position {
return this.indexOf(group);
}
public groupAt(position: Position): EditorGroup {
this.ensureLoaded();
return this._groups[position];
}
public next(jumpGroups: boolean, cycleAtEnd = true): IEditorIdentifier {
this.ensureLoaded();
if (!this.activeGroup) {
return null;
}
const index = this.activeGroup.indexOf(this.activeGroup.activeEditor);
// Return next in group
if (index + 1 < this.activeGroup.count) {
return { group: this.activeGroup, editor: this.activeGroup.getEditor(index + 1) };
}
// Return first if we are not jumping groups
if (!jumpGroups) {
if (!cycleAtEnd) {
return null;
}
return { group: this.activeGroup, editor: this.activeGroup.getEditor(0) };
}
// Return first in next group
const indexOfGroup = this.indexOf(this.activeGroup);
const nextGroup = this.groups[indexOfGroup + 1];
if (nextGroup) {
return { group: nextGroup, editor: nextGroup.getEditor(0) };
}
// Return null if we are not cycling at the end
if (!cycleAtEnd) {
return null;
}
// Return first in first group
const firstGroup = this.groups[0];
return { group: firstGroup, editor: firstGroup.getEditor(0) };
}
public previous(jumpGroups: boolean, cycleAtStart = true): IEditorIdentifier {
this.ensureLoaded();
if (!this.activeGroup) {
return null;
}
const index = this.activeGroup.indexOf(this.activeGroup.activeEditor);
// Return previous in group
if (index > 0) {
return { group: this.activeGroup, editor: this.activeGroup.getEditor(index - 1) };
}
// Return last if we are not jumping groups
if (!jumpGroups) {
if (!cycleAtStart) {
return null;
}
return { group: this.activeGroup, editor: this.activeGroup.getEditor(this.activeGroup.count - 1) };
}
// Return last in previous group
const indexOfGroup = this.indexOf(this.activeGroup);
const previousGroup = this.groups[indexOfGroup - 1];
if (previousGroup) {
return { group: previousGroup, editor: previousGroup.getEditor(previousGroup.count - 1) };
}
// Return null if we are not cycling at the start
if (!cycleAtStart) {
return null;
}
// Return last in last group
const lastGroup = this.groups[this.groups.length - 1];
return { group: lastGroup, editor: lastGroup.getEditor(lastGroup.count - 1) };
}
public last(): IEditorIdentifier {
this.ensureLoaded();
if (!this.activeGroup) {
return null;
}
return { group: this.activeGroup, editor: this.activeGroup.getEditor(this.activeGroup.count - 1) };
}
private save(): void {
const serialized = this.serialize();
if (serialized.groups.length) {
this.storageService.store(EditorStacksModel.STORAGE_KEY, JSON.stringify(serialized), StorageScope.WORKSPACE);
} else {
this.storageService.remove(EditorStacksModel.STORAGE_KEY, StorageScope.WORKSPACE);
}
}
private serialize(): ISerializedEditorStacksModel {
// Exclude now empty groups (can happen if an editor cannot be serialized)
let serializableGroups = this._groups.map(g => g.serialize()).filter(g => g.editors.length > 0);
// Only consider active index if we do not have empty groups
let serializableActiveIndex: number;
if (serializableGroups.length > 0) {
if (serializableGroups.length === this._groups.length) {
serializableActiveIndex = this.indexOf(this._activeGroup);
} else {
serializableActiveIndex = 0;
}
}
return {
groups: serializableGroups,
active: serializableActiveIndex
};
}
private fireEvent(emitter: Emitter<EditorGroup>, group: EditorGroup, isStructuralChange: boolean): void {
emitter.fire(group);
this._onModelChanged.fire({ group, structural: isStructuralChange });
}
private ensureLoaded(): void {
if (!this.loaded) {
this.loaded = true;
this.load();
}
}
private load(): void {
if (!this.restoreFromStorage) {
return; // do not load from last session if the user explicitly asks to open a set of files
}
const modelRaw = this.storageService.get(EditorStacksModel.STORAGE_KEY, StorageScope.WORKSPACE);
if (modelRaw) {
const serialized: ISerializedEditorStacksModel = JSON.parse(modelRaw);
const invalidId = this.doValidate(serialized);
if (invalidId) {
console.warn(`Ignoring invalid stacks model (Error code: ${invalidId}): ${JSON.stringify(serialized)}`);
console.warn(serialized);
return;
}
this._groups = serialized.groups.map(s => this.doCreateGroup(s));
this._activeGroup = this._groups[serialized.active];
}
}
private doValidate(serialized: ISerializedEditorStacksModel): number {
if (!serialized.groups.length && typeof serialized.active === 'number') {
return 1; // Invalid active (we have no groups, but an active one)
}
if (serialized.groups.length && !serialized.groups[serialized.active]) {
return 2; // Invalid active (we cannot find the active one in group)
}
if (serialized.groups.length > 3) {
return 3; // Too many groups
}
if (serialized.groups.some(g => !g.editors.length)) {
return 4; // Some empty groups
}
if (serialized.groups.some(g => g.editors.length !== g.mru.length)) {
return 5; // MRU out of sync with editors
}
if (serialized.groups.some(g => typeof g.preview === 'number' && !g.editors[g.preview])) {
return 6; // Invalid preview editor
}
if (serialized.groups.some(g => !g.label)) {
return 7; // Group without label
}
return 0;
}
private doCreateGroup(arg1: string | ISerializedEditorGroup): EditorGroup {
const group = this.instantiationService.createInstance(EditorGroup, arg1);
this.groupToIdentifier[group.id] = group;
// Funnel editor changes in the group through our event aggregator
const unbind: IDisposable[] = [];
unbind.push(group.onEditorsStructureChanged(editor => this._onModelChanged.fire({ group, editor, structural: true })));
unbind.push(group.onEditorStateChanged(editor => this._onModelChanged.fire({ group, editor })));
unbind.push(group.onEditorOpened(editor => this._onEditorOpened.fire({ editor, group })));
unbind.push(group.onEditorClosed(event => {
this._onWillCloseEditor.fire(event);
this.handleOnEditorClosed(event);
this._onEditorClosed.fire(event);
}));
unbind.push(group.onEditorDisposed(editor => this._onEditorDisposed.fire({ editor, group })));
unbind.push(group.onEditorDirty(editor => this._onEditorDirty.fire({ editor, group })));
unbind.push(group.onEditorLabelChange(editor => this._onEditorLabelChange.fire({ editor, group })));
unbind.push(this.onGroupClosed(g => {
if (g === group) {
dispose(unbind);
}
}));
return group;
}
private handleOnEditorClosed(event: EditorCloseEvent): void {
const editor = event.editor;
const editorsToClose = [editor];
// Include both sides of side by side editors when being closed and not opened multiple times
if (editor instanceof SideBySideEditorInput && !this.isOpen(editor)) {
editorsToClose.push(editor.master, editor.details);
}
// Close the editor when it is no longer open in any group including diff editors
editorsToClose.forEach(editorToClose => {
const resource = editorToClose ? editorToClose.getResource() : void 0; // prefer resource to not close right-hand side editors of a diff editor
if (!this.isOpen(resource || editorToClose)) {
editorToClose.close();
}
});
}
public isOpen(editorOrResource: URI | EditorInput): boolean {
return this._groups.some(group => group.contains(editorOrResource));
}
public count(editor: EditorInput): number {
return this._groups.filter(group => group.contains(editor)).length;
}
private onShutdown(): void {
this.save();
dispose(this.toDispose);
}
public validate(): void {
const serialized = this.serialize();
const invalidId = this.doValidate(serialized);
if (invalidId) {
console.warn(`Ignoring invalid stacks model (Error code: ${invalidId}): ${JSON.stringify(serialized)}`);
console.warn(serialized);
} else {
console.log('Stacks Model OK!');
}
}
public toString(): string {
this.ensureLoaded();
const lines: string[] = [];
if (!this.groups.length) {
return '<No Groups>';
}
this.groups.forEach(g => {
let label = `Group: ${g.label}`;
if (this._activeGroup === g) {
label = `${label} [active]`;
}
lines.push(label);
g.getEditors().forEach(e => {
let label = `\t${e.getName()}`;
if (g.previewEditor === e) {
label = `${label} [preview]`;
}
if (g.activeEditor === e) {
label = `${label} [active]`;
}
lines.push(label);
});
});
return lines.join('\n');
}
} | src/vs/workbench/common/editor/editorStacksModel.ts | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.002489279955625534,
0.00019163354591000825,
0.00016291587962768972,
0.000172140309587121,
0.00020300946198403835
] |
{
"id": 1,
"code_window": [
"\t\tthis.model.removeWatchExpressions(id);\n",
"\t}\n",
"\n",
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {\n",
"\n",
"\t\t// make sure to save all files and that the configuration is up to date\n",
"\t\treturn this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<void> {\n",
"\t\tconst sessionId = generateUuid();\n",
"\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\tconst wrapUpState = () => {\n",
"\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t}\n",
"\t\t};\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 683
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"error": "Erreur",
"Unknown Dependency": "Dépendance inconnue :"
} | i18n/fra/src/vs/workbench/parts/extensions/browser/dependenciesViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017690801178105175,
0.0001757473946781829,
0.00017458677757531404,
0.0001757473946781829,
0.000001160617102868855
] |
{
"id": 1,
"code_window": [
"\t\tthis.model.removeWatchExpressions(id);\n",
"\t}\n",
"\n",
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {\n",
"\n",
"\t\t// make sure to save all files and that the configuration is up to date\n",
"\t\treturn this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<void> {\n",
"\t\tconst sessionId = generateUuid();\n",
"\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\tconst wrapUpState = () => {\n",
"\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t}\n",
"\t\t};\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 683
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"displayName": "Git",
"description": "Intégration Git SCM",
"command.clone": "Cloner",
"command.init": "Initialiser le dépôt",
"command.close": "Fermer le dépôt",
"command.refresh": "Actualiser",
"command.openChange": "Ouvrir les modifications",
"command.openFile": "Ouvrir le fichier",
"command.openHEADFile": "Ouvrir le fichier (HEAD)",
"command.stage": "Mettre en attente les modifications",
"command.stageAll": "Mettre en attente toutes les modifications",
"command.stageSelectedRanges": "Mettre en attente les plages sélectionnées",
"command.revertSelectedRanges": "Restaurer les portées sélectionnées",
"command.stageChange": "Mettre en attente la modification",
"command.revertChange": "Restaurer la modification",
"command.unstage": "Annuler la mise en attente des modifications",
"command.unstageAll": "Annuler la mise en attente de toutes les modifications",
"command.unstageSelectedRanges": "Annuler la mise en attente des plages sélectionnées",
"command.clean": "Ignorer les modifications",
"command.cleanAll": "Ignorer toutes les modifications",
"command.commit": "Commit",
"command.commitStaged": "Valider le contenu en zone de transit",
"command.commitStagedSigned": "Valider les modifications en attente (signé)",
"command.commitStagedAmend": "Valider les modifications en attente (modifier)",
"command.commitAll": "Valider tout",
"command.commitAllSigned": "Valider tout (signé)",
"command.commitAllAmend": "Tout Valider (Modifier)",
"command.undoCommit": "Annuler la dernière validation",
"command.checkout": "Extraire vers...",
"command.branch": "Créer une branche...",
"command.deleteBranch": "Supprimer la branche...",
"command.renameBranch": "Renommer la branche...",
"command.merge": "Fusionner la branche...",
"command.createTag": "Créer une étiquette",
"command.fetch": "Rappatrier",
"command.pull": "Pull",
"command.pullRebase": "Pull (rebaser)",
"command.pullFrom": "Extraire de...",
"command.push": "Push",
"command.pushTo": "Transfert (Push) vers...",
"command.pushWithTags": "Envoyer avec les Tags",
"command.sync": "Synchroniser",
"command.syncRebase": "Synchroniser (Rebase)",
"command.publish": "Publier la branche",
"command.showOutput": "Afficher la sortie Git",
"command.ignore": "Ajouter un fichier à .gitignore",
"command.stashIncludeUntracked": "Remiser (Inclure les non-tracés)",
"command.stash": "Remiser (stash)",
"command.stashPop": "Appliquer et supprimer la remise...",
"command.stashPopLatest": "Appliquer et supprimer la dernière remise",
"config.enabled": "Indique si git est activé",
"config.path": "Chemin d'accès à l'exécutable git",
"config.autoRepositoryDetection": "Si les dépôts doivent être détectés automatiquement",
"config.autorefresh": "Indique si l'actualisation automatique est activée",
"config.autofetch": "Indique si la récupération automatique est activée",
"config.enableLongCommitWarning": "Indique si les longs messages de validation doivent faire l'objet d'un avertissement",
"config.confirmSync": "Confirmer avant de synchroniser des dépôts git",
"config.countBadge": "Contrôle le compteur de badges Git. La valeur 'toutes' compte toutes les modifications. La valeur 'suivies' compte uniquement les modifications suivies. La valeur 'désactivé' désactive le compteur.",
"config.checkoutType": "Contrôle quel type de branches sont répertoriées pendant l'exécution de 'Extraire vers...'. `all` affiche toutes les références, `local` affiche uniquement les branches locales, `tags` affiche uniquement les balises et la valeur `remote` montre uniquement les branches distantes.",
"config.ignoreLegacyWarning": "Ignore l'avertissement Git hérité",
"config.ignoreMissingGitWarning": "Ignore l'avertissement quand Git est manquant",
"config.ignoreLimitWarning": "Ignore l'avertissement quand il y a trop de modifications dans un dépôt",
"config.defaultCloneDirectory": "Emplacement par défaut où cloner un dépôt git",
"config.enableSmartCommit": "Validez toutes les modifications en l'absence de modifications en attente.",
"config.enableCommitSigning": "Permet de valider en signant avec GPG.",
"config.discardAllScope": "Contrôle les modifications ignorées par la commande 'Ignorer toutes les modifications'. 'all' ignore toutes les modifications. 'tracked' ignore uniquement les fichiers suivis. 'prompt' affiche un message d'invite chaque fois que l’action est exécutée.",
"config.decorations.enabled": "Contrôle si Git contribue aux couleurs et aux badges de l’Explorateur et à l'affichage des éditeurs ouverts.",
"config.promptToSaveFilesBeforeCommit": "Contrôle si Git doit vérifier les fichiers non sauvegardés avant d'effectuer le commit.",
"config.showInlineOpenFileAction": "Contrôle s’il faut afficher une action Ouvrir le fichier dans l’affichage des modifications de Git.",
"config.inputValidation": "Contrôle quand afficher la validation de la saisie du message de commit.",
"config.detectSubmodules": "Contrôle s’il faut détecter automatiquement les sous-modules git.",
"colors.modified": "Couleur pour les ressources modifiées.",
"colors.deleted": "Couleur pour les ressources supprimées.",
"colors.untracked": "Couleur pour les ressources non tracées.",
"colors.ignored": "Couleur des ressources ignorées.",
"colors.conflict": "Couleur pour les ressources avec des conflits.",
"colors.submodule": "Couleur pour les ressources de sous-module."
} | i18n/fra/extensions/git/package.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017709264648146927,
0.00017307023517787457,
0.00016807658539619297,
0.00017324043437838554,
0.000003005775397468824
] |
{
"id": 2,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t\tif (noDebug) {\n",
"\t\t\t\t\tconfig.noDebug = true;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst sessionId = generateUuid();\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\t\t\tconst wrapUpState = () => {\n",
"\t\t\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t};\n",
"\n",
"\t\t\t\treturn (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>\n",
"\t\t\t\t\t(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>\n",
"\t\t\t\t\t\tthis.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {\n",
"\t\t\t\t\t\t\t// a falsy config indicates an aborted launch\n",
"\t\t\t\t\t\t\tif (config && config.type) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 761
} | /*---------------------------------------------------------------------------------------------
* 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 uri from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import severity from 'vs/base/common/severity';
import { Event } from 'vs/base/common/event';
import { IJSONSchemaSnippet } from 'vs/base/common/jsonSchema';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextModel as EditorIModel } from 'vs/editor/common/model';
import { IEditor } from 'vs/platform/editor/common/editor';
import { Position } from 'vs/editor/common/core/position';
import { ISuggestion } from 'vs/editor/common/modes';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { Range, IRange } from 'vs/editor/common/core/range';
import { RawContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
export const VIEWLET_ID = 'workbench.view.debug';
export const VARIABLES_VIEW_ID = 'workbench.debug.variablesView';
export const WATCH_VIEW_ID = 'workbench.debug.watchExpressionsView';
export const CALLSTACK_VIEW_ID = 'workbench.debug.callStackView';
export const BREAKPOINTS_VIEW_ID = 'workbench.debug.breakPointsView';
export const REPL_ID = 'workbench.panel.repl';
export const DEBUG_SERVICE_ID = 'debugService';
export const CONTEXT_DEBUG_TYPE = new RawContextKey<string>('debugType', undefined);
export const CONTEXT_DEBUG_STATE = new RawContextKey<string>('debugState', undefined);
export const CONTEXT_IN_DEBUG_MODE = new RawContextKey<boolean>('inDebugMode', false);
export const CONTEXT_NOT_IN_DEBUG_MODE: ContextKeyExpr = CONTEXT_IN_DEBUG_MODE.toNegated();
export const CONTEXT_IN_DEBUG_REPL = new RawContextKey<boolean>('inDebugRepl', false);
export const CONTEXT_NOT_IN_DEBUG_REPL: ContextKeyExpr = CONTEXT_IN_DEBUG_REPL.toNegated();
export const CONTEXT_ON_FIRST_DEBUG_REPL_LINE = new RawContextKey<boolean>('onFirstDebugReplLine', false);
export const CONTEXT_ON_LAST_DEBUG_REPL_LINE = new RawContextKey<boolean>('onLastDebugReplLine', false);
export const CONTEXT_BREAKPOINT_WIDGET_VISIBLE = new RawContextKey<boolean>('breakpointWidgetVisible', false);
export const CONTEXT_BREAKPOINTS_FOCUSED = new RawContextKey<boolean>('breakpointsFocused', true);
export const CONTEXT_WATCH_EXPRESSIONS_FOCUSED = new RawContextKey<boolean>('watchExpressionsFocused', true);
export const CONTEXT_VARIABLES_FOCUSED = new RawContextKey<boolean>('variablesFocused', true);
export const CONTEXT_EXPRESSION_SELECTED = new RawContextKey<boolean>('expressionSelected', false);
export const CONTEXT_BREAKPOINT_SELECTED = new RawContextKey<boolean>('breakpointSelected', false);
export const EDITOR_CONTRIBUTION_ID = 'editor.contrib.debug';
export const DEBUG_SCHEME = 'debug';
export const INTERNAL_CONSOLE_OPTIONS_SCHEMA = {
enum: ['neverOpen', 'openOnSessionStart', 'openOnFirstSessionStart'],
default: 'openOnFirstSessionStart',
description: nls.localize('internalConsoleOptions', "Controls behavior of the internal debug console.")
};
// raw
export interface IRawModelUpdate {
threadId: number;
sessionId: string;
thread?: DebugProtocol.Thread;
callStack?: DebugProtocol.StackFrame[];
stoppedDetails?: IRawStoppedDetails;
}
export interface IRawStoppedDetails {
reason: string;
description?: string;
threadId?: number;
text?: string;
totalFrames?: number;
allThreadsStopped?: boolean;
framesErrorMessage?: string;
}
// model
export interface ITreeElement {
getId(): string;
}
export interface IReplElement extends ITreeElement {
toString(): string;
sourceData?: IReplElementSource;
}
export interface IReplElementSource {
source: Source;
lineNumber: number;
column: number;
}
export interface IExpressionContainer extends ITreeElement {
hasChildren: boolean;
getChildren(): TPromise<IExpression[]>;
}
export interface IExpression extends IReplElement, IExpressionContainer {
name: string;
value: string;
valueChanged?: boolean;
type?: string;
}
export interface ISession {
root: IWorkspaceFolder;
stackTrace(args: DebugProtocol.StackTraceArguments): TPromise<DebugProtocol.StackTraceResponse>;
exceptionInfo(args: DebugProtocol.ExceptionInfoArguments): TPromise<DebugProtocol.ExceptionInfoResponse>;
scopes(args: DebugProtocol.ScopesArguments): TPromise<DebugProtocol.ScopesResponse>;
variables(args: DebugProtocol.VariablesArguments): TPromise<DebugProtocol.VariablesResponse>;
evaluate(args: DebugProtocol.EvaluateArguments): TPromise<DebugProtocol.EvaluateResponse>;
capabilities: DebugProtocol.Capabilities;
disconnect(restart?: boolean, force?: boolean): TPromise<DebugProtocol.DisconnectResponse>;
custom(request: string, args: any): TPromise<DebugProtocol.Response>;
onDidEvent: Event<DebugProtocol.Event>;
onDidInitialize: Event<DebugProtocol.InitializedEvent>;
onDidExitAdapter: Event<DebugEvent>;
restartFrame(args: DebugProtocol.RestartFrameArguments, threadId: number): TPromise<DebugProtocol.RestartFrameResponse>;
next(args: DebugProtocol.NextArguments): TPromise<DebugProtocol.NextResponse>;
stepIn(args: DebugProtocol.StepInArguments): TPromise<DebugProtocol.StepInResponse>;
stepOut(args: DebugProtocol.StepOutArguments): TPromise<DebugProtocol.StepOutResponse>;
continue(args: DebugProtocol.ContinueArguments): TPromise<DebugProtocol.ContinueResponse>;
pause(args: DebugProtocol.PauseArguments): TPromise<DebugProtocol.PauseResponse>;
stepBack(args: DebugProtocol.StepBackArguments): TPromise<DebugProtocol.StepBackResponse>;
reverseContinue(args: DebugProtocol.ReverseContinueArguments): TPromise<DebugProtocol.ReverseContinueResponse>;
completions(args: DebugProtocol.CompletionsArguments): TPromise<DebugProtocol.CompletionsResponse>;
setVariable(args: DebugProtocol.SetVariableArguments): TPromise<DebugProtocol.SetVariableResponse>;
source(args: DebugProtocol.SourceArguments): TPromise<DebugProtocol.SourceResponse>;
}
export enum ProcessState {
INACTIVE,
ATTACH,
LAUNCH
}
export interface IProcess extends ITreeElement {
getName(includeRoot: boolean): string;
configuration: IConfig;
session: ISession;
sources: Map<string, Source>;
state: ProcessState;
getThread(threadId: number): IThread;
getAllThreads(): IThread[];
getSource(raw: DebugProtocol.Source): Source;
completions(frameId: number, text: string, position: Position, overwriteBefore: number): TPromise<ISuggestion[]>;
}
export interface IThread extends ITreeElement {
/**
* Process the thread belongs to
*/
process: IProcess;
/**
* Id of the thread generated by the debug adapter backend.
*/
threadId: number;
/**
* Name of the thread.
*/
name: string;
/**
* Information about the current thread stop event. Null if thread is not stopped.
*/
stoppedDetails: IRawStoppedDetails;
/**
* Information about the exception if an 'exception' stopped event raised and DA supports the 'exceptionInfo' request, otherwise null.
*/
exceptionInfo: TPromise<IExceptionInfo>;
/**
* Gets the callstack if it has already been received from the debug
* adapter, otherwise it returns null.
*/
getCallStack(): IStackFrame[];
/**
* Invalidates the callstack cache
*/
clearCallStack(): void;
/**
* Indicates whether this thread is stopped. The callstack for stopped
* threads can be retrieved from the debug adapter.
*/
stopped: boolean;
next(): TPromise<any>;
stepIn(): TPromise<any>;
stepOut(): TPromise<any>;
stepBack(): TPromise<any>;
continue(): TPromise<any>;
pause(): TPromise<any>;
reverseContinue(): TPromise<any>;
}
export interface IScope extends IExpressionContainer {
name: string;
expensive: boolean;
range?: IRange;
}
export interface IStackFrame extends ITreeElement {
thread: IThread;
name: string;
presentationHint: string;
frameId: number;
range: IRange;
source: Source;
getScopes(): TPromise<IScope[]>;
getMostSpecificScopes(range: IRange): TPromise<IScope[]>;
restart(): TPromise<any>;
toString(): string;
openInEditor(editorService: IWorkbenchEditorService, preserveFocus?: boolean, sideBySide?: boolean): TPromise<any>;
}
export interface IEnablement extends ITreeElement {
enabled: boolean;
}
export interface IBreakpointData {
id?: string;
lineNumber: number;
column?: number;
enabled?: boolean;
condition?: string;
hitCondition?: string;
}
export interface IBreakpointUpdateData extends DebugProtocol.Breakpoint {
condition?: string;
hitCondition?: string;
}
export interface IBreakpoint extends IEnablement {
uri: uri;
lineNumber: number;
endLineNumber?: number;
column: number;
endColumn?: number;
condition: string;
hitCondition: string;
verified: boolean;
idFromAdapter: number;
message: string;
}
export interface IFunctionBreakpoint extends IEnablement {
name: string;
verified: boolean;
idFromAdapter: number;
hitCondition: string;
}
export interface IExceptionBreakpoint extends IEnablement {
filter: string;
label: string;
}
export interface IExceptionInfo {
id?: string;
description?: string;
breakMode: string;
details?: DebugProtocol.ExceptionDetails;
}
// model interfaces
export interface IViewModel extends ITreeElement {
/**
* Returns the focused debug process or null if no process is stopped.
*/
focusedProcess: IProcess;
/**
* Returns the focused thread or null if no thread is stopped.
*/
focusedThread: IThread;
/**
* Returns the focused stack frame or null if there are no stack frames.
*/
focusedStackFrame: IStackFrame;
getSelectedExpression(): IExpression;
getSelectedFunctionBreakpoint(): IFunctionBreakpoint;
setSelectedExpression(expression: IExpression): void;
setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void;
isMultiProcessView(): boolean;
onDidFocusProcess: Event<IProcess | undefined>;
onDidFocusStackFrame: Event<{ stackFrame: IStackFrame, explicit: boolean }>;
onDidSelectExpression: Event<IExpression>;
}
export interface IModel extends ITreeElement {
getProcesses(): IProcess[];
getBreakpoints(): IBreakpoint[];
areBreakpointsActivated(): boolean;
getFunctionBreakpoints(): IFunctionBreakpoint[];
getExceptionBreakpoints(): IExceptionBreakpoint[];
getWatchExpressions(): IExpression[];
getReplElements(): IReplElement[];
onDidChangeBreakpoints: Event<IBreakpointsChangeEvent>;
onDidChangeCallStack: Event<void>;
onDidChangeWatchExpressions: Event<IExpression>;
onDidChangeReplElements: Event<void>;
}
/**
* An event describing a change to the set of [breakpoints](#debug.Breakpoint).
*/
export interface IBreakpointsChangeEvent {
added?: (IBreakpoint | IFunctionBreakpoint)[];
removed?: (IBreakpoint | IFunctionBreakpoint)[];
changed?: (IBreakpoint | IFunctionBreakpoint)[];
}
// Debug enums
export enum State {
Inactive,
Initializing,
Stopped,
Running
}
// Debug configuration interfaces
export interface IDebugConfiguration {
allowBreakpointsEverywhere: boolean;
openDebug: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
openExplorerOnEnd: boolean;
inlineValues: boolean;
hideActionBar: boolean;
showInStatusBar: 'never' | 'always' | 'onFirstSessionStart';
internalConsoleOptions: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
}
export interface IGlobalConfig {
version: string;
compounds: ICompound[];
configurations: IConfig[];
}
export interface IEnvConfig {
name?: string;
type: string;
request: string;
internalConsoleOptions?: 'neverOpen' | 'openOnSessionStart' | 'openOnFirstSessionStart';
preLaunchTask?: string;
postDebugTask?: string;
__restart?: any;
__sessionId?: string;
debugServer?: number;
noDebug?: boolean;
port?: number;
}
export interface IConfig extends IEnvConfig {
windows?: IEnvConfig;
osx?: IEnvConfig;
linux?: IEnvConfig;
}
export interface ICompound {
name: string;
configurations: (string | { name: string, folder: string })[];
}
export interface IAdapterExecutable {
command?: string;
args?: string[];
}
export interface IRawEnvAdapter {
type?: string;
label?: string;
program?: string;
args?: string[];
runtime?: string;
runtimeArgs?: string[];
}
export interface IRawAdapter extends IRawEnvAdapter {
adapterExecutableCommand?: string;
enableBreakpointsFor?: { languageIds: string[] };
configurationAttributes?: any;
configurationSnippets?: IJSONSchemaSnippet[];
initialConfigurations?: any[];
languages?: string[];
variables?: { [key: string]: string };
aiKey?: string;
win?: IRawEnvAdapter;
winx86?: IRawEnvAdapter;
windows?: IRawEnvAdapter;
osx?: IRawEnvAdapter;
linux?: IRawEnvAdapter;
}
export interface IDebugConfigurationProvider {
type: string;
handle: number;
resolveDebugConfiguration?(folderUri: uri | undefined, debugConfiguration: IConfig): TPromise<IConfig>;
provideDebugConfigurations?(folderUri: uri | undefined): TPromise<IConfig[]>;
debugAdapterExecutable(folderUri: uri | undefined): TPromise<IAdapterExecutable>;
}
export interface IConfigurationManager {
/**
* Returns true if breakpoints can be set for a given editor model. Depends on mode.
*/
canSetBreakpointsIn(model: EditorIModel): boolean;
/**
* Returns an object containing the selected launch configuration and the selected configuration name. Both these fields can be null (no folder workspace).
*/
selectedConfiguration: {
launch: ILaunch;
name: string;
};
selectConfiguration(launch: ILaunch, name?: string, debugStarted?: boolean): void;
getLaunches(): ILaunch[];
getLaunch(workspaceUri: uri): ILaunch | undefined;
/**
* Allows to register on change of selected debug configuration.
*/
onDidSelectConfiguration: Event<void>;
registerDebugConfigurationProvider(handle: number, debugConfigurationProvider: IDebugConfigurationProvider): void;
unregisterDebugConfigurationProvider(handle: number): void;
resolveConfigurationByProviders(folderUri: uri | undefined, type: string | undefined, debugConfiguration: any): TPromise<any>;
debugAdapterExecutable(folderUri: uri | undefined, type: string): TPromise<IAdapterExecutable | undefined>;
}
export interface ILaunch {
/**
* Resource pointing to the launch.json this object is wrapping.
*/
uri: uri;
/**
* Name of the launch.
*/
name: string;
/**
* Workspace of the launch. Can be null.
*/
workspace: IWorkspaceFolder;
/**
* Should this launch be shown in the debug dropdown.
*/
hidden: boolean;
/**
* Returns a configuration with the specified name.
* Returns null if there is no configuration with the specified name.
*/
getConfiguration(name: string): IConfig;
/**
* Returns a compound with the specified name.
* Returns null if there is no compound with the specified name.
*/
getCompound(name: string): ICompound;
/**
* Returns the names of all configurations and compounds.
* Ignores configurations which are invalid.
*/
getConfigurationNames(includeCompounds?: boolean): string[];
/**
* Returns the resolved configuration.
* Replaces os specific values, system variables, interactive variables.
*/
resolveConfiguration(config: IConfig): TPromise<IConfig>;
/**
* Opens the launch.json file. Creates if it does not exist.
*/
openConfigFile(sideBySide: boolean, type?: string): TPromise<IEditor>;
}
// Debug service interfaces
export const IDebugService = createDecorator<IDebugService>(DEBUG_SERVICE_ID);
export interface DebugEvent extends DebugProtocol.Event {
sessionId?: string;
}
export interface IDebugService {
_serviceBrand: any;
/**
* Gets the current debug state.
*/
state: State;
/**
* Allows to register on debug state changes.
*/
onDidChangeState: Event<State>;
/**
* Allows to register on new process events.
*/
onDidNewProcess: Event<IProcess>;
/**
* Allows to register on end process events.
*/
onDidEndProcess: Event<IProcess>;
/**
* Allows to register on custom DAP events.
*/
onDidCustomEvent: Event<DebugEvent>;
/**
* Gets the current configuration manager.
*/
getConfigurationManager(): IConfigurationManager;
/**
* Sets the focused stack frame and evaluates all expressions against the newly focused stack frame,
*/
focusStackFrame(focusedStackFrame: IStackFrame, thread?: IThread, process?: IProcess, explicit?: boolean): void;
/**
* Adds new breakpoints to the model for the file specified with the uri. Notifies debug adapter of breakpoint changes.
*/
addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[]): TPromise<void>;
/**
* Updates the breakpoints.
*/
updateBreakpoints(uri: uri, data: { [id: string]: IBreakpointUpdateData }, sendOnResourceSaved: boolean): void;
/**
* Enables or disables all breakpoints. If breakpoint is passed only enables or disables the passed breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): TPromise<void>;
/**
* Sets the global activated property for all breakpoints.
* Notifies debug adapter of breakpoint changes.
*/
setBreakpointsActivated(activated: boolean): TPromise<void>;
/**
* Removes all breakpoints. If id is passed only removes the breakpoint associated with that id.
* Notifies debug adapter of breakpoint changes.
*/
removeBreakpoints(id?: string): TPromise<any>;
/**
* Adds a new function breakpoint for the given name.
*/
addFunctionBreakpoint(name?: string, id?: string): void;
/**
* Renames an already existing function breakpoint.
* Notifies debug adapter of breakpoint changes.
*/
renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void>;
/**
* Removes all function breakpoints. If id is passed only removes the function breakpoint with the passed id.
* Notifies debug adapter of breakpoint changes.
*/
removeFunctionBreakpoints(id?: string): TPromise<void>;
/**
* Adds a new expression to the repl.
*/
addReplExpression(name: string): TPromise<void>;
/**
* Removes all repl expressions.
*/
removeReplExpressions(): void;
/**
* Appends the passed string to the debug repl.
*/
logToRepl(value: string, sev?: severity): void;
/**
* Adds a new watch expression and evaluates it against the debug adapter.
*/
addWatchExpression(name?: string): void;
/**
* Renames a watch expression and evaluates it against the debug adapter.
*/
renameWatchExpression(id: string, newName: string): void;
/**
* Moves a watch expression to a new possition. Used for reordering watch expressions.
*/
moveWatchExpression(id: string, position: number): void;
/**
* Removes all watch expressions. If id is passed only removes the watch expression with the passed id.
*/
removeWatchExpressions(id?: string): void;
/**
* Starts debugging. If the configOrName is not passed uses the selected configuration in the debug dropdown.
* Also saves all files, manages if compounds are present in the configuration
* and resolveds configurations via DebugConfigurationProviders.
*/
startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug?: boolean): TPromise<any>;
/**
* Restarts a process or creates a new one if there is no active session.
*/
restartProcess(process: IProcess): TPromise<any>;
/**
* Stops the process. If the process does not exist then stops all processes.
*/
stopProcess(process: IProcess): TPromise<any>;
/**
* Makes unavailable all sources with the passed uri. Source will appear as grayed out in callstack view.
*/
sourceIsNotAvailable(uri: uri): void;
/**
* Gets the current debug model.
*/
getModel(): IModel;
/**
* Gets the current view model.
*/
getViewModel(): IViewModel;
}
// Editor interfaces
export interface IDebugEditorContribution extends IEditorContribution {
showHover(range: Range, focus: boolean): TPromise<void>;
showBreakpointWidget(lineNumber: number, column: number): void;
closeBreakpointWidget(): void;
addLaunchConfiguration(): TPromise<any>;
}
// utils
const _formatPIIRegexp = /{([^}]+)}/g;
export function formatPII(value: string, excludePII: boolean, args: { [key: string]: string }): string {
return value.replace(_formatPIIRegexp, function (match, group) {
if (excludePII && group.length > 0 && group[0] !== '_') {
return match;
}
return args && args.hasOwnProperty(group) ?
args[group] :
match;
});
}
| src/vs/workbench/parts/debug/common/debug.ts | 1 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.002951508155092597,
0.00028616044437512755,
0.00016116147162392735,
0.00016742380103096366,
0.0004297582490835339
] |
{
"id": 2,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t\tif (noDebug) {\n",
"\t\t\t\t\tconfig.noDebug = true;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst sessionId = generateUuid();\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\t\t\tconst wrapUpState = () => {\n",
"\t\t\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t};\n",
"\n",
"\t\t\t\treturn (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>\n",
"\t\t\t\t\t(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>\n",
"\t\t\t\t\t\tthis.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {\n",
"\t\t\t\t\t\t\t// a falsy config indicates an aborted launch\n",
"\t\t\t\t\t\t\tif (config && config.type) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 761
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"valid": "올바른 Git 리포지토리 URL을 입력하세요.",
"url": "리포지토리 URL",
"directory": "대상 복제 디렉터리",
"cloning": "'{0}' 리포지토리를 복제하는 중...",
"already exists": "대상 리포지토리가 이미 있습니다. 복제할 다른 디렉터리를 선택하세요."
} | i18n/kor/src/vs/workbench/parts/git/electron-browser/gitActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.0001707432820694521,
0.00016889537801034749,
0.0001670474885031581,
0.00016889537801034749,
0.0000018478967831470072
] |
{
"id": 2,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t\tif (noDebug) {\n",
"\t\t\t\t\tconfig.noDebug = true;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst sessionId = generateUuid();\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\t\t\tconst wrapUpState = () => {\n",
"\t\t\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t};\n",
"\n",
"\t\t\t\treturn (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>\n",
"\t\t\t\t\t(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>\n",
"\t\t\t\t\t\tthis.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {\n",
"\t\t\t\t\t\t\t// a falsy config indicates an aborted launch\n",
"\t\t\t\t\t\t\tif (config && config.type) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 761
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"focusSideBar": "Foco na Barra Lateral",
"viewCategory": "Exibir"
} | i18n/ptb/src/vs/workbench/browser/parts/sidebar/sidebarPart.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017640521400608122,
0.00016962250811047852,
0.0001628397876629606,
0.00016962250811047852,
0.000006782713171560317
] |
{
"id": 2,
"code_window": [
"\t\t\t\t}\n",
"\t\t\t\tif (noDebug) {\n",
"\t\t\t\t\tconfig.noDebug = true;\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\tconst sessionId = generateUuid();\n",
"\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Initializing);\n",
"\t\t\t\tconst wrapUpState = () => {\n",
"\t\t\t\t\tif (this.sessionStates.get(sessionId) === debug.State.Initializing) {\n",
"\t\t\t\t\t\tthis.updateStateAndEmit(sessionId, debug.State.Inactive);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t};\n",
"\n",
"\t\t\t\treturn (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>\n",
"\t\t\t\t\t(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>\n",
"\t\t\t\t\t\tthis.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {\n",
"\t\t\t\t\t\t\t// a falsy config indicates an aborted launch\n",
"\t\t\t\t\t\t\tif (config && config.type) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 761
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"renameAriaLabel": "為輸入重新命名。請鍵入新名稱,然後按 Enter 以認可。"
} | i18n/cht/src/vs/editor/contrib/rename/renameInputField.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017653814575169235,
0.00016941234935075045,
0.00016228655294980854,
0.00016941234935075045,
0.000007125796400941908
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t\t\tif (launch) {\n",
"\t\t\t\t\t\t\t\treturn launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);\n",
"\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t})\n",
"\t\t\t\t\t).then(() => wrapUpState(), err => {\n",
"\t\t\t\t\t\twrapUpState();\n",
"\t\t\t\t\t\treturn <any>TPromise.wrapError(err);\n",
"\t\t\t\t\t}));\n",
"\t\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t)).then(() => undefined);\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 781
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import * as resources from 'vs/base/common/resources';
import * as strings from 'vs/base/common/strings';
import { generateUuid } from 'vs/base/common/uuid';
import uri from 'vs/base/common/uri';
import * as platform from 'vs/base/common/platform';
import { first, distinct } from 'vs/base/common/arrays';
import { isObject, isUndefinedOrNull } from 'vs/base/common/types';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { TPromise } from 'vs/base/common/winjs.base';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import * as debug from 'vs/workbench/parts/debug/common/debug';
import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import { Model, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, RawObjectReplElement, ExpressionContainer, Process } from 'vs/workbench/parts/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/parts/debug/electron-browser/debugConfigurationManager';
import Constants from 'vs/workbench/parts/markers/electron-browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService';
import { TaskError } from 'vs/workbench/parts/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL, EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL, EXTENSION_RELOAD_BROADCAST_CHANNEL } from 'vs/platform/extensions/common/extensionHost';
import { IBroadcastService, IBroadcast } from 'vs/platform/broadcast/electron-browser/broadcastService';
import { IRemoteConsoleLog, parse, getFirstFrame } from 'vs/base/node/console';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { TaskEvent, TaskEventKind } from 'vs/workbench/parts/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { RunOnceScheduler } from 'vs/base/common/async';
import product from 'vs/platform/node/product';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private sessionStates: Map<string, debug.State>;
private readonly _onDidChangeState: Emitter<debug.State>;
private readonly _onDidNewProcess: Emitter<debug.IProcess>;
private readonly _onDidEndProcess: Emitter<debug.IProcess>;
private readonly _onDidCustomEvent: Emitter<debug.DebugEvent>;
private model: Model;
private viewModel: ViewModel;
private allProcesses: Map<string, debug.IProcess>;
private configurationManager: ConfigurationManager;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: Map<string, lifecycle.IDisposable[]>;
private inDebugMode: IContextKey<boolean>;
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private breakpointsToSendOnResourceSaved: Set<string>;
private launchJsonChanged: boolean;
private firstSessionStart: boolean;
private skipRunningTask: boolean;
private previousState: debug.State;
private fetchThreadsSchedulers: Map<string, RunOnceScheduler>;
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@INotificationService private notificationService: INotificationService,
@IDialogService private dialogService: IDialogService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@IBroadcastService private broadcastService: IBroadcastService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = new Map<string, lifecycle.IDisposable[]>();
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<debug.State>();
this._onDidNewProcess = new Emitter<debug.IProcess>();
this._onDidEndProcess = new Emitter<debug.IProcess>();
this._onDidCustomEvent = new Emitter<debug.DebugEvent>();
this.sessionStates = new Map<string, debug.State>();
this.allProcesses = new Map<string, debug.IProcess>();
this.fetchThreadsSchedulers = new Map<string, RunOnceScheduler>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
this.toDispose.push(this.configurationManager);
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.debugType = debug.CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = debug.CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.model = new Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.firstSessionStart = true;
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.store, this);
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.broadcastService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
const process = this.allProcesses.get(broadcast.payload.debugId);
if (!process) {
// Ignore attach events for sessions that never existed (wrong vscode windows)
return;
}
const session = <RawDebugSession>process.session;
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
process.configuration.request = 'attach';
process.configuration.port = broadcast.payload.port;
this.doCreateProcess(process.session.root, process.configuration, process.getId());
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
return;
}
// an extension logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: IRemoteConsoleLog = broadcast.payload.logEntry;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(extensionOutput);
let source: debug.IReplElementSource;
if (stack) {
const frame = getFirstFrame(stack);
if (frame) {
source = {
column: frame.column,
lineNumber: frame.line,
source: process.getSource({
name: resources.basenameOrAuthority(frame.uri),
path: frame.uri.fsPath
})
};
}
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev, source);
simpleVals = [];
}
// show object
this.logToRepl(new RawObjectReplElement((<any>a).prototype, a, undefined, nls.localize('snapshotObj', "Only primitive values are shown for this object.")), sev, source);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
// always append a new line for output coming from an extension such that separate logs go to separate lines #23695
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' ') + '\n', sev, source);
}
}
}
private tryToAutoFocusStackFrame(thread: debug.IThread): TPromise<any> {
const callStack = thread.getCallStack();
if (!callStack.length || (this.viewModel.focusedStackFrame && this.viewModel.focusedStackFrame.thread.getId() === thread.getId())) {
return TPromise.as(null);
}
// focus first stack frame from top that has source location if no other stack frame is focused
const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, undefined);
if (!stackFrameToFocus) {
return TPromise.as(null);
}
this.focusStackFrame(stackFrameToFocus);
if (thread.stoppedDetails) {
this.windowService.focusWindow();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", thread.stoppedDetails.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.range.startLineNumber));
}
return stackFrameToFocus.openInEditor(this.editorService, true);
}
private registerSessionListeners(process: Process, session: RawDebugSession): void {
this.toDisposeOnSessionEnd.get(session.getId()).push(session);
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
const sendConfigurationDone = () => {
if (session && session.capabilities.supportsConfigurationDoneRequest) {
return session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (session) {
session.disconnect().done(null, errors.onUnexpectedError);
}
this.notificationService.error(e.message);
});
}
};
this.sendAllBreakpoints(process).then(sendConfigurationDone, sendConfigurationDone)
.done(() => this.fetchThreads(session), errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidStop(event => {
this.updateStateAndEmit(session.getId(), debug.State.Stopped);
this.fetchThreads(session, event.body).done(() => {
const thread = process && process.getThread(event.body.threadId);
if (thread) {
// Call fetch call stack twice, the first only return the top stack frame.
// Second retrieves the rest of the call stack. For performance reasons #25605
this.model.fetchCallStack(thread).then(() => {
return this.tryToAutoFocusStackFrame(thread);
});
}
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidThread(event => {
if (event.body.reason === 'started') {
// debounce to reduce threadsRequest frequency and improve performance
let scheduler = this.fetchThreadsSchedulers.get(session.getId());
if (!scheduler) {
scheduler = new RunOnceScheduler(() => {
this.fetchThreads(session).done(undefined, errors.onUnexpectedError);
}, 100);
this.fetchThreadsSchedulers.set(session.getId(), scheduler);
this.toDisposeOnSessionEnd.get(session.getId()).push(scheduler);
}
if (!scheduler.isScheduled()) {
scheduler.schedule();
}
} else if (event.body.reason === 'exited') {
this.model.clearThreads(session.getId(), true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (session && session.getId() === event.sessionId) {
if (event.body && event.body.restart && process) {
this.restartProcess(process, event.body.restart).done(null, err => this.notificationService.error(err.message));
} else {
session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidContinued(event => {
const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
this.model.clearThreads(session.getId(), false, threadId);
if (this.viewModel.focusedProcess.getId() === session.getId()) {
this.focusStackFrame(undefined, this.viewModel.focusedThread, this.viewModel.focusedProcess);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
}));
let outputPromises: TPromise<void>[] = [];
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidOutput(event => {
if (!event.body) {
return;
}
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
if (event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (session.customTelemetryService && this.telemetryService.isOptedIn) {
// __GDPR__TODO__ We're sending events in the name of the debug adapter and we can not ensure that those are declared correctly.
session.customTelemetryService.publicLog(event.body.output, event.body.data);
}
return;
}
// Make sure to append output in the correct order by properly waiting on preivous promises #33822
const waitFor = outputPromises.slice();
const source = event.body.source ? {
lineNumber: event.body.line,
column: event.body.column,
source: process.getSource(event.body.source)
} : undefined;
if (event.body.variablesReference) {
const container = new ExpressionContainer(process, event.body.variablesReference, generateUuid());
outputPromises.push(container.getChildren().then(children => {
return TPromise.join(waitFor).then(() => children.forEach(child => {
// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
child.name = null;
this.logToRepl(child, outputSeverity, source);
}));
}));
} else if (typeof event.body.output === 'string') {
TPromise.join(waitFor).then(() => this.logToRepl(event.body.output, outputSeverity, source));
}
TPromise.join(outputPromises).then(() => outputPromises = []);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (event.body.reason === 'new' && event.body.breakpoint.source) {
const source = process.getSource(event.body.breakpoint.source);
const bps = this.model.addBreakpoints(source.uri, [{
column: event.body.breakpoint.column,
enabled: true,
lineNumber: event.body.breakpoint.line,
}], false);
if (bps.length === 1) {
this.model.updateBreakpoints({ [bps[0].getId()]: event.body.breakpoint });
}
}
if (event.body.reason === 'removed') {
if (breakpoint) {
this.model.removeBreakpoints([breakpoint]);
}
if (functionBreakpoint) {
this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
}
}
if (event.body.reason === 'changed') {
if (breakpoint) {
if (!breakpoint.column) {
event.body.breakpoint.column = undefined;
}
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
}
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionhost') && this.sessionStates.get(session.getId()) === debug.State.Running &&
process && process.session.root && process.configuration.noDebug) {
this.broadcastService.broadcast({
channel: EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
if (session && session.getId() === event.sessionId) {
this.onSessionEnd(session);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidCustomEvent(event => {
this._onDidCustomEvent.fire(event);
}));
}
private fetchThreads(session: RawDebugSession, stoppedDetails?: debug.IRawStoppedDetails): TPromise<any> {
return session.threads().then(response => {
if (response && response.body && response.body.threads) {
response.body.threads.forEach(thread => {
this.model.rawUpdate({
sessionId: session.getId(),
threadId: thread.id,
thread,
stoppedDetails: stoppedDetails && thread.id === stoppedDetails.threadId ? stoppedDetails : undefined
});
});
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.adapterData);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
const focusedThread = this.viewModel.focusedThread;
if (focusedThread && focusedThread.stopped) {
return debug.State.Stopped;
}
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && this.sessionStates.has(focusedProcess.getId())) {
return this.sessionStates.get(focusedProcess.getId());
}
if (this.sessionStates.size > 0) {
return debug.State.Initializing;
}
return debug.State.Inactive;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
public get onDidNewProcess(): Event<debug.IProcess> {
return this._onDidNewProcess.event;
}
public get onDidEndProcess(): Event<debug.IProcess> {
return this._onDidEndProcess.event;
}
public get onDidCustomEvent(): Event<debug.DebugEvent> {
return this._onDidCustomEvent.event;
}
private updateStateAndEmit(sessionId?: string, newState?: debug.State): void {
if (sessionId) {
if (newState === debug.State.Inactive) {
this.sessionStates.delete(sessionId);
} else {
this.sessionStates.set(sessionId, newState);
}
}
const state = this.state;
if (this.previousState !== state) {
const stateLabel = debug.State[state];
if (stateLabel) {
this.debugState.set(stateLabel.toLowerCase());
}
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
public focusStackFrame(stackFrame: debug.IStackFrame, thread?: debug.IThread, process?: debug.IProcess, explicit?: boolean): void {
if (!process) {
if (stackFrame || thread) {
process = stackFrame ? stackFrame.thread.process : thread.process;
} else {
const processes = this.model.getProcesses();
process = processes.length ? processes[0] : undefined;
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = process ? process.getAllThreads() : undefined;
thread = threads && threads.length ? threads[0] : undefined;
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = callStack && callStack.length ? callStack[0] : null;
}
}
this.viewModel.setFocus(stackFrame, thread, process, explicit);
this.updateStateAndEmit();
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
return this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(uri: uri, rawBreakpoints: debug.IBreakpointData[]): TPromise<void> {
this.model.addBreakpoints(uri, rawBreakpoints);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, uri.fsPath)));
return this.sendBreakpoints(uri);
}
public updateBreakpoints(uri: uri, data: { [id: string]: DebugProtocol.Breakpoint }, sendOnResourceSaved: boolean): void {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
this.sendBreakpoints(uri);
}
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
return this.model.addReplExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name)
// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
.then(() => this.focusStackFrame(this.viewModel.focusedStackFrame, this.viewModel.focusedThread, this.viewModel.focusedProcess));
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public logToRepl(value: string | debug.IExpression, sev = severity.Info, source?: debug.IReplElementSource): void {
if (typeof value === 'string' && '[2J'.localeCompare(value) === 0) {
// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
this.model.removeReplExpressions();
} else {
this.model.appendToRepl(value, sev, source);
}
}
public addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name);
this.viewModel.setSelectedExpression(we);
}
public renameWatchExpression(id: string, newName: string): void {
return this.model.renameWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, id, newName);
}
public moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
if (this.model.getProcesses().length === 0) {
this.removeReplExpressions();
this.allProcesses.clear();
this.model.getBreakpoints().forEach(bp => bp.verified = false);
}
this.launchJsonChanged = false;
let config: debug.IConfig, compound: debug.ICompound;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
if (!compound.configurations) {
return TPromise.wrapError(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return TPromise.join(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound.name) {
return TPromise.as(null);
}
let launchForName: debug.ILaunch;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return TPromise.wrapError(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return TPromise.wrapError(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
}
}
return this.startDebugging(launchForName, name, noDebug);
}));
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", configOrName) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return TPromise.wrapError(new Error(message));
}
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = <debug.IConfig>{};
}
if (noDebug) {
config.noDebug = true;
}
const sessionId = generateUuid();
this.updateStateAndEmit(sessionId, debug.State.Initializing);
const wrapUpState = () => {
if (this.sessionStates.get(sessionId) === debug.State.Initializing) {
this.updateStateAndEmit(sessionId, debug.State.Inactive);
}
};
return (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>
(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>
this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.createProcess(launch, config, sessionId);
}
if (launch) {
return launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);
}
})
).then(() => wrapUpState(), err => {
wrapUpState();
return <any>TPromise.wrapError(err);
}));
})
)));
}
private createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {
return this.textFileService.saveAll().then(() =>
(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return undefined;
}
if (!this.configurationManager.getAdapter(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message);
}
this.toDisposeOnSessionEnd.set(sessionId, []);
const workspace = launch ? launch.workspace : undefined;
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
});
return this.runTask(sessionId, workspace, resolvedConfig.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = resolvedConfig.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
}
const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", resolvedConfig.preLaunchTask, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => undefined);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}, err => {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved on disk and that you have a debug extension installed for that file type."));
}
return launch && launch.openConfigFile(false).then(editor => void 0);
})
);
}
private doCreateProcess(root: IWorkspaceFolder, configuration: debug.IConfig, sessionId: string): TPromise<debug.IProcess> {
configuration.__sessionId = sessionId;
this.inDebugMode.set(true);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const adapter = this.configurationManager.getAdapter(configuration.type);
const { aiKey, type } = adapter;
const publisher = adapter.extensionDescription.publisher;
let client: TelemetryClient;
let customTelemetryService: TelemetryService;
if (aiKey) {
client = new TelemetryClient(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${publisher}.${type}`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, customTelemetryService, root);
const process = this.model.addProcess(configuration, session);
this.allProcesses.set(process.getId(), process);
if (client) {
this.toDisposeOnSessionEnd.get(session.getId()).push(client);
}
this.registerSessionListeners(process, session);
return session.initialize({
clientID: 'vscode',
clientName: product.nameLong,
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true, // #10574
locale: platform.locale
}).then((result: DebugProtocol.InitializeResponse) => {
this.model.setExceptionBreakpoints(session.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (session.disconnected) {
return TPromise.as(null);
}
this.focusStackFrame(undefined, undefined, process);
this._onDidNewProcess.fire(process);
const internalConsoleOptions = configuration.internalConsoleOptions || this.configurationService.getValue<debug.IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const openDebugOptions = this.configurationService.getValue<debug.IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting
if (openDebugOptions === 'openOnSessionStart' || (openDebugOptions === 'openOnFirstSessionStart' && this.firstSessionStart)) {
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
this.firstSessionStart = false;
this.debugType.set(configuration.type);
if (this.model.getProcesses().length > 1) {
this.viewModel.setMultiProcessView(true);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: adapter.extensionDescription.id,
isBuiltin: adapter.extensionDescription.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<debug.IGlobalConfig>('launch', { resource: root.uri })
});
}).then(() => process, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
const errorMessage = error instanceof Error ? error.message : error;
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined, error: errorMessage });
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (!session.disconnected) {
session.disconnect().done(null, errors.onUnexpectedError);
} else if (process) {
this.model.removeProcess(process.getId());
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (this.model.getReplElements().length === 0) {
this.inDebugMode.reset();
}
this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []);
return undefined;
});
});
}
private showError(message: string, actions: IAction[] = []): TPromise<any> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
actions.push(configureAction);
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return TPromise.as(null);
});
}
private runTask(sessionId: string, root: IWorkspaceFolder, taskName: string): TPromise<ITaskSummary> {
if (!taskName || this.skipRunningTask) {
this.skipRunningTask = false;
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskName).then(task => {
if (!task) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the task \'{0}\'.", taskName)));
}
function once(kind: TaskEventKind, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (e.kind === kind) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return TPromise.as(null);
}
this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Active, this.taskService.onDidStateChange)(() => {
taskStarted = true;
})
);
const taskPromise = this.taskService.run(task);
if (task.isBackground) {
return new TPromise((c, e) => this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => c(null)))
);
}
return taskPromise;
});
return new TPromise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
e({ severity: severity.Error, message: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", taskName) });
}
}, 10000);
});
});
}
public sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
public restartProcess(process: debug.IProcess, restartData?: any): TPromise<any> {
return this.textFileService.saveAll().then(() => {
if (process.session.capabilities.supportsRestartRequest) {
return <TPromise>process.session.custom('restart', null);
}
const focusedProcess = this.viewModel.focusedProcess;
const preserveFocus = focusedProcess && process.getId() === focusedProcess.getId();
// Do not run preLaunch and postDebug tasks for automatic restarts
this.skipRunningTask = !!restartData;
return process.session.disconnect(true).then(() => {
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionHost') && process.session.root) {
return this.broadcastService.broadcast({
channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
return new TPromise<void>((c, e) => {
setTimeout(() => {
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let config = process.configuration;
const launch = process.session.root ? this.configurationManager.getLaunch(process.session.root.uri) : undefined;
if (this.launchJsonChanged && launch) {
this.launchJsonChanged = false;
config = launch.getConfiguration(process.configuration.name) || config;
// Take the type from the process since the debug extension might overwrite it #21316
config.type = process.configuration.type;
config.noDebug = process.configuration.noDebug;
}
config.__restart = restartData;
this.skipRunningTask = !!restartData;
this.startDebugging(launch, config).then(() => c(null), err => e(err));
}, 300);
});
}).then(() => {
if (preserveFocus) {
// Restart should preserve the focused process
const restartedProcess = this.model.getProcesses().filter(p => p.configuration.name === process.configuration.name).pop();
if (restartedProcess && restartedProcess !== this.viewModel.focusedProcess) {
this.focusStackFrame(undefined, undefined, restartedProcess);
}
}
});
});
}
public stopProcess(process: debug.IProcess): TPromise<any> {
if (process) {
return process.session.disconnect(false, true);
}
const processes = this.model.getProcesses();
if (processes.length) {
return TPromise.join(processes.map(p => p.session.disconnect(false, true)));
}
this.sessionStates.clear();
this._onDidChangeState.fire();
return undefined;
}
private onSessionEnd(session: RawDebugSession): void {
const bpsExist = this.model.getBreakpoints().length > 0;
const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('debugSessionStop', {
type: process && process.configuration.type,
success: session.emittedStopped || !bpsExist,
sessionLengthInSeconds: session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
this.model.removeProcess(session.getId());
if (process) {
process.inactive = true;
this._onDidEndProcess.fire(process);
if (process.configuration.postDebugTask) {
this.runTask(process.getId(), process.session.root, process.configuration.postDebugTask);
}
}
this.toDisposeOnSessionEnd.set(session.getId(), lifecycle.dispose(this.toDisposeOnSessionEnd.get(session.getId())));
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && focusedProcess.getId() === session.getId()) {
this.focusStackFrame(null);
}
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (this.model.getProcesses().length === 0) {
// set breakpoints back to unverified since the session ended.
const data: { [id: string]: { line: number, verified: boolean, column: number, endLine: number, endColumn: number } } = {};
this.model.getBreakpoints().forEach(bp => {
data[bp.getId()] = { line: bp.lineNumber, verified: false, column: bp.column, endLine: bp.endLineNumber, endColumn: bp.endColumn };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
this.debugType.reset();
this.viewModel.setMultiProcessView(false);
if (this.partService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);
}
}
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
private sendAllBreakpoints(process?: debug.IProcess): TPromise<any> {
return TPromise.join(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, process)))
.then(() => this.sendFunctionBreakpoints(process))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(process));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, targetProcess?: debug.IProcess): TPromise<void> {
const sendBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.uri.toString() === modelUri.toString());
const source = process.sources.get(modelUri.toString());
let rawSource: DebugProtocol.Source;
if (source) {
rawSource = source.raw;
} else {
const data = Source.getEncodedDebugData(modelUri);
rawSource = { name: data.name, path: data.path, sourceReference: data.sourceReference };
}
if (breakpointsToSend.length && !rawSource.adapterData) {
rawSource.adapterData = breakpointsToSend[0].adapterData;
}
// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
rawSource.path = normalizeDriveLetter(rawSource.path);
return session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.lineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.lineNumber, column: bp.column, condition: bp.condition, hitCondition: bp.hitCondition })),
sourceModified
}).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: DebugProtocol.Breakpoint } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
if (!breakpointsToSend[i].column) {
// If there was no column sent ignore the breakpoint column response from the adapter
data[breakpointsToSend[i].getId()].column = undefined;
}
}
this.model.updateBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendBreakpointsToProcess);
}
private sendFunctionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendFunctionBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || !session.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendFunctionBreakpointsToProcess);
}
private sendExceptionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendExceptionBreakpointsToProcess = (process: debug.IProcess): TPromise<any> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
};
return this.sendToOneOrAllProcesses(targetProcess, sendExceptionBreakpointsToProcess);
}
private sendToOneOrAllProcesses(process: debug.IProcess, send: (process: debug.IProcess) => TPromise<void>): TPromise<void> {
if (process) {
return send(process);
}
return TPromise.join(this.model.getProcesses().map(p => send(p))).then(() => void 0);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.has(event.resource.toString())) {
this.breakpointsToSendOnResourceSaved.delete(event.resource.toString());
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
if (event.resource.toString().indexOf('.vscode/launch.json') >= 0) {
this.launchJsonChanged = true;
}
});
}
private store(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
if (!this.model.areBreakpointsActivated()) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
public dispose(): void {
this.toDisposeOnSessionEnd.forEach(toDispose => lifecycle.dispose(toDispose));
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.4195377230644226,
0.003899296745657921,
0.0001625061413506046,
0.00017099003889597952,
0.03620840236544609
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t\t\tif (launch) {\n",
"\t\t\t\t\t\t\t\treturn launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);\n",
"\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t})\n",
"\t\t\t\t\t).then(() => wrapUpState(), err => {\n",
"\t\t\t\t\t\twrapUpState();\n",
"\t\t\t\t\t\treturn <any>TPromise.wrapError(err);\n",
"\t\t\t\t\t}));\n",
"\t\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t)).then(() => undefined);\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 781
} | src/vs/workbench/services/search/test/node/fixtures/examples/subfolder/anotherfolder/anotherfile.txt | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.0001719267456792295,
0.0001719267456792295,
0.0001719267456792295,
0.0001719267456792295,
0
] |
|
{
"id": 3,
"code_window": [
"\t\t\t\t\t\t\tif (launch) {\n",
"\t\t\t\t\t\t\t\treturn launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);\n",
"\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t})\n",
"\t\t\t\t\t).then(() => wrapUpState(), err => {\n",
"\t\t\t\t\t\twrapUpState();\n",
"\t\t\t\t\t\treturn <any>TPromise.wrapError(err);\n",
"\t\t\t\t\t}));\n",
"\t\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t)).then(() => undefined);\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 781
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"removeTag": "Emmet: Quitar etiqueta"
} | i18n/esn/src/vs/workbench/parts/emmet/electron-browser/actions/removeTag.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017480298993177712,
0.00017480298993177712,
0.00017480298993177712,
0.00017480298993177712,
0
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t\t\tif (launch) {\n",
"\t\t\t\t\t\t\t\treturn launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);\n",
"\t\t\t\t\t\t\t}\n",
"\t\t\t\t\t\t})\n",
"\t\t\t\t\t).then(() => wrapUpState(), err => {\n",
"\t\t\t\t\t\twrapUpState();\n",
"\t\t\t\t\t\treturn <any>TPromise.wrapError(err);\n",
"\t\t\t\t\t}));\n",
"\t\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\t\t\t\t)).then(() => undefined);\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 781
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"matchingPair": "Emmet : Go to Matching Pair"
} | i18n/fra/src/vs/workbench/parts/emmet/node/actions/matchingPair.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.0001737855636747554,
0.0001737855636747554,
0.0001737855636747554,
0.0001737855636747554,
0
] |
{
"id": 4,
"code_window": [
"\t\t\t})\n",
"\t\t)));\n",
"\t}\n",
"\n",
"\tprivate createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {\n",
"\t\treturn this.textFileService.saveAll().then(() =>\n",
"\t\t\t(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t))).then(() => wrapUpState(), err => {\n",
"\t\t\twrapUpState();\n",
"\t\t\treturn TPromise.wrapError(err);\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 786
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as lifecycle from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import * as resources from 'vs/base/common/resources';
import * as strings from 'vs/base/common/strings';
import { generateUuid } from 'vs/base/common/uuid';
import uri from 'vs/base/common/uri';
import * as platform from 'vs/base/common/platform';
import { first, distinct } from 'vs/base/common/arrays';
import { isObject, isUndefinedOrNull } from 'vs/base/common/types';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { TPromise } from 'vs/base/common/winjs.base';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService';
import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import * as debug from 'vs/workbench/parts/debug/common/debug';
import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession';
import { Model, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, RawObjectReplElement, ExpressionContainer, Process } from 'vs/workbench/parts/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/parts/debug/electron-browser/debugConfigurationManager';
import Constants from 'vs/workbench/parts/markers/electron-browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService';
import { TaskError } from 'vs/workbench/parts/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL, EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL, EXTENSION_RELOAD_BROADCAST_CHANNEL } from 'vs/platform/extensions/common/extensionHost';
import { IBroadcastService, IBroadcast } from 'vs/platform/broadcast/electron-browser/broadcastService';
import { IRemoteConsoleLog, parse, getFirstFrame } from 'vs/base/node/console';
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
import { TaskEvent, TaskEventKind } from 'vs/workbench/parts/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { RunOnceScheduler } from 'vs/base/common/async';
import product from 'vs/platform/node/product';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
export class DebugService implements debug.IDebugService {
public _serviceBrand: any;
private sessionStates: Map<string, debug.State>;
private readonly _onDidChangeState: Emitter<debug.State>;
private readonly _onDidNewProcess: Emitter<debug.IProcess>;
private readonly _onDidEndProcess: Emitter<debug.IProcess>;
private readonly _onDidCustomEvent: Emitter<debug.DebugEvent>;
private model: Model;
private viewModel: ViewModel;
private allProcesses: Map<string, debug.IProcess>;
private configurationManager: ConfigurationManager;
private toDispose: lifecycle.IDisposable[];
private toDisposeOnSessionEnd: Map<string, lifecycle.IDisposable[]>;
private inDebugMode: IContextKey<boolean>;
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private breakpointsToSendOnResourceSaved: Set<string>;
private launchJsonChanged: boolean;
private firstSessionStart: boolean;
private skipRunningTask: boolean;
private previousState: debug.State;
private fetchThreadsSchedulers: Map<string, RunOnceScheduler>;
constructor(
@IStorageService private storageService: IStorageService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@INotificationService private notificationService: INotificationService,
@IDialogService private dialogService: IDialogService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@IBroadcastService private broadcastService: IBroadcastService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService
) {
this.toDispose = [];
this.toDisposeOnSessionEnd = new Map<string, lifecycle.IDisposable[]>();
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<debug.State>();
this._onDidNewProcess = new Emitter<debug.IProcess>();
this._onDidEndProcess = new Emitter<debug.IProcess>();
this._onDidCustomEvent = new Emitter<debug.DebugEvent>();
this.sessionStates = new Map<string, debug.State>();
this.allProcesses = new Map<string, debug.IProcess>();
this.fetchThreadsSchedulers = new Map<string, RunOnceScheduler>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
this.toDispose.push(this.configurationManager);
this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.debugType = debug.CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = debug.CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.model = new Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions());
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.firstSessionStart = true;
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.store, this);
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.broadcastService.onBroadcast(this.onBroadcast, this));
}
private onBroadcast(broadcast: IBroadcast): void {
// attach: PH is ready to be attached to
const process = this.allProcesses.get(broadcast.payload.debugId);
if (!process) {
// Ignore attach events for sessions that never existed (wrong vscode windows)
return;
}
const session = <RawDebugSession>process.session;
if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
process.configuration.request = 'attach';
process.configuration.port = broadcast.payload.port;
this.doCreateProcess(process.session.root, process.configuration, process.getId());
return;
}
if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
this.onSessionEnd(session);
return;
}
// an extension logged output, show it inside the REPL
if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
let extensionOutput: IRemoteConsoleLog = broadcast.payload.logEntry;
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(extensionOutput);
let source: debug.IReplElementSource;
if (stack) {
const frame = getFirstFrame(stack);
if (frame) {
source = {
column: frame.column,
lineNumber: frame.line,
source: process.getSource({
name: resources.basenameOrAuthority(frame.uri),
path: frame.uri.fsPath
})
};
}
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev, source);
simpleVals = [];
}
// show object
this.logToRepl(new RawObjectReplElement((<any>a).prototype, a, undefined, nls.localize('snapshotObj', "Only primitive values are shown for this object.")), sev, source);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) {
i++; // read over substitution
buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
// always append a new line for output coming from an extension such that separate logs go to separate lines #23695
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' ') + '\n', sev, source);
}
}
}
private tryToAutoFocusStackFrame(thread: debug.IThread): TPromise<any> {
const callStack = thread.getCallStack();
if (!callStack.length || (this.viewModel.focusedStackFrame && this.viewModel.focusedStackFrame.thread.getId() === thread.getId())) {
return TPromise.as(null);
}
// focus first stack frame from top that has source location if no other stack frame is focused
const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, undefined);
if (!stackFrameToFocus) {
return TPromise.as(null);
}
this.focusStackFrame(stackFrameToFocus);
if (thread.stoppedDetails) {
this.windowService.focusWindow();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", thread.stoppedDetails.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.range.startLineNumber));
}
return stackFrameToFocus.openInEditor(this.editorService, true);
}
private registerSessionListeners(process: Process, session: RawDebugSession): void {
this.toDisposeOnSessionEnd.get(session.getId()).push(session);
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidInitialize(event => {
aria.status(nls.localize('debuggingStarted', "Debugging started."));
const sendConfigurationDone = () => {
if (session && session.capabilities.supportsConfigurationDoneRequest) {
return session.configurationDone().done(null, e => {
// Disconnect the debug session on configuration done error #10596
if (session) {
session.disconnect().done(null, errors.onUnexpectedError);
}
this.notificationService.error(e.message);
});
}
};
this.sendAllBreakpoints(process).then(sendConfigurationDone, sendConfigurationDone)
.done(() => this.fetchThreads(session), errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidStop(event => {
this.updateStateAndEmit(session.getId(), debug.State.Stopped);
this.fetchThreads(session, event.body).done(() => {
const thread = process && process.getThread(event.body.threadId);
if (thread) {
// Call fetch call stack twice, the first only return the top stack frame.
// Second retrieves the rest of the call stack. For performance reasons #25605
this.model.fetchCallStack(thread).then(() => {
return this.tryToAutoFocusStackFrame(thread);
});
}
}, errors.onUnexpectedError);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidThread(event => {
if (event.body.reason === 'started') {
// debounce to reduce threadsRequest frequency and improve performance
let scheduler = this.fetchThreadsSchedulers.get(session.getId());
if (!scheduler) {
scheduler = new RunOnceScheduler(() => {
this.fetchThreads(session).done(undefined, errors.onUnexpectedError);
}, 100);
this.fetchThreadsSchedulers.set(session.getId(), scheduler);
this.toDisposeOnSessionEnd.get(session.getId()).push(scheduler);
}
if (!scheduler.isScheduled()) {
scheduler.schedule();
}
} else if (event.body.reason === 'exited') {
this.model.clearThreads(session.getId(), true, event.body.threadId);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidTerminateDebugee(event => {
aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
if (session && session.getId() === event.sessionId) {
if (event.body && event.body.restart && process) {
this.restartProcess(process, event.body.restart).done(null, err => this.notificationService.error(err.message));
} else {
session.disconnect().done(null, errors.onUnexpectedError);
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidContinued(event => {
const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
this.model.clearThreads(session.getId(), false, threadId);
if (this.viewModel.focusedProcess.getId() === session.getId()) {
this.focusStackFrame(undefined, this.viewModel.focusedThread, this.viewModel.focusedProcess);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
}));
let outputPromises: TPromise<void>[] = [];
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidOutput(event => {
if (!event.body) {
return;
}
const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
if (event.body.category === 'telemetry') {
// only log telemetry events from debug adapter if the adapter provided the telemetry key
// and the user opted in telemetry
if (session.customTelemetryService && this.telemetryService.isOptedIn) {
// __GDPR__TODO__ We're sending events in the name of the debug adapter and we can not ensure that those are declared correctly.
session.customTelemetryService.publicLog(event.body.output, event.body.data);
}
return;
}
// Make sure to append output in the correct order by properly waiting on preivous promises #33822
const waitFor = outputPromises.slice();
const source = event.body.source ? {
lineNumber: event.body.line,
column: event.body.column,
source: process.getSource(event.body.source)
} : undefined;
if (event.body.variablesReference) {
const container = new ExpressionContainer(process, event.body.variablesReference, generateUuid());
outputPromises.push(container.getChildren().then(children => {
return TPromise.join(waitFor).then(() => children.forEach(child => {
// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
child.name = null;
this.logToRepl(child, outputSeverity, source);
}));
}));
} else if (typeof event.body.output === 'string') {
TPromise.join(waitFor).then(() => this.logToRepl(event.body.output, outputSeverity, source));
}
TPromise.join(outputPromises).then(() => outputPromises = []);
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidBreakpoint(event => {
const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
if (event.body.reason === 'new' && event.body.breakpoint.source) {
const source = process.getSource(event.body.breakpoint.source);
const bps = this.model.addBreakpoints(source.uri, [{
column: event.body.breakpoint.column,
enabled: true,
lineNumber: event.body.breakpoint.line,
}], false);
if (bps.length === 1) {
this.model.updateBreakpoints({ [bps[0].getId()]: event.body.breakpoint });
}
}
if (event.body.reason === 'removed') {
if (breakpoint) {
this.model.removeBreakpoints([breakpoint]);
}
if (functionBreakpoint) {
this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
}
}
if (event.body.reason === 'changed') {
if (breakpoint) {
if (!breakpoint.column) {
event.body.breakpoint.column = undefined;
}
this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
}
if (functionBreakpoint) {
this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
}
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidExitAdapter(event => {
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionhost') && this.sessionStates.get(session.getId()) === debug.State.Running &&
process && process.session.root && process.configuration.noDebug) {
this.broadcastService.broadcast({
channel: EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
if (session && session.getId() === event.sessionId) {
this.onSessionEnd(session);
}
}));
this.toDisposeOnSessionEnd.get(session.getId()).push(session.onDidCustomEvent(event => {
this._onDidCustomEvent.fire(event);
}));
}
private fetchThreads(session: RawDebugSession, stoppedDetails?: debug.IRawStoppedDetails): TPromise<any> {
return session.threads().then(response => {
if (response && response.body && response.body.threads) {
response.body.threads.forEach(thread => {
this.model.rawUpdate({
sessionId: session.getId(),
threadId: thread.id,
thread,
stoppedDetails: stoppedDetails && thread.id === stoppedDetails.threadId ? stoppedDetails : undefined
});
});
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.adapterData);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[];
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[];
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
public get state(): debug.State {
const focusedThread = this.viewModel.focusedThread;
if (focusedThread && focusedThread.stopped) {
return debug.State.Stopped;
}
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && this.sessionStates.has(focusedProcess.getId())) {
return this.sessionStates.get(focusedProcess.getId());
}
if (this.sessionStates.size > 0) {
return debug.State.Initializing;
}
return debug.State.Inactive;
}
public get onDidChangeState(): Event<debug.State> {
return this._onDidChangeState.event;
}
public get onDidNewProcess(): Event<debug.IProcess> {
return this._onDidNewProcess.event;
}
public get onDidEndProcess(): Event<debug.IProcess> {
return this._onDidEndProcess.event;
}
public get onDidCustomEvent(): Event<debug.DebugEvent> {
return this._onDidCustomEvent.event;
}
private updateStateAndEmit(sessionId?: string, newState?: debug.State): void {
if (sessionId) {
if (newState === debug.State.Inactive) {
this.sessionStates.delete(sessionId);
} else {
this.sessionStates.set(sessionId, newState);
}
}
const state = this.state;
if (this.previousState !== state) {
const stateLabel = debug.State[state];
if (stateLabel) {
this.debugState.set(stateLabel.toLowerCase());
}
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
public focusStackFrame(stackFrame: debug.IStackFrame, thread?: debug.IThread, process?: debug.IProcess, explicit?: boolean): void {
if (!process) {
if (stackFrame || thread) {
process = stackFrame ? stackFrame.thread.process : thread.process;
} else {
const processes = this.model.getProcesses();
process = processes.length ? processes[0] : undefined;
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = process ? process.getAllThreads() : undefined;
thread = threads && threads.length ? threads[0] : undefined;
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = callStack && callStack.length ? callStack[0] : null;
}
}
this.viewModel.setFocus(stackFrame, thread, process, explicit);
this.updateStateAndEmit();
}
public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
return this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
public addBreakpoints(uri: uri, rawBreakpoints: debug.IBreakpointData[]): TPromise<void> {
this.model.addBreakpoints(uri, rawBreakpoints);
rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, uri.fsPath)));
return this.sendBreakpoints(uri);
}
public updateBreakpoints(uri: uri, data: { [id: string]: DebugProtocol.Breakpoint }, sendOnResourceSaved: boolean): void {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
this.sendBreakpoints(uri);
}
}
public removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
public setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
public addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
return this.sendFunctionBreakpoints();
}
public removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
public addReplExpression(name: string): TPromise<void> {
return this.model.addReplExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name)
// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
.then(() => this.focusStackFrame(this.viewModel.focusedStackFrame, this.viewModel.focusedThread, this.viewModel.focusedProcess));
}
public removeReplExpressions(): void {
this.model.removeReplExpressions();
}
public logToRepl(value: string | debug.IExpression, sev = severity.Info, source?: debug.IReplElementSource): void {
if (typeof value === 'string' && '[2J'.localeCompare(value) === 0) {
// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
this.model.removeReplExpressions();
} else {
this.model.appendToRepl(value, sev, source);
}
}
public addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name);
this.viewModel.setSelectedExpression(we);
}
public renameWatchExpression(id: string, newName: string): void {
return this.model.renameWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, id, newName);
}
public moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
}
public removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
public startDebugging(launch: debug.ILaunch, configOrName?: debug.IConfig | string, noDebug = false): TPromise<any> {
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
if (this.model.getProcesses().length === 0) {
this.removeReplExpressions();
this.allProcesses.clear();
this.model.getBreakpoints().forEach(bp => bp.verified = false);
}
this.launchJsonChanged = false;
let config: debug.IConfig, compound: debug.ICompound;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
if (!compound.configurations) {
return TPromise.wrapError(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return TPromise.join(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound.name) {
return TPromise.as(null);
}
let launchForName: debug.ILaunch;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return TPromise.wrapError(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return TPromise.wrapError(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
}
}
return this.startDebugging(launchForName, name, noDebug);
}));
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", configOrName) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return TPromise.wrapError(new Error(message));
}
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = <debug.IConfig>{};
}
if (noDebug) {
config.noDebug = true;
}
const sessionId = generateUuid();
this.updateStateAndEmit(sessionId, debug.State.Initializing);
const wrapUpState = () => {
if (this.sessionStates.get(sessionId) === debug.State.Initializing) {
this.updateStateAndEmit(sessionId, debug.State.Inactive);
}
};
return (type ? TPromise.as(null) : this.configurationManager.guessAdapter().then(a => type = a && a.type)).then(() =>
(type ? this.extensionService.activateByEvent(`onDebugResolve:${type}`) : TPromise.as(null)).then(() =>
this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.createProcess(launch, config, sessionId);
}
if (launch) {
return launch.openConfigFile(false, type).done(undefined, errors.onUnexpectedError);
}
})
).then(() => wrapUpState(), err => {
wrapUpState();
return <any>TPromise.wrapError(err);
}));
})
)));
}
private createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {
return this.textFileService.saveAll().then(() =>
(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return undefined;
}
if (!this.configurationManager.getAdapter(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message);
}
this.toDisposeOnSessionEnd.set(sessionId, []);
const workspace = launch ? launch.workspace : undefined;
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
});
return this.runTask(sessionId, workspace, resolvedConfig.preLaunchTask).then((taskSummary: ITaskSummary) => {
const errorCount = resolvedConfig.preLaunchTask ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return this.doCreateProcess(workspace, resolvedConfig, sessionId);
}
const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", resolvedConfig.preLaunchTask) :
nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", resolvedConfig.preLaunchTask, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => undefined);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}, err => {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved on disk and that you have a debug extension installed for that file type."));
}
return launch && launch.openConfigFile(false).then(editor => void 0);
})
);
}
private doCreateProcess(root: IWorkspaceFolder, configuration: debug.IConfig, sessionId: string): TPromise<debug.IProcess> {
configuration.__sessionId = sessionId;
this.inDebugMode.set(true);
return this.telemetryService.getTelemetryInfo().then(info => {
const telemetryInfo: { [key: string]: string } = Object.create(null);
telemetryInfo['common.vscodemachineid'] = info.machineId;
telemetryInfo['common.vscodesessionid'] = info.sessionId;
return telemetryInfo;
}).then(data => {
const adapter = this.configurationManager.getAdapter(configuration.type);
const { aiKey, type } = adapter;
const publisher = adapter.extensionDescription.publisher;
let client: TelemetryClient;
let customTelemetryService: TelemetryService;
if (aiKey) {
client = new TelemetryClient(
uri.parse(require.toUrl('bootstrap')).fsPath,
{
serverName: 'Debug Telemetry',
timeout: 1000 * 60 * 5,
args: [`${publisher}.${type}`, JSON.stringify(data), aiKey],
env: {
ELECTRON_RUN_AS_NODE: 1,
PIPE_LOGGING: 'true',
AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp'
}
}
);
const channel = client.getChannel('telemetryAppender');
const appender = new TelemetryAppenderClient(channel);
customTelemetryService = new TelemetryService({ appender }, this.configurationService);
}
const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, customTelemetryService, root);
const process = this.model.addProcess(configuration, session);
this.allProcesses.set(process.getId(), process);
if (client) {
this.toDisposeOnSessionEnd.get(session.getId()).push(client);
}
this.registerSessionListeners(process, session);
return session.initialize({
clientID: 'vscode',
clientName: product.nameLong,
adapterID: configuration.type,
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true, // #8858
supportsVariablePaging: true, // #9537
supportsRunInTerminalRequest: true, // #10574
locale: platform.locale
}).then((result: DebugProtocol.InitializeResponse) => {
this.model.setExceptionBreakpoints(session.capabilities.exceptionBreakpointFilters);
return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration);
}).then((result: DebugProtocol.Response) => {
if (session.disconnected) {
return TPromise.as(null);
}
this.focusStackFrame(undefined, undefined, process);
this._onDidNewProcess.fire(process);
const internalConsoleOptions = configuration.internalConsoleOptions || this.configurationService.getValue<debug.IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
const openDebugOptions = this.configurationService.getValue<debug.IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting
if (openDebugOptions === 'openOnSessionStart' || (openDebugOptions === 'openOnFirstSessionStart' && this.firstSessionStart)) {
this.viewletService.openViewlet(debug.VIEWLET_ID);
}
this.firstSessionStart = false;
this.debugType.set(configuration.type);
if (this.model.getProcesses().length > 1) {
this.viewModel.setMultiProcessView(true);
}
this.updateStateAndEmit(session.getId(), debug.State.Running);
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: configuration.type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: adapter.extensionDescription.id,
isBuiltin: adapter.extensionDescription.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<debug.IGlobalConfig>('launch', { resource: root.uri })
});
}).then(() => process, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// Do not show 'canceled' error messages to the user #7906
return TPromise.as(null);
}
const errorMessage = error instanceof Error ? error.message : error;
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined, error: errorMessage });
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (!session.disconnected) {
session.disconnect().done(null, errors.onUnexpectedError);
} else if (process) {
this.model.removeProcess(process.getId());
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError);
}
if (this.model.getReplElements().length === 0) {
this.inDebugMode.reset();
}
this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []);
return undefined;
});
});
}
private showError(message: string, actions: IAction[] = []): TPromise<any> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
actions.push(configureAction);
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return TPromise.as(null);
});
}
private runTask(sessionId: string, root: IWorkspaceFolder, taskName: string): TPromise<ITaskSummary> {
if (!taskName || this.skipRunningTask) {
this.skipRunningTask = false;
return TPromise.as(null);
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskName).then(task => {
if (!task) {
return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the task \'{0}\'.", taskName)));
}
function once(kind: TaskEventKind, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (e.kind === kind) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return TPromise.as(null);
}
this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Active, this.taskService.onDidStateChange)(() => {
taskStarted = true;
})
);
const taskPromise = this.taskService.run(task);
if (task.isBackground) {
return new TPromise((c, e) => this.toDisposeOnSessionEnd.get(sessionId).push(
once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => c(null)))
);
}
return taskPromise;
});
return new TPromise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
e({ severity: severity.Error, message: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", taskName) });
}
}, 10000);
});
});
}
public sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
public restartProcess(process: debug.IProcess, restartData?: any): TPromise<any> {
return this.textFileService.saveAll().then(() => {
if (process.session.capabilities.supportsRestartRequest) {
return <TPromise>process.session.custom('restart', null);
}
const focusedProcess = this.viewModel.focusedProcess;
const preserveFocus = focusedProcess && process.getId() === focusedProcess.getId();
// Do not run preLaunch and postDebug tasks for automatic restarts
this.skipRunningTask = !!restartData;
return process.session.disconnect(true).then(() => {
if (strings.equalsIgnoreCase(process.configuration.type, 'extensionHost') && process.session.root) {
return this.broadcastService.broadcast({
channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
payload: [process.session.root.uri.fsPath]
});
}
return new TPromise<void>((c, e) => {
setTimeout(() => {
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let config = process.configuration;
const launch = process.session.root ? this.configurationManager.getLaunch(process.session.root.uri) : undefined;
if (this.launchJsonChanged && launch) {
this.launchJsonChanged = false;
config = launch.getConfiguration(process.configuration.name) || config;
// Take the type from the process since the debug extension might overwrite it #21316
config.type = process.configuration.type;
config.noDebug = process.configuration.noDebug;
}
config.__restart = restartData;
this.skipRunningTask = !!restartData;
this.startDebugging(launch, config).then(() => c(null), err => e(err));
}, 300);
});
}).then(() => {
if (preserveFocus) {
// Restart should preserve the focused process
const restartedProcess = this.model.getProcesses().filter(p => p.configuration.name === process.configuration.name).pop();
if (restartedProcess && restartedProcess !== this.viewModel.focusedProcess) {
this.focusStackFrame(undefined, undefined, restartedProcess);
}
}
});
});
}
public stopProcess(process: debug.IProcess): TPromise<any> {
if (process) {
return process.session.disconnect(false, true);
}
const processes = this.model.getProcesses();
if (processes.length) {
return TPromise.join(processes.map(p => p.session.disconnect(false, true)));
}
this.sessionStates.clear();
this._onDidChangeState.fire();
return undefined;
}
private onSessionEnd(session: RawDebugSession): void {
const bpsExist = this.model.getBreakpoints().length > 0;
const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('debugSessionStop', {
type: process && process.configuration.type,
success: session.emittedStopped || !bpsExist,
sessionLengthInSeconds: session.getLengthInSeconds(),
breakpointCount: this.model.getBreakpoints().length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
this.model.removeProcess(session.getId());
if (process) {
process.inactive = true;
this._onDidEndProcess.fire(process);
if (process.configuration.postDebugTask) {
this.runTask(process.getId(), process.session.root, process.configuration.postDebugTask);
}
}
this.toDisposeOnSessionEnd.set(session.getId(), lifecycle.dispose(this.toDisposeOnSessionEnd.get(session.getId())));
const focusedProcess = this.viewModel.focusedProcess;
if (focusedProcess && focusedProcess.getId() === session.getId()) {
this.focusStackFrame(null);
}
this.updateStateAndEmit(session.getId(), debug.State.Inactive);
if (this.model.getProcesses().length === 0) {
// set breakpoints back to unverified since the session ended.
const data: { [id: string]: { line: number, verified: boolean, column: number, endLine: number, endColumn: number } } = {};
this.model.getBreakpoints().forEach(bp => {
data[bp.getId()] = { line: bp.lineNumber, verified: false, column: bp.column, endLine: bp.endLineNumber, endColumn: bp.endColumn };
});
this.model.updateBreakpoints(data);
this.inDebugMode.reset();
this.debugType.reset();
this.viewModel.setMultiProcessView(false);
if (this.partService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);
}
}
}
public getModel(): debug.IModel {
return this.model;
}
public getViewModel(): debug.IViewModel {
return this.viewModel;
}
public getConfigurationManager(): debug.IConfigurationManager {
return this.configurationManager;
}
private sendAllBreakpoints(process?: debug.IProcess): TPromise<any> {
return TPromise.join(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, process)))
.then(() => this.sendFunctionBreakpoints(process))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(process));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, targetProcess?: debug.IProcess): TPromise<void> {
const sendBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.uri.toString() === modelUri.toString());
const source = process.sources.get(modelUri.toString());
let rawSource: DebugProtocol.Source;
if (source) {
rawSource = source.raw;
} else {
const data = Source.getEncodedDebugData(modelUri);
rawSource = { name: data.name, path: data.path, sourceReference: data.sourceReference };
}
if (breakpointsToSend.length && !rawSource.adapterData) {
rawSource.adapterData = breakpointsToSend[0].adapterData;
}
// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
rawSource.path = normalizeDriveLetter(rawSource.path);
return session.setBreakpoints({
source: rawSource,
lines: breakpointsToSend.map(bp => bp.lineNumber),
breakpoints: breakpointsToSend.map(bp => ({ line: bp.lineNumber, column: bp.column, condition: bp.condition, hitCondition: bp.hitCondition })),
sourceModified
}).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: DebugProtocol.Breakpoint } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
if (!breakpointsToSend[i].column) {
// If there was no column sent ignore the breakpoint column response from the adapter
data[breakpointsToSend[i].getId()].column = undefined;
}
}
this.model.updateBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendBreakpointsToProcess);
}
private sendFunctionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendFunctionBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || !session.capabilities.supportsFunctionBreakpoints) {
return TPromise.as(null);
}
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
if (!response || !response.body) {
return;
}
const data: { [id: string]: { name?: string, verified?: boolean } } = {};
for (let i = 0; i < breakpointsToSend.length; i++) {
data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
}
this.model.updateFunctionBreakpoints(data);
});
};
return this.sendToOneOrAllProcesses(targetProcess, sendFunctionBreakpointsToProcess);
}
private sendExceptionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> {
const sendExceptionBreakpointsToProcess = (process: debug.IProcess): TPromise<any> => {
const session = <RawDebugSession>process.session;
if (!session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
return TPromise.as(null);
}
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
};
return this.sendToOneOrAllProcesses(targetProcess, sendExceptionBreakpointsToProcess);
}
private sendToOneOrAllProcesses(process: debug.IProcess, send: (process: debug.IProcess) => TPromise<void>): TPromise<void> {
if (process) {
return send(process);
}
return TPromise.join(this.model.getProcesses().map(p => send(p))).then(() => void 0);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.has(event.resource.toString())) {
this.breakpointsToSendOnResourceSaved.delete(event.resource.toString());
this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError);
}
if (event.resource.toString().indexOf('.vscode/launch.json') >= 0) {
this.launchJsonChanged = true;
}
});
}
private store(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
if (!this.model.areBreakpointsActivated()) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
public dispose(): void {
this.toDisposeOnSessionEnd.forEach(toDispose => lifecycle.dispose(toDispose));
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/electron-browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.9990473389625549,
0.05433858931064606,
0.0001624779251869768,
0.00017414211470168084,
0.20673859119415283
] |
{
"id": 4,
"code_window": [
"\t\t\t})\n",
"\t\t)));\n",
"\t}\n",
"\n",
"\tprivate createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {\n",
"\t\treturn this.textFileService.saveAll().then(() =>\n",
"\t\t\t(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t))).then(() => wrapUpState(), err => {\n",
"\t\t\twrapUpState();\n",
"\t\t\treturn TPromise.wrapError(err);\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 786
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"errorInvalidTaskConfiguration": "Nem sikerült írni a munkaterület konfigurációs fájljába. Nyissa meg a fájlt, javítsa a benne található hibákat és figyelmeztetéseket, majd próbálja újra!",
"errorWorkspaceConfigurationFileDirty": "Nem sikerült írni a munkaterület konfigurációs fájljába, mert módosítva lett. Mentse, majd próbálja újra!",
"openWorkspaceConfigurationFile": "Munkaterület-konfiguráció megnyitása"
} | i18n/hun/src/vs/workbench/services/workspace/node/workspaceEditingService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017112288333009928,
0.0001685415772954002,
0.00016596027126070112,
0.0001685415772954002,
0.0000025813060346990824
] |
{
"id": 4,
"code_window": [
"\t\t\t})\n",
"\t\t)));\n",
"\t}\n",
"\n",
"\tprivate createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {\n",
"\t\treturn this.textFileService.saveAll().then(() =>\n",
"\t\t\t(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t))).then(() => wrapUpState(), err => {\n",
"\t\t\twrapUpState();\n",
"\t\t\treturn TPromise.wrapError(err);\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 786
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"default": "Impostazione predefinita",
"user": "Utente",
"meta": "meta",
"option": "opzione"
} | i18n/ita/src/vs/workbench/parts/preferences/common/keybindingsEditorModel.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.0001762323809089139,
0.00017520913388580084,
0.00017418587231077254,
0.00017520913388580084,
0.000001023254299070686
] |
{
"id": 4,
"code_window": [
"\t\t\t})\n",
"\t\t)));\n",
"\t}\n",
"\n",
"\tprivate createProcess(launch: debug.ILaunch, config: debug.IConfig, sessionId: string): TPromise<void> {\n",
"\t\treturn this.textFileService.saveAll().then(() =>\n",
"\t\t\t(launch ? launch.resolveConfiguration(config) : TPromise.as(config)).then(resolvedConfig => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t))).then(() => wrapUpState(), err => {\n",
"\t\t\twrapUpState();\n",
"\t\t\treturn TPromise.wrapError(err);\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 786
} | {
"": [
"--------------------------------------------------------------------------------------------",
"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."
],
"dotnetCore": "Esegue il comando di compilazione di .NET Core",
"msbuild": "Esegue la destinazione di compilazione",
"externalCommand": "Esempio per eseguire un comando esterno arbitrario",
"Maven": "Consente di eseguire comandi Maven comuni"
} | i18n/ita/src/vs/workbench/parts/tasks/common/taskTemplates.i18n.json | 0 | https://github.com/microsoft/vscode/commit/2775e756eb6505fc5956219c63b411c0e1780470 | [
0.00017586493049748242,
0.00017440496594645083,
0.000172944986843504,
0.00017440496594645083,
0.0000014599718269892037
] |
{
"id": 0,
"code_window": [
"\t\t}\n",
"\t\tthis._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\tpublic layout(dimension?: IDimension): void {\n",
"\t\tthis._configuration.observeContainer(dimension);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tpublic layout(dimension?: IDimension, postponeRendering: boolean = false): void {\n"
],
"file_path": "src/vs/editor/browser/widget/codeEditorWidget.ts",
"type": "replace",
"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.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { IDisposable } from 'vs/base/common/lifecycle';
import { ThemeColor } from 'vs/base/common/themables';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { IDimension } from 'vs/editor/common/core/dimension';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
import { IModelDecoration, IModelDecorationsChangeAccessor, IModelDeltaDecoration, ITextModel, IValidEditOperation, OverviewRulerLane, TrackedRangeStickiness } from 'vs/editor/common/model';
import { IModelDecorationsChangedEvent } from 'vs/editor/common/textModelEvents';
import { ICommandMetadata } from 'vs/platform/commands/common/commands';
/**
* A builder and helper for edit operations for a command.
*/
export interface IEditOperationBuilder {
/**
* Add a new edit operation (a replace operation).
* @param range The range to replace (delete). May be empty to represent a simple insert.
* @param text The text to replace with. May be null to represent a simple delete.
*/
addEditOperation(range: IRange, text: string | null, forceMoveMarkers?: boolean): void;
/**
* Add a new edit operation (a replace operation).
* The inverse edits will be accessible in `ICursorStateComputerData.getInverseEditOperations()`
* @param range The range to replace (delete). May be empty to represent a simple insert.
* @param text The text to replace with. May be null to represent a simple delete.
*/
addTrackedEditOperation(range: IRange, text: string | null, forceMoveMarkers?: boolean): void;
/**
* Track `selection` when applying edit operations.
* A best effort will be made to not grow/expand the selection.
* An empty selection will clamp to a nearby character.
* @param selection The selection to track.
* @param trackPreviousOnEmpty If set, and the selection is empty, indicates whether the selection
* should clamp to the previous or the next character.
* @return A unique identifier.
*/
trackSelection(selection: Selection, trackPreviousOnEmpty?: boolean): string;
}
/**
* A helper for computing cursor state after a command.
*/
export interface ICursorStateComputerData {
/**
* Get the inverse edit operations of the added edit operations.
*/
getInverseEditOperations(): IValidEditOperation[];
/**
* Get a previously tracked selection.
* @param id The unique identifier returned by `trackSelection`.
* @return The selection.
*/
getTrackedSelection(id: string): Selection;
}
/**
* A command that modifies text / cursor state on a model.
*/
export interface ICommand {
/**
* Signal that this command is inserting automatic whitespace that should be trimmed if possible.
* @internal
*/
readonly insertsAutoWhitespace?: boolean;
/**
* Get the edit operations needed to execute this command.
* @param model The model the command will execute on.
* @param builder A helper to collect the needed edit operations and to track selections.
*/
getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void;
/**
* Compute the cursor state after the edit operations were applied.
* @param model The model the command has executed on.
* @param helper A helper to get inverse edit operations and to get previously tracked selections.
* @return The cursor state after the command executed.
*/
computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection;
}
/**
* A model for the diff editor.
*/
export interface IDiffEditorModel {
/**
* Original model.
*/
original: ITextModel;
/**
* Modified model.
*/
modified: ITextModel;
}
export interface IDiffEditorViewModel extends IDisposable {
readonly model: IDiffEditorModel;
waitForDiff(): Promise<void>;
}
/**
* An event describing that an editor has had its model reset (i.e. `editor.setModel()`).
*/
export interface IModelChangedEvent {
/**
* The `uri` of the previous model or null.
*/
readonly oldModelUrl: URI | null;
/**
* The `uri` of the new model or null.
*/
readonly newModelUrl: URI | null;
}
// --- view
export interface IScrollEvent {
readonly scrollTop: number;
readonly scrollLeft: number;
readonly scrollWidth: number;
readonly scrollHeight: number;
readonly scrollTopChanged: boolean;
readonly scrollLeftChanged: boolean;
readonly scrollWidthChanged: boolean;
readonly scrollHeightChanged: boolean;
}
export interface IContentSizeChangedEvent {
readonly contentWidth: number;
readonly contentHeight: number;
readonly contentWidthChanged: boolean;
readonly contentHeightChanged: boolean;
}
export interface INewScrollPosition {
scrollLeft?: number;
scrollTop?: number;
}
export interface IEditorAction {
readonly id: string;
readonly label: string;
readonly alias: string;
readonly metadata: ICommandMetadata | undefined;
isSupported(): boolean;
run(args?: unknown): Promise<void>;
}
export type IEditorModel = ITextModel | IDiffEditorModel | IDiffEditorViewModel;
/**
* A (serializable) state of the cursors.
*/
export interface ICursorState {
inSelectionMode: boolean;
selectionStart: IPosition;
position: IPosition;
}
/**
* A (serializable) state of the view.
*/
export interface IViewState {
/** written by previous versions */
scrollTop?: number;
/** written by previous versions */
scrollTopWithoutViewZones?: number;
scrollLeft: number;
firstPosition: IPosition;
firstPositionDeltaTop: number;
}
/**
* A (serializable) state of the code editor.
*/
export interface ICodeEditorViewState {
cursorState: ICursorState[];
viewState: IViewState;
contributionsState: { [id: string]: any };
}
/**
* (Serializable) View state for the diff editor.
*/
export interface IDiffEditorViewState {
original: ICodeEditorViewState | null;
modified: ICodeEditorViewState | null;
modelState?: unknown;
}
/**
* An editor view state.
*/
export type IEditorViewState = ICodeEditorViewState | IDiffEditorViewState;
export const enum ScrollType {
Smooth = 0,
Immediate = 1,
}
/**
* An editor.
*/
export interface IEditor {
/**
* An event emitted when the editor has been disposed.
* @event
*/
onDidDispose(listener: () => void): IDisposable;
/**
* Dispose the editor.
*/
dispose(): void;
/**
* Get a unique id for this editor instance.
*/
getId(): string;
/**
* Get the editor type. Please see `EditorType`.
* This is to avoid an instanceof check
*/
getEditorType(): string;
/**
* Update the editor's options after the editor has been created.
*/
updateOptions(newOptions: IEditorOptions): void;
/**
* Indicates that the editor becomes visible.
* @internal
*/
onVisible(): void;
/**
* Indicates that the editor becomes hidden.
* @internal
*/
onHide(): void;
/**
* Instructs the editor to remeasure its container. This method should
* be called when the container of the editor gets resized.
*
* If a dimension is passed in, the passed in value will be used.
*/
layout(dimension?: IDimension): void;
/**
* Brings browser focus to the editor text
*/
focus(): void;
/**
* Returns true if the text inside this editor is focused (i.e. cursor is blinking).
*/
hasTextFocus(): boolean;
/**
* Returns all actions associated with this editor.
*/
getSupportedActions(): IEditorAction[];
/**
* Saves current view state of the editor in a serializable object.
*/
saveViewState(): IEditorViewState | null;
/**
* Restores the view state of the editor from a serializable object generated by `saveViewState`.
*/
restoreViewState(state: IEditorViewState | null): void;
/**
* Given a position, returns a column number that takes tab-widths into account.
*/
getVisibleColumnFromPosition(position: IPosition): number;
/**
* Given a position, returns a column number that takes tab-widths into account.
* @internal
*/
getStatusbarColumn(position: IPosition): number;
/**
* Returns the primary position of the cursor.
*/
getPosition(): Position | null;
/**
* Set the primary position of the cursor. This will remove any secondary cursors.
* @param position New primary cursor's position
* @param source Source of the call that caused the position
*/
setPosition(position: IPosition, source?: string): void;
/**
* Scroll vertically as necessary and reveal a line.
*/
revealLine(lineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically as necessary and reveal a line centered vertically.
*/
revealLineInCenter(lineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically as necessary and reveal a line centered vertically only if it lies outside the viewport.
*/
revealLineInCenterIfOutsideViewport(lineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically as necessary and reveal a line close to the top of the viewport,
* optimized for viewing a code definition.
*/
revealLineNearTop(lineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a position.
*/
revealPosition(position: IPosition, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a position centered vertically.
*/
revealPositionInCenter(position: IPosition, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a position centered vertically only if it lies outside the viewport.
*/
revealPositionInCenterIfOutsideViewport(position: IPosition, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a position close to the top of the viewport,
* optimized for viewing a code definition.
*/
revealPositionNearTop(position: IPosition, scrollType?: ScrollType): void;
/**
* Returns the primary selection of the editor.
*/
getSelection(): Selection | null;
/**
* Returns all the selections of the editor.
*/
getSelections(): Selection[] | null;
/**
* Set the primary selection of the editor. This will remove any secondary cursors.
* @param selection The new selection
* @param source Source of the call that caused the selection
*/
setSelection(selection: IRange, source?: string): void;
/**
* Set the primary selection of the editor. This will remove any secondary cursors.
* @param selection The new selection
* @param source Source of the call that caused the selection
*/
setSelection(selection: Range, source?: string): void;
/**
* Set the primary selection of the editor. This will remove any secondary cursors.
* @param selection The new selection
* @param source Source of the call that caused the selection
*/
setSelection(selection: ISelection, source?: string): void;
/**
* Set the primary selection of the editor. This will remove any secondary cursors.
* @param selection The new selection
* @param source Source of the call that caused the selection
*/
setSelection(selection: Selection, source?: string): void;
/**
* Set the selections for all the cursors of the editor.
* Cursors will be removed or added, as necessary.
* @param selections The new selection
* @param source Source of the call that caused the selection
*/
setSelections(selections: readonly ISelection[], source?: string): void;
/**
* Scroll vertically as necessary and reveal lines.
*/
revealLines(startLineNumber: number, endLineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically as necessary and reveal lines centered vertically.
*/
revealLinesInCenter(lineNumber: number, endLineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically as necessary and reveal lines centered vertically only if it lies outside the viewport.
*/
revealLinesInCenterIfOutsideViewport(lineNumber: number, endLineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically as necessary and reveal lines close to the top of the viewport,
* optimized for viewing a code definition.
*/
revealLinesNearTop(lineNumber: number, endLineNumber: number, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a range.
*/
revealRange(range: IRange, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a range centered vertically.
*/
revealRangeInCenter(range: IRange, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a range at the top of the viewport.
*/
revealRangeAtTop(range: IRange, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a range centered vertically only if it lies outside the viewport.
*/
revealRangeInCenterIfOutsideViewport(range: IRange, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a range close to the top of the viewport,
* optimized for viewing a code definition.
*/
revealRangeNearTop(range: IRange, scrollType?: ScrollType): void;
/**
* Scroll vertically or horizontally as necessary and reveal a range close to the top of the viewport,
* optimized for viewing a code definition. Only if it lies outside the viewport.
*/
revealRangeNearTopIfOutsideViewport(range: IRange, scrollType?: ScrollType): void;
/**
* Directly trigger a handler or an editor action.
* @param source The source of the call.
* @param handlerId The id of the handler or the id of a contribution.
* @param payload Extra data to be sent to the handler.
*/
trigger(source: string | null | undefined, handlerId: string, payload: any): void;
/**
* Gets the current model attached to this editor.
*/
getModel(): IEditorModel | null;
/**
* Sets the current model attached to this editor.
* If the previous model was created by the editor via the value key in the options
* literal object, it will be destroyed. Otherwise, if the previous model was set
* via setModel, or the model key in the options literal object, the previous model
* will not be destroyed.
* It is safe to call setModel(null) to simply detach the current model from the editor.
*/
setModel(model: IEditorModel | null): void;
/**
* Create a collection of decorations. All decorations added through this collection
* will get the ownerId of the editor (meaning they will not show up in other editors).
* These decorations will be automatically cleared when the editor's model changes.
*/
createDecorationsCollection(decorations?: IModelDeltaDecoration[]): IEditorDecorationsCollection;
/**
* Change the decorations. All decorations added through this changeAccessor
* will get the ownerId of the editor (meaning they will not show up in other
* editors).
* @see {@link ITextModel.changeDecorations}
* @internal
*/
changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any;
}
/**
* A diff editor.
*
* @internal
*/
export interface IDiffEditor extends IEditor {
/**
* Type the getModel() of IEditor.
*/
getModel(): IDiffEditorModel | null;
/**
* Get the `original` editor.
*/
getOriginalEditor(): IEditor;
/**
* Get the `modified` editor.
*/
getModifiedEditor(): IEditor;
}
/**
* @internal
*/
export interface ICompositeCodeEditor {
/**
* An event that signals that the active editor has changed
*/
readonly onDidChangeActiveEditor: Event<ICompositeCodeEditor>;
/**
* The active code editor iff any
*/
readonly activeCodeEditor: IEditor | undefined;
// readonly editors: readonly ICodeEditor[] maybe supported with uris
}
/**
* A collection of decorations
*/
export interface IEditorDecorationsCollection {
/**
* An event emitted when decorations change in the editor,
* but the change is not caused by us setting or clearing the collection.
*/
onDidChange: Event<IModelDecorationsChangedEvent>;
/**
* Get the decorations count.
*/
length: number;
/**
* Get the range for a decoration.
*/
getRange(index: number): Range | null;
/**
* Get all ranges for decorations.
*/
getRanges(): Range[];
/**
* Determine if a decoration is in this collection.
*/
has(decoration: IModelDecoration): boolean;
/**
* Replace all previous decorations with `newDecorations`.
*/
set(newDecorations: readonly IModelDeltaDecoration[]): string[];
/**
* Remove all previous decorations.
*/
clear(): void;
}
/**
* An editor contribution that gets created every time a new editor gets created and gets disposed when the editor gets disposed.
*/
export interface IEditorContribution {
/**
* Dispose this contribution.
*/
dispose(): void;
/**
* Store view state.
*/
saveViewState?(): any;
/**
* Restore view state.
*/
restoreViewState?(state: any): void;
}
/**
* A diff editor contribution that gets created every time a new diffeditor gets created and gets disposed when the diff editor gets disposed.
* @internal
*/
export interface IDiffEditorContribution {
/**
* Dispose this contribution.
*/
dispose(): void;
}
/**
* @internal
*/
export function isThemeColor(o: any): o is ThemeColor {
return o && typeof o.id === 'string';
}
/**
* @internal
*/
export interface IThemeDecorationRenderOptions {
backgroundColor?: string | ThemeColor;
outline?: string;
outlineColor?: string | ThemeColor;
outlineStyle?: string;
outlineWidth?: string;
border?: string;
borderColor?: string | ThemeColor;
borderRadius?: string;
borderSpacing?: string;
borderStyle?: string;
borderWidth?: string;
fontStyle?: string;
fontWeight?: string;
fontSize?: string;
textDecoration?: string;
cursor?: string;
color?: string | ThemeColor;
opacity?: string;
letterSpacing?: string;
gutterIconPath?: UriComponents;
gutterIconSize?: string;
overviewRulerColor?: string | ThemeColor;
/**
* @deprecated
*/
before?: IContentDecorationRenderOptions;
/**
* @deprecated
*/
after?: IContentDecorationRenderOptions;
/**
* @deprecated
*/
beforeInjectedText?: IContentDecorationRenderOptions & { affectsLetterSpacing?: boolean };
/**
* @deprecated
*/
afterInjectedText?: IContentDecorationRenderOptions & { affectsLetterSpacing?: boolean };
}
/**
* @internal
*/
export interface IContentDecorationRenderOptions {
contentText?: string;
contentIconPath?: UriComponents;
border?: string;
borderColor?: string | ThemeColor;
borderRadius?: string;
fontStyle?: string;
fontWeight?: string;
fontSize?: string;
fontFamily?: string;
textDecoration?: string;
color?: string | ThemeColor;
backgroundColor?: string | ThemeColor;
opacity?: string;
verticalAlign?: string;
margin?: string;
padding?: string;
width?: string;
height?: string;
}
/**
* @internal
*/
export interface IDecorationRenderOptions extends IThemeDecorationRenderOptions {
isWholeLine?: boolean;
rangeBehavior?: TrackedRangeStickiness;
overviewRulerLane?: OverviewRulerLane;
light?: IThemeDecorationRenderOptions;
dark?: IThemeDecorationRenderOptions;
}
/**
* @internal
*/
export interface IThemeDecorationInstanceRenderOptions {
/**
* @deprecated
*/
before?: IContentDecorationRenderOptions;
/**
* @deprecated
*/
after?: IContentDecorationRenderOptions;
}
/**
* @internal
*/
export interface IDecorationInstanceRenderOptions extends IThemeDecorationInstanceRenderOptions {
light?: IThemeDecorationInstanceRenderOptions;
dark?: IThemeDecorationInstanceRenderOptions;
}
/**
* @internal
*/
export interface IDecorationOptions {
range: IRange;
hoverMessage?: IMarkdownString | IMarkdownString[];
renderOptions?: IDecorationInstanceRenderOptions;
}
/**
* The type of the `IEditor`.
*/
export const EditorType = {
ICodeEditor: 'vs.editor.ICodeEditor',
IDiffEditor: 'vs.editor.IDiffEditor'
};
/**
* Built-in commands.
* @internal
*/
export const enum Handler {
CompositionStart = 'compositionStart',
CompositionEnd = 'compositionEnd',
Type = 'type',
ReplacePreviousChar = 'replacePreviousChar',
CompositionType = 'compositionType',
Paste = 'paste',
Cut = 'cut',
}
/**
* @internal
*/
export interface TypePayload {
text: string;
}
/**
* @internal
*/
export interface ReplacePreviousCharPayload {
text: string;
replaceCharCnt: number;
}
/**
* @internal
*/
export interface CompositionTypePayload {
text: string;
replacePrevCharCnt: number;
replaceNextCharCnt: number;
positionDelta: number;
}
/**
* @internal
*/
export interface PastePayload {
text: string;
pasteOnNewLine: boolean;
multicursorText: string[] | null;
mode: string | null;
}
| src/vs/editor/common/editorCommon.ts | 1 | https://github.com/microsoft/vscode/commit/9ed8380e54351b3aa29002b55bd10098f8866fc1 | [
0.9901131391525269,
0.01286537479609251,
0.00016513722948729992,
0.00017090178153011948,
0.11136772483587265
] |
{
"id": 0,
"code_window": [
"\t\t}\n",
"\t\tthis._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\tpublic layout(dimension?: IDimension): void {\n",
"\t\tthis._configuration.observeContainer(dimension);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tpublic layout(dimension?: IDimension, postponeRendering: boolean = false): void {\n"
],
"file_path": "src/vs/editor/browser/widget/codeEditorWidget.ts",
"type": "replace",
"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.
*--------------------------------------------------------------------------------------------*/
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { Barrier, Promises } from 'vs/base/common/async';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IUserDataInitializer } from 'vs/workbench/services/userData/browser/userDataInit';
import { IProfileResourceInitializer, IUserDataProfileService, IUserDataProfileTemplate } from 'vs/workbench/services/userDataProfile/common/userDataProfile';
import { SettingsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/settingsResource';
import { GlobalStateResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/globalStateResource';
import { KeybindingsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/keybindingsResource';
import { TasksResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/tasksResource';
import { SnippetsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/snippetsResource';
import { ExtensionsResourceInitializer } from 'vs/workbench/services/userDataProfile/browser/extensionsResource';
import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService';
import { isString } from 'vs/base/common/types';
import { IRequestService, asJson } from 'vs/platform/request/common/request';
import { CancellationToken } from 'vs/base/common/cancellation';
import { URI } from 'vs/base/common/uri';
import { ProfileResourceType } from 'vs/platform/userDataProfile/common/userDataProfile';
export class UserDataProfileInitializer implements IUserDataInitializer {
_serviceBrand: any;
private readonly initialized: ProfileResourceType[] = [];
private readonly initializationFinished = new Barrier();
constructor(
@IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService,
@IFileService private readonly fileService: IFileService,
@IUserDataProfileService private readonly userDataProfileService: IUserDataProfileService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IRequestService private readonly requestService: IRequestService,
) {
}
async whenInitializationFinished(): Promise<void> {
await this.initializationFinished.wait();
}
async requiresInitialization(): Promise<boolean> {
if (!this.environmentService.options?.profile?.contents) {
return false;
}
if (!this.storageService.isNew(StorageScope.PROFILE)) {
return false;
}
return true;
}
async initializeRequiredResources(): Promise<void> {
this.logService.trace(`UserDataProfileInitializer#initializeRequiredResources`);
const promises = [];
const profileTemplate = await this.getProfileTemplate();
if (profileTemplate?.settings) {
promises.push(this.initialize(new SettingsResourceInitializer(this.userDataProfileService, this.fileService, this.logService), profileTemplate.settings, ProfileResourceType.Settings));
}
if (profileTemplate?.globalState) {
promises.push(this.initialize(new GlobalStateResourceInitializer(this.storageService), profileTemplate.globalState, ProfileResourceType.GlobalState));
}
await Promise.all(promises);
}
async initializeOtherResources(instantiationService: IInstantiationService): Promise<void> {
try {
this.logService.trace(`UserDataProfileInitializer#initializeOtherResources`);
const promises = [];
const profileTemplate = await this.getProfileTemplate();
if (profileTemplate?.keybindings) {
promises.push(this.initialize(new KeybindingsResourceInitializer(this.userDataProfileService, this.fileService, this.logService), profileTemplate.keybindings, ProfileResourceType.Keybindings));
}
if (profileTemplate?.tasks) {
promises.push(this.initialize(new TasksResourceInitializer(this.userDataProfileService, this.fileService, this.logService), profileTemplate.tasks, ProfileResourceType.Tasks));
}
if (profileTemplate?.snippets) {
promises.push(this.initialize(new SnippetsResourceInitializer(this.userDataProfileService, this.fileService, this.uriIdentityService), profileTemplate.snippets, ProfileResourceType.Snippets));
}
promises.push(this.initializeInstalledExtensions(instantiationService));
await Promises.settled(promises);
} finally {
this.initializationFinished.open();
}
}
private initializeInstalledExtensionsPromise: Promise<void> | undefined;
async initializeInstalledExtensions(instantiationService: IInstantiationService): Promise<void> {
if (!this.initializeInstalledExtensionsPromise) {
const profileTemplate = await this.getProfileTemplate();
if (profileTemplate?.extensions) {
this.initializeInstalledExtensionsPromise = this.initialize(instantiationService.createInstance(ExtensionsResourceInitializer), profileTemplate.extensions, ProfileResourceType.Extensions);
} else {
this.initializeInstalledExtensionsPromise = Promise.resolve();
}
}
return this.initializeInstalledExtensionsPromise;
}
private profileTemplatePromise: Promise<IUserDataProfileTemplate | null> | undefined;
private getProfileTemplate(): Promise<IUserDataProfileTemplate | null> {
if (!this.profileTemplatePromise) {
this.profileTemplatePromise = this.doGetProfileTemplate();
}
return this.profileTemplatePromise;
}
private async doGetProfileTemplate(): Promise<IUserDataProfileTemplate | null> {
if (!this.environmentService.options?.profile?.contents) {
return null;
}
if (isString(this.environmentService.options.profile.contents)) {
try {
return JSON.parse(this.environmentService.options.profile.contents);
} catch (error) {
this.logService.error(error);
return null;
}
}
try {
const url = URI.revive(this.environmentService.options.profile.contents).toString(true);
const context = await this.requestService.request({ type: 'GET', url }, CancellationToken.None);
if (context.res.statusCode === 200) {
return await asJson(context);
} else {
this.logService.warn(`UserDataProfileInitializer: Failed to get profile from URL: ${url}. Status code: ${context.res.statusCode}.`);
}
} catch (error) {
this.logService.error(error);
}
return null;
}
private async initialize(initializer: IProfileResourceInitializer, content: string, profileResource: ProfileResourceType): Promise<void> {
try {
if (this.initialized.includes(profileResource)) {
this.logService.info(`UserDataProfileInitializer: ${profileResource} initialized already.`);
return;
}
this.initialized.push(profileResource);
this.logService.trace(`UserDataProfileInitializer: Initializing ${profileResource}`);
await initializer.initialize(content);
this.logService.info(`UserDataProfileInitializer: Initialized ${profileResource}`);
} catch (error) {
this.logService.info(`UserDataProfileInitializer: Error while initializing ${profileResource}`);
this.logService.error(error);
}
}
}
| src/vs/workbench/services/userDataProfile/browser/userDataProfileInit.ts | 0 | https://github.com/microsoft/vscode/commit/9ed8380e54351b3aa29002b55bd10098f8866fc1 | [
0.0001753552205627784,
0.00017079018289223313,
0.0001677110994933173,
0.0001701505680102855,
0.000002111484263878083
] |
{
"id": 0,
"code_window": [
"\t\t}\n",
"\t\tthis._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\tpublic layout(dimension?: IDimension): void {\n",
"\t\tthis._configuration.observeContainer(dimension);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tpublic layout(dimension?: IDimension, postponeRendering: boolean = false): void {\n"
],
"file_path": "src/vs/editor/browser/widget/codeEditorWidget.ts",
"type": "replace",
"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.
*--------------------------------------------------------------------------------------------*/
import { $, addDisposableListener, append, getWindow, scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';
import { DomEmitter } from 'vs/base/browser/event';
import { ISashEvent as IBaseSashEvent, Orientation, Sash, SashState } from 'vs/base/browser/ui/sash/sash';
import { SmoothScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { pushToEnd, pushToStart, range } from 'vs/base/common/arrays';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { combinedDisposable, Disposable, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { clamp } from 'vs/base/common/numbers';
import { Scrollable, ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable';
import * as types from 'vs/base/common/types';
import 'vs/css!./splitview';
export { Orientation } from 'vs/base/browser/ui/sash/sash';
export interface ISplitViewStyles {
readonly separatorBorder: Color;
}
const defaultStyles: ISplitViewStyles = {
separatorBorder: Color.transparent
};
export const enum LayoutPriority {
Normal,
Low,
High
}
/**
* The interface to implement for views within a {@link SplitView}.
*
* An optional {@link TLayoutContext layout context type} may be used in order to
* pass along layout contextual data from the {@link SplitView.layout} method down
* to each view's {@link IView.layout} calls.
*/
export interface IView<TLayoutContext = undefined> {
/**
* The DOM element for this view.
*/
readonly element: HTMLElement;
/**
* A minimum size for this view.
*
* @remarks If none, set it to `0`.
*/
readonly minimumSize: number;
/**
* A maximum size for this view.
*
* @remarks If none, set it to `Number.POSITIVE_INFINITY`.
*/
readonly maximumSize: number;
/**
* The priority of the view when the {@link SplitView.resize layout} algorithm
* runs. Views with higher priority will be resized first.
*
* @remarks Only used when `proportionalLayout` is false.
*/
readonly priority?: LayoutPriority;
/**
* If the {@link SplitView} supports {@link ISplitViewOptions.proportionalLayout proportional layout},
* this property allows for finer control over the proportional layout algorithm, per view.
*
* @defaultValue `true`
*/
readonly proportionalLayout?: boolean;
/**
* Whether the view will snap whenever the user reaches its minimum size or
* attempts to grow it beyond the minimum size.
*
* @defaultValue `false`
*/
readonly snap?: boolean;
/**
* View instances are supposed to fire the {@link IView.onDidChange} event whenever
* any of the constraint properties have changed:
*
* - {@link IView.minimumSize}
* - {@link IView.maximumSize}
* - {@link IView.priority}
* - {@link IView.snap}
*
* The SplitView will relayout whenever that happens. The event can optionally emit
* the view's preferred size for that relayout.
*/
readonly onDidChange: Event<number | undefined>;
/**
* This will be called by the {@link SplitView} during layout. A view meant to
* pass along the layout information down to its descendants.
*
* @param size The size of this view, in pixels.
* @param offset The offset of this view, relative to the start of the {@link SplitView}.
* @param context The optional {@link IView layout context} passed to {@link SplitView.layout}.
*/
layout(size: number, offset: number, context: TLayoutContext | undefined): void;
/**
* This will be called by the {@link SplitView} whenever this view is made
* visible or hidden.
*
* @param visible Whether the view becomes visible.
*/
setVisible?(visible: boolean): void;
}
/**
* A descriptor for a {@link SplitView} instance.
*/
export interface ISplitViewDescriptor<TLayoutContext = undefined, TView extends IView<TLayoutContext> = IView<TLayoutContext>> {
/**
* The layout size of the {@link SplitView}.
*/
readonly size: number;
/**
* Descriptors for each {@link IView view}.
*/
readonly views: {
/**
* Whether the {@link IView view} is visible.
*
* @defaultValue `true`
*/
readonly visible?: boolean;
/**
* The size of the {@link IView view}.
*
* @defaultValue `true`
*/
readonly size: number;
/**
* The size of the {@link IView view}.
*
* @defaultValue `true`
*/
readonly view: TView;
}[];
}
export interface ISplitViewOptions<TLayoutContext = undefined, TView extends IView<TLayoutContext> = IView<TLayoutContext>> {
/**
* Which axis the views align on.
*
* @defaultValue `Orientation.VERTICAL`
*/
readonly orientation?: Orientation;
/**
* Styles overriding the {@link defaultStyles default ones}.
*/
readonly styles?: ISplitViewStyles;
/**
* Make Alt-drag the default drag operation.
*/
readonly inverseAltBehavior?: boolean;
/**
* Resize each view proportionally when resizing the SplitView.
*
* @defaultValue `true`
*/
readonly proportionalLayout?: boolean;
/**
* An initial description of this {@link SplitView} instance, allowing
* to initialze all views within the ctor.
*/
readonly descriptor?: ISplitViewDescriptor<TLayoutContext, TView>;
/**
* The scrollbar visibility setting for whenever the views within
* the {@link SplitView} overflow.
*/
readonly scrollbarVisibility?: ScrollbarVisibility;
/**
* Override the orthogonal size of sashes.
*/
readonly getSashOrthogonalSize?: () => number;
}
interface ISashEvent {
readonly sash: Sash;
readonly start: number;
readonly current: number;
readonly alt: boolean;
}
type ViewItemSize = number | { cachedVisibleSize: number };
abstract class ViewItem<TLayoutContext, TView extends IView<TLayoutContext>> {
private _size: number;
set size(size: number) {
this._size = size;
}
get size(): number {
return this._size;
}
private _cachedVisibleSize: number | undefined = undefined;
get cachedVisibleSize(): number | undefined { return this._cachedVisibleSize; }
get visible(): boolean {
return typeof this._cachedVisibleSize === 'undefined';
}
setVisible(visible: boolean, size?: number): void {
if (visible === this.visible) {
return;
}
if (visible) {
this.size = clamp(this._cachedVisibleSize!, this.viewMinimumSize, this.viewMaximumSize);
this._cachedVisibleSize = undefined;
} else {
this._cachedVisibleSize = typeof size === 'number' ? size : this.size;
this.size = 0;
}
this.container.classList.toggle('visible', visible);
try {
this.view.setVisible?.(visible);
} catch (e) {
console.error('Splitview: Failed to set visible view');
console.error(e);
}
}
get minimumSize(): number { return this.visible ? this.view.minimumSize : 0; }
get viewMinimumSize(): number { return this.view.minimumSize; }
get maximumSize(): number { return this.visible ? this.view.maximumSize : 0; }
get viewMaximumSize(): number { return this.view.maximumSize; }
get priority(): LayoutPriority | undefined { return this.view.priority; }
get proportionalLayout(): boolean { return this.view.proportionalLayout ?? true; }
get snap(): boolean { return !!this.view.snap; }
set enabled(enabled: boolean) {
this.container.style.pointerEvents = enabled ? '' : 'none';
}
constructor(
protected container: HTMLElement,
readonly view: TView,
size: ViewItemSize,
private disposable: IDisposable
) {
if (typeof size === 'number') {
this._size = size;
this._cachedVisibleSize = undefined;
container.classList.add('visible');
} else {
this._size = 0;
this._cachedVisibleSize = size.cachedVisibleSize;
}
}
layout(offset: number, layoutContext: TLayoutContext | undefined): void {
this.layoutContainer(offset);
try {
this.view.layout(this.size, offset, layoutContext);
} catch (e) {
console.error('Splitview: Failed to layout view');
console.error(e);
}
}
abstract layoutContainer(offset: number): void;
dispose(): void {
this.disposable.dispose();
}
}
class VerticalViewItem<TLayoutContext, TView extends IView<TLayoutContext>> extends ViewItem<TLayoutContext, TView> {
layoutContainer(offset: number): void {
this.container.style.top = `${offset}px`;
this.container.style.height = `${this.size}px`;
}
}
class HorizontalViewItem<TLayoutContext, TView extends IView<TLayoutContext>> extends ViewItem<TLayoutContext, TView> {
layoutContainer(offset: number): void {
this.container.style.left = `${offset}px`;
this.container.style.width = `${this.size}px`;
}
}
interface ISashItem {
sash: Sash;
disposable: IDisposable;
}
interface ISashDragSnapState {
readonly index: number;
readonly limitDelta: number;
readonly size: number;
}
interface ISashDragState {
index: number;
start: number;
current: number;
sizes: number[];
minDelta: number;
maxDelta: number;
alt: boolean;
snapBefore: ISashDragSnapState | undefined;
snapAfter: ISashDragSnapState | undefined;
disposable: IDisposable;
}
enum State {
Idle,
Busy
}
/**
* When adding or removing views, uniformly distribute the entire split view space among
* all views.
*/
export type DistributeSizing = { type: 'distribute' };
/**
* When adding a view, make space for it by reducing the size of another view,
* indexed by the provided `index`.
*/
export type SplitSizing = { type: 'split'; index: number };
/**
* When adding a view, use DistributeSizing when all pre-existing views are
* distributed evenly, otherwise use SplitSizing.
*/
export type AutoSizing = { type: 'auto'; index: number };
/**
* When adding or removing views, assume the view is invisible.
*/
export type InvisibleSizing = { type: 'invisible'; cachedVisibleSize: number };
/**
* When adding or removing views, the sizing provides fine grained
* control over how other views get resized.
*/
export type Sizing = DistributeSizing | SplitSizing | AutoSizing | InvisibleSizing;
export namespace Sizing {
/**
* When adding or removing views, distribute the delta space among
* all other views.
*/
export const Distribute: DistributeSizing = { type: 'distribute' };
/**
* When adding or removing views, split the delta space with another
* specific view, indexed by the provided `index`.
*/
export function Split(index: number): SplitSizing { return { type: 'split', index }; }
/**
* When adding a view, use DistributeSizing when all pre-existing views are
* distributed evenly, otherwise use SplitSizing.
*/
export function Auto(index: number): AutoSizing { return { type: 'auto', index }; }
/**
* When adding or removing views, assume the view is invisible.
*/
export function Invisible(cachedVisibleSize: number): InvisibleSizing { return { type: 'invisible', cachedVisibleSize }; }
}
/**
* The {@link SplitView} is the UI component which implements a one dimensional
* flex-like layout algorithm for a collection of {@link IView} instances, which
* are essentially HTMLElement instances with the following size constraints:
*
* - {@link IView.minimumSize}
* - {@link IView.maximumSize}
* - {@link IView.priority}
* - {@link IView.snap}
*
* In case the SplitView doesn't have enough size to fit all views, it will overflow
* its content with a scrollbar.
*
* In between each pair of views there will be a {@link Sash} allowing the user
* to resize the views, making sure the constraints are respected.
*
* An optional {@link TLayoutContext layout context type} may be used in order to
* pass along layout contextual data from the {@link SplitView.layout} method down
* to each view's {@link IView.layout} calls.
*
* Features:
* - Flex-like layout algorithm
* - Snap support
* - Orthogonal sash support, for corner sashes
* - View hide/show support
* - View swap/move support
* - Alt key modifier behavior, macOS style
*/
export class SplitView<TLayoutContext = undefined, TView extends IView<TLayoutContext> = IView<TLayoutContext>> extends Disposable {
/**
* This {@link SplitView}'s orientation.
*/
readonly orientation: Orientation;
/**
* The DOM element representing this {@link SplitView}.
*/
readonly el: HTMLElement;
private sashContainer: HTMLElement;
private viewContainer: HTMLElement;
private scrollable: Scrollable;
private scrollableElement: SmoothScrollableElement;
private size = 0;
private layoutContext: TLayoutContext | undefined;
private _contentSize = 0;
private proportions: (number | undefined)[] | undefined = undefined;
private viewItems: ViewItem<TLayoutContext, TView>[] = [];
sashItems: ISashItem[] = []; // used in tests
private sashDragState: ISashDragState | undefined;
private state: State = State.Idle;
private inverseAltBehavior: boolean;
private proportionalLayout: boolean;
private readonly getSashOrthogonalSize: { (): number } | undefined;
private _onDidSashChange = this._register(new Emitter<number>());
private _onDidSashReset = this._register(new Emitter<number>());
private _orthogonalStartSash: Sash | undefined;
private _orthogonalEndSash: Sash | undefined;
private _startSnappingEnabled = true;
private _endSnappingEnabled = true;
/**
* The sum of all views' sizes.
*/
get contentSize(): number { return this._contentSize; }
/**
* Fires whenever the user resizes a {@link Sash sash}.
*/
readonly onDidSashChange = this._onDidSashChange.event;
/**
* Fires whenever the user double clicks a {@link Sash sash}.
*/
readonly onDidSashReset = this._onDidSashReset.event;
/**
* Fires whenever the split view is scrolled.
*/
readonly onDidScroll: Event<ScrollEvent>;
/**
* The amount of views in this {@link SplitView}.
*/
get length(): number {
return this.viewItems.length;
}
/**
* The minimum size of this {@link SplitView}.
*/
get minimumSize(): number {
return this.viewItems.reduce((r, item) => r + item.minimumSize, 0);
}
/**
* The maximum size of this {@link SplitView}.
*/
get maximumSize(): number {
return this.length === 0 ? Number.POSITIVE_INFINITY : this.viewItems.reduce((r, item) => r + item.maximumSize, 0);
}
get orthogonalStartSash(): Sash | undefined { return this._orthogonalStartSash; }
get orthogonalEndSash(): Sash | undefined { return this._orthogonalEndSash; }
get startSnappingEnabled(): boolean { return this._startSnappingEnabled; }
get endSnappingEnabled(): boolean { return this._endSnappingEnabled; }
/**
* A reference to a sash, perpendicular to all sashes in this {@link SplitView},
* located at the left- or top-most side of the SplitView.
* Corner sashes will be created automatically at the intersections.
*/
set orthogonalStartSash(sash: Sash | undefined) {
for (const sashItem of this.sashItems) {
sashItem.sash.orthogonalStartSash = sash;
}
this._orthogonalStartSash = sash;
}
/**
* A reference to a sash, perpendicular to all sashes in this {@link SplitView},
* located at the right- or bottom-most side of the SplitView.
* Corner sashes will be created automatically at the intersections.
*/
set orthogonalEndSash(sash: Sash | undefined) {
for (const sashItem of this.sashItems) {
sashItem.sash.orthogonalEndSash = sash;
}
this._orthogonalEndSash = sash;
}
/**
* The internal sashes within this {@link SplitView}.
*/
get sashes(): readonly Sash[] {
return this.sashItems.map(s => s.sash);
}
/**
* Enable/disable snapping at the beginning of this {@link SplitView}.
*/
set startSnappingEnabled(startSnappingEnabled: boolean) {
if (this._startSnappingEnabled === startSnappingEnabled) {
return;
}
this._startSnappingEnabled = startSnappingEnabled;
this.updateSashEnablement();
}
/**
* Enable/disable snapping at the end of this {@link SplitView}.
*/
set endSnappingEnabled(endSnappingEnabled: boolean) {
if (this._endSnappingEnabled === endSnappingEnabled) {
return;
}
this._endSnappingEnabled = endSnappingEnabled;
this.updateSashEnablement();
}
/**
* Create a new {@link SplitView} instance.
*/
constructor(container: HTMLElement, options: ISplitViewOptions<TLayoutContext, TView> = {}) {
super();
this.orientation = options.orientation ?? Orientation.VERTICAL;
this.inverseAltBehavior = options.inverseAltBehavior ?? false;
this.proportionalLayout = options.proportionalLayout ?? true;
this.getSashOrthogonalSize = options.getSashOrthogonalSize;
this.el = document.createElement('div');
this.el.classList.add('monaco-split-view2');
this.el.classList.add(this.orientation === Orientation.VERTICAL ? 'vertical' : 'horizontal');
container.appendChild(this.el);
this.sashContainer = append(this.el, $('.sash-container'));
this.viewContainer = $('.split-view-container');
this.scrollable = this._register(new Scrollable({
forceIntegerValues: true,
smoothScrollDuration: 125,
scheduleAtNextAnimationFrame: callback => scheduleAtNextAnimationFrame(getWindow(this.el), callback),
}));
this.scrollableElement = this._register(new SmoothScrollableElement(this.viewContainer, {
vertical: this.orientation === Orientation.VERTICAL ? (options.scrollbarVisibility ?? ScrollbarVisibility.Auto) : ScrollbarVisibility.Hidden,
horizontal: this.orientation === Orientation.HORIZONTAL ? (options.scrollbarVisibility ?? ScrollbarVisibility.Auto) : ScrollbarVisibility.Hidden
}, this.scrollable));
// https://github.com/microsoft/vscode/issues/157737
const onDidScrollViewContainer = this._register(new DomEmitter(this.viewContainer, 'scroll')).event;
this._register(onDidScrollViewContainer(_ => {
const position = this.scrollableElement.getScrollPosition();
const scrollLeft = Math.abs(this.viewContainer.scrollLeft - position.scrollLeft) <= 1 ? undefined : this.viewContainer.scrollLeft;
const scrollTop = Math.abs(this.viewContainer.scrollTop - position.scrollTop) <= 1 ? undefined : this.viewContainer.scrollTop;
if (scrollLeft !== undefined || scrollTop !== undefined) {
this.scrollableElement.setScrollPosition({ scrollLeft, scrollTop });
}
}));
this.onDidScroll = this.scrollableElement.onScroll;
this._register(this.onDidScroll(e => {
if (e.scrollTopChanged) {
this.viewContainer.scrollTop = e.scrollTop;
}
if (e.scrollLeftChanged) {
this.viewContainer.scrollLeft = e.scrollLeft;
}
}));
append(this.el, this.scrollableElement.getDomNode());
this.style(options.styles || defaultStyles);
// We have an existing set of view, add them now
if (options.descriptor) {
this.size = options.descriptor.size;
options.descriptor.views.forEach((viewDescriptor, index) => {
const sizing = types.isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: 'invisible', cachedVisibleSize: viewDescriptor.size } as InvisibleSizing;
const view = viewDescriptor.view;
this.doAddView(view, sizing, index, true);
});
// Initialize content size and proportions for first layout
this._contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
this.saveProportions();
}
}
style(styles: ISplitViewStyles): void {
if (styles.separatorBorder.isTransparent()) {
this.el.classList.remove('separator-border');
this.el.style.removeProperty('--separator-border');
} else {
this.el.classList.add('separator-border');
this.el.style.setProperty('--separator-border', styles.separatorBorder.toString());
}
}
/**
* Add a {@link IView view} to this {@link SplitView}.
*
* @param view The view to add.
* @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
* @param index The index to insert the view on.
* @param skipLayout Whether layout should be skipped.
*/
addView(view: TView, size: number | Sizing, index = this.viewItems.length, skipLayout?: boolean): void {
this.doAddView(view, size, index, skipLayout);
}
/**
* Remove a {@link IView view} from this {@link SplitView}.
*
* @param index The index where the {@link IView view} is located.
* @param sizing Whether to distribute other {@link IView view}'s sizes.
*/
removeView(index: number, sizing?: Sizing): TView {
if (index < 0 || index >= this.viewItems.length) {
throw new Error('Index out of bounds');
}
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
try {
if (sizing?.type === 'auto') {
if (this.areViewsDistributed()) {
sizing = { type: 'distribute' };
} else {
sizing = { type: 'split', index: sizing.index };
}
}
// Save referene view, in case of `split` sizing
const referenceViewItem = sizing?.type === 'split' ? this.viewItems[sizing.index] : undefined;
// Remove view
const viewItemToRemove = this.viewItems.splice(index, 1)[0];
// Resize reference view, in case of `split` sizing
if (referenceViewItem) {
referenceViewItem.size += viewItemToRemove.size;
}
// Remove sash
if (this.viewItems.length >= 1) {
const sashIndex = Math.max(index - 1, 0);
const sashItem = this.sashItems.splice(sashIndex, 1)[0];
sashItem.disposable.dispose();
}
this.relayout();
if (sizing?.type === 'distribute') {
this.distributeViewSizes();
}
const result = viewItemToRemove.view;
viewItemToRemove.dispose();
return result;
} finally {
this.state = State.Idle;
}
}
removeAllViews(): TView[] {
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
try {
const viewItems = this.viewItems.splice(0, this.viewItems.length);
for (const viewItem of viewItems) {
viewItem.dispose();
}
const sashItems = this.sashItems.splice(0, this.sashItems.length);
for (const sashItem of sashItems) {
sashItem.disposable.dispose();
}
this.relayout();
return viewItems.map(i => i.view);
} finally {
this.state = State.Idle;
}
}
/**
* Move a {@link IView view} to a different index.
*
* @param from The source index.
* @param to The target index.
*/
moveView(from: number, to: number): void {
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
const cachedVisibleSize = this.getViewCachedVisibleSize(from);
const sizing = typeof cachedVisibleSize === 'undefined' ? this.getViewSize(from) : Sizing.Invisible(cachedVisibleSize);
const view = this.removeView(from);
this.addView(view, sizing, to);
}
/**
* Swap two {@link IView views}.
*
* @param from The source index.
* @param to The target index.
*/
swapViews(from: number, to: number): void {
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
if (from > to) {
return this.swapViews(to, from);
}
const fromSize = this.getViewSize(from);
const toSize = this.getViewSize(to);
const toView = this.removeView(to);
const fromView = this.removeView(from);
this.addView(toView, fromSize, from);
this.addView(fromView, toSize, to);
}
/**
* Returns whether the {@link IView view} is visible.
*
* @param index The {@link IView view} index.
*/
isViewVisible(index: number): boolean {
if (index < 0 || index >= this.viewItems.length) {
throw new Error('Index out of bounds');
}
const viewItem = this.viewItems[index];
return viewItem.visible;
}
/**
* Set a {@link IView view}'s visibility.
*
* @param index The {@link IView view} index.
* @param visible Whether the {@link IView view} should be visible.
*/
setViewVisible(index: number, visible: boolean): void {
if (index < 0 || index >= this.viewItems.length) {
throw new Error('Index out of bounds');
}
const viewItem = this.viewItems[index];
viewItem.setVisible(visible);
this.distributeEmptySpace(index);
this.layoutViews();
this.saveProportions();
}
/**
* Returns the {@link IView view}'s size previously to being hidden.
*
* @param index The {@link IView view} index.
*/
getViewCachedVisibleSize(index: number): number | undefined {
if (index < 0 || index >= this.viewItems.length) {
throw new Error('Index out of bounds');
}
const viewItem = this.viewItems[index];
return viewItem.cachedVisibleSize;
}
/**
* Layout the {@link SplitView}.
*
* @param size The entire size of the {@link SplitView}.
* @param layoutContext An optional layout context to pass along to {@link IView views}.
*/
layout(size: number, layoutContext?: TLayoutContext): void {
const previousSize = Math.max(this.size, this._contentSize);
this.size = size;
this.layoutContext = layoutContext;
if (!this.proportions) {
const indexes = range(this.viewItems.length);
const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.Low);
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.High);
this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes);
} else {
let total = 0;
for (let i = 0; i < this.viewItems.length; i++) {
const item = this.viewItems[i];
const proportion = this.proportions[i];
if (typeof proportion === 'number') {
total += proportion;
} else {
size -= item.size;
}
}
for (let i = 0; i < this.viewItems.length; i++) {
const item = this.viewItems[i];
const proportion = this.proportions[i];
if (typeof proportion === 'number' && total > 0) {
item.size = clamp(Math.round(proportion * size / total), item.minimumSize, item.maximumSize);
}
}
}
this.distributeEmptySpace();
this.layoutViews();
}
private saveProportions(): void {
if (this.proportionalLayout && this._contentSize > 0) {
this.proportions = this.viewItems.map(v => v.proportionalLayout && v.visible ? v.size / this._contentSize : undefined);
}
}
private onSashStart({ sash, start, alt }: ISashEvent): void {
for (const item of this.viewItems) {
item.enabled = false;
}
const index = this.sashItems.findIndex(item => item.sash === sash);
// This way, we can press Alt while we resize a sash, macOS style!
const disposable = combinedDisposable(
addDisposableListener(this.el.ownerDocument.body, 'keydown', e => resetSashDragState(this.sashDragState!.current, e.altKey)),
addDisposableListener(this.el.ownerDocument.body, 'keyup', () => resetSashDragState(this.sashDragState!.current, false))
);
const resetSashDragState = (start: number, alt: boolean) => {
const sizes = this.viewItems.map(i => i.size);
let minDelta = Number.NEGATIVE_INFINITY;
let maxDelta = Number.POSITIVE_INFINITY;
if (this.inverseAltBehavior) {
alt = !alt;
}
if (alt) {
// When we're using the last sash with Alt, we're resizing
// the view to the left/up, instead of right/down as usual
// Thus, we must do the inverse of the usual
const isLastSash = index === this.sashItems.length - 1;
if (isLastSash) {
const viewItem = this.viewItems[index];
minDelta = (viewItem.minimumSize - viewItem.size) / 2;
maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
} else {
const viewItem = this.viewItems[index + 1];
minDelta = (viewItem.size - viewItem.maximumSize) / 2;
maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
}
}
let snapBefore: ISashDragSnapState | undefined;
let snapAfter: ISashDragSnapState | undefined;
if (!alt) {
const upIndexes = range(index, -1);
const downIndexes = range(index + 1, this.viewItems.length);
const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].viewMaximumSize - sizes[i]), 0);
const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].viewMaximumSize), 0);
const minDelta = Math.max(minDeltaUp, minDeltaDown);
const maxDelta = Math.min(maxDeltaDown, maxDeltaUp);
const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
if (typeof snapBeforeIndex === 'number') {
const viewItem = this.viewItems[snapBeforeIndex];
const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
snapBefore = {
index: snapBeforeIndex,
limitDelta: viewItem.visible ? minDelta - halfSize : minDelta + halfSize,
size: viewItem.size
};
}
if (typeof snapAfterIndex === 'number') {
const viewItem = this.viewItems[snapAfterIndex];
const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
snapAfter = {
index: snapAfterIndex,
limitDelta: viewItem.visible ? maxDelta + halfSize : maxDelta - halfSize,
size: viewItem.size
};
}
}
this.sashDragState = { start, current: start, index, sizes, minDelta, maxDelta, alt, snapBefore, snapAfter, disposable };
};
resetSashDragState(start, alt);
}
private onSashChange({ current }: ISashEvent): void {
const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.sashDragState!;
this.sashDragState!.current = current;
const delta = current - start;
const newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta, snapBefore, snapAfter);
if (alt) {
const isLastSash = index === this.sashItems.length - 1;
const newSizes = this.viewItems.map(i => i.size);
const viewItemIndex = isLastSash ? index : index + 1;
const viewItem = this.viewItems[viewItemIndex];
const newMinDelta = viewItem.size - viewItem.maximumSize;
const newMaxDelta = viewItem.size - viewItem.minimumSize;
const resizeIndex = isLastSash ? index - 1 : index + 1;
this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta);
}
this.distributeEmptySpace();
this.layoutViews();
}
private onSashEnd(index: number): void {
this._onDidSashChange.fire(index);
this.sashDragState!.disposable.dispose();
this.saveProportions();
for (const item of this.viewItems) {
item.enabled = true;
}
}
private onViewChange(item: ViewItem<TLayoutContext, TView>, size: number | undefined): void {
const index = this.viewItems.indexOf(item);
if (index < 0 || index >= this.viewItems.length) {
return;
}
size = typeof size === 'number' ? size : item.size;
size = clamp(size, item.minimumSize, item.maximumSize);
if (this.inverseAltBehavior && index > 0) {
// In this case, we want the view to grow or shrink both sides equally
// so we just resize the "left" side by half and let `resize` do the clamping magic
this.resize(index - 1, Math.floor((item.size - size) / 2));
this.distributeEmptySpace();
this.layoutViews();
} else {
item.size = size;
this.relayout([index], undefined);
}
}
/**
* Resize a {@link IView view} within the {@link SplitView}.
*
* @param index The {@link IView view} index.
* @param size The {@link IView view} size.
*/
resizeView(index: number, size: number): void {
if (index < 0 || index >= this.viewItems.length) {
return;
}
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
try {
const indexes = range(this.viewItems.length).filter(i => i !== index);
const lowPriorityIndexes = [...indexes.filter(i => this.viewItems[i].priority === LayoutPriority.Low), index];
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.High);
const item = this.viewItems[index];
size = Math.round(size);
size = clamp(size, item.minimumSize, Math.min(item.maximumSize, this.size));
item.size = size;
this.relayout(lowPriorityIndexes, highPriorityIndexes);
} finally {
this.state = State.Idle;
}
}
/**
* Returns whether all other {@link IView views} are at their minimum size.
*/
isViewExpanded(index: number): boolean {
if (index < 0 || index >= this.viewItems.length) {
return false;
}
for (const item of this.viewItems) {
if (item !== this.viewItems[index] && item.size > item.minimumSize) {
return false;
}
}
return true;
}
/**
* Distribute the entire {@link SplitView} size among all {@link IView views}.
*/
distributeViewSizes(): void {
const flexibleViewItems: ViewItem<TLayoutContext, TView>[] = [];
let flexibleSize = 0;
for (const item of this.viewItems) {
if (item.maximumSize - item.minimumSize > 0) {
flexibleViewItems.push(item);
flexibleSize += item.size;
}
}
const size = Math.floor(flexibleSize / flexibleViewItems.length);
for (const item of flexibleViewItems) {
item.size = clamp(size, item.minimumSize, item.maximumSize);
}
const indexes = range(this.viewItems.length);
const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.Low);
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.High);
this.relayout(lowPriorityIndexes, highPriorityIndexes);
}
/**
* Returns the size of a {@link IView view}.
*/
getViewSize(index: number): number {
if (index < 0 || index >= this.viewItems.length) {
return -1;
}
return this.viewItems[index].size;
}
private doAddView(view: TView, size: number | Sizing, index = this.viewItems.length, skipLayout?: boolean): void {
if (this.state !== State.Idle) {
throw new Error('Cant modify splitview');
}
this.state = State.Busy;
try {
// Add view
const container = $('.split-view-view');
if (index === this.viewItems.length) {
this.viewContainer.appendChild(container);
} else {
this.viewContainer.insertBefore(container, this.viewContainer.children.item(index));
}
const onChangeDisposable = view.onDidChange(size => this.onViewChange(item, size));
const containerDisposable = toDisposable(() => this.viewContainer.removeChild(container));
const disposable = combinedDisposable(onChangeDisposable, containerDisposable);
let viewSize: ViewItemSize;
if (typeof size === 'number') {
viewSize = size;
} else {
if (size.type === 'auto') {
if (this.areViewsDistributed()) {
size = { type: 'distribute' };
} else {
size = { type: 'split', index: size.index };
}
}
if (size.type === 'split') {
viewSize = this.getViewSize(size.index) / 2;
} else if (size.type === 'invisible') {
viewSize = { cachedVisibleSize: size.cachedVisibleSize };
} else {
viewSize = view.minimumSize;
}
}
const item = this.orientation === Orientation.VERTICAL
? new VerticalViewItem(container, view, viewSize, disposable)
: new HorizontalViewItem(container, view, viewSize, disposable);
this.viewItems.splice(index, 0, item);
// Add sash
if (this.viewItems.length > 1) {
const opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
const sash = this.orientation === Orientation.VERTICAL
? new Sash(this.sashContainer, { getHorizontalSashTop: s => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, { ...opts, orientation: Orientation.HORIZONTAL })
: new Sash(this.sashContainer, { getVerticalSashLeft: s => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, { ...opts, orientation: Orientation.VERTICAL });
const sashEventMapper = this.orientation === Orientation.VERTICAL
? (e: IBaseSashEvent) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey })
: (e: IBaseSashEvent) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey });
const onStart = Event.map(sash.onDidStart, sashEventMapper);
const onStartDisposable = onStart(this.onSashStart, this);
const onChange = Event.map(sash.onDidChange, sashEventMapper);
const onChangeDisposable = onChange(this.onSashChange, this);
const onEnd = Event.map(sash.onDidEnd, () => this.sashItems.findIndex(item => item.sash === sash));
const onEndDisposable = onEnd(this.onSashEnd, this);
const onDidResetDisposable = sash.onDidReset(() => {
const index = this.sashItems.findIndex(item => item.sash === sash);
const upIndexes = range(index, -1);
const downIndexes = range(index + 1, this.viewItems.length);
const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
if (typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible) {
return;
}
if (typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible) {
return;
}
this._onDidSashReset.fire(index);
});
const disposable = combinedDisposable(onStartDisposable, onChangeDisposable, onEndDisposable, onDidResetDisposable, sash);
const sashItem: ISashItem = { sash, disposable };
this.sashItems.splice(index - 1, 0, sashItem);
}
container.appendChild(view.element);
let highPriorityIndexes: number[] | undefined;
if (typeof size !== 'number' && size.type === 'split') {
highPriorityIndexes = [size.index];
}
if (!skipLayout) {
this.relayout([index], highPriorityIndexes);
}
if (!skipLayout && typeof size !== 'number' && size.type === 'distribute') {
this.distributeViewSizes();
}
} finally {
this.state = State.Idle;
}
}
private relayout(lowPriorityIndexes?: number[], highPriorityIndexes?: number[]): void {
const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes);
this.distributeEmptySpace();
this.layoutViews();
this.saveProportions();
}
private resize(
index: number,
delta: number,
sizes = this.viewItems.map(i => i.size),
lowPriorityIndexes?: number[],
highPriorityIndexes?: number[],
overloadMinDelta: number = Number.NEGATIVE_INFINITY,
overloadMaxDelta: number = Number.POSITIVE_INFINITY,
snapBefore?: ISashDragSnapState,
snapAfter?: ISashDragSnapState
): number {
if (index < 0 || index >= this.viewItems.length) {
return 0;
}
const upIndexes = range(index, -1);
const downIndexes = range(index + 1, this.viewItems.length);
if (highPriorityIndexes) {
for (const index of highPriorityIndexes) {
pushToStart(upIndexes, index);
pushToStart(downIndexes, index);
}
}
if (lowPriorityIndexes) {
for (const index of lowPriorityIndexes) {
pushToEnd(upIndexes, index);
pushToEnd(downIndexes, index);
}
}
const upItems = upIndexes.map(i => this.viewItems[i]);
const upSizes = upIndexes.map(i => sizes[i]);
const downItems = downIndexes.map(i => this.viewItems[i]);
const downSizes = downIndexes.map(i => sizes[i]);
const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].maximumSize - sizes[i]), 0);
const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].maximumSize), 0);
const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
let snapped = false;
if (snapBefore) {
const snapView = this.viewItems[snapBefore.index];
const visible = delta >= snapBefore.limitDelta;
snapped = visible !== snapView.visible;
snapView.setVisible(visible, snapBefore.size);
}
if (!snapped && snapAfter) {
const snapView = this.viewItems[snapAfter.index];
const visible = delta < snapAfter.limitDelta;
snapped = visible !== snapView.visible;
snapView.setVisible(visible, snapAfter.size);
}
if (snapped) {
return this.resize(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
}
delta = clamp(delta, minDelta, maxDelta);
for (let i = 0, deltaUp = delta; i < upItems.length; i++) {
const item = upItems[i];
const size = clamp(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize);
const viewDelta = size - upSizes[i];
deltaUp -= viewDelta;
item.size = size;
}
for (let i = 0, deltaDown = delta; i < downItems.length; i++) {
const item = downItems[i];
const size = clamp(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize);
const viewDelta = size - downSizes[i];
deltaDown += viewDelta;
item.size = size;
}
return delta;
}
private distributeEmptySpace(lowPriorityIndex?: number): void {
const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
let emptyDelta = this.size - contentSize;
const indexes = range(this.viewItems.length - 1, -1);
const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.Low);
const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === LayoutPriority.High);
for (const index of highPriorityIndexes) {
pushToStart(indexes, index);
}
for (const index of lowPriorityIndexes) {
pushToEnd(indexes, index);
}
if (typeof lowPriorityIndex === 'number') {
pushToEnd(indexes, lowPriorityIndex);
}
for (let i = 0; emptyDelta !== 0 && i < indexes.length; i++) {
const item = this.viewItems[indexes[i]];
const size = clamp(item.size + emptyDelta, item.minimumSize, item.maximumSize);
const viewDelta = size - item.size;
emptyDelta -= viewDelta;
item.size = size;
}
}
private layoutViews(): void {
// Save new content size
this._contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
// Layout views
let offset = 0;
for (const viewItem of this.viewItems) {
viewItem.layout(offset, this.layoutContext);
offset += viewItem.size;
}
// Layout sashes
this.sashItems.forEach(item => item.sash.layout());
this.updateSashEnablement();
this.updateScrollableElement();
}
private updateScrollableElement(): void {
if (this.orientation === Orientation.VERTICAL) {
this.scrollableElement.setScrollDimensions({
height: this.size,
scrollHeight: this._contentSize
});
} else {
this.scrollableElement.setScrollDimensions({
width: this.size,
scrollWidth: this._contentSize
});
}
}
private updateSashEnablement(): void {
let previous = false;
const collapsesDown = this.viewItems.map(i => previous = (i.size - i.minimumSize > 0) || previous);
previous = false;
const expandsDown = this.viewItems.map(i => previous = (i.maximumSize - i.size > 0) || previous);
const reverseViews = [...this.viewItems].reverse();
previous = false;
const collapsesUp = reverseViews.map(i => previous = (i.size - i.minimumSize > 0) || previous).reverse();
previous = false;
const expandsUp = reverseViews.map(i => previous = (i.maximumSize - i.size > 0) || previous).reverse();
let position = 0;
for (let index = 0; index < this.sashItems.length; index++) {
const { sash } = this.sashItems[index];
const viewItem = this.viewItems[index];
position += viewItem.size;
const min = !(collapsesDown[index] && expandsUp[index + 1]);
const max = !(expandsDown[index] && collapsesUp[index + 1]);
if (min && max) {
const upIndexes = range(index, -1);
const downIndexes = range(index + 1, this.viewItems.length);
const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
const snappedBefore = typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible;
const snappedAfter = typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible;
if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
sash.state = SashState.AtMinimum;
} else if (snappedAfter && collapsesDown[index] && (position < this._contentSize || this.endSnappingEnabled)) {
sash.state = SashState.AtMaximum;
} else {
sash.state = SashState.Disabled;
}
} else if (min && !max) {
sash.state = SashState.AtMinimum;
} else if (!min && max) {
sash.state = SashState.AtMaximum;
} else {
sash.state = SashState.Enabled;
}
}
}
private getSashPosition(sash: Sash): number {
let position = 0;
for (let i = 0; i < this.sashItems.length; i++) {
position += this.viewItems[i].size;
if (this.sashItems[i].sash === sash) {
return position;
}
}
return 0;
}
private findFirstSnapIndex(indexes: number[]): number | undefined {
// visible views first
for (const index of indexes) {
const viewItem = this.viewItems[index];
if (!viewItem.visible) {
continue;
}
if (viewItem.snap) {
return index;
}
}
// then, hidden views
for (const index of indexes) {
const viewItem = this.viewItems[index];
if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
return undefined;
}
if (!viewItem.visible && viewItem.snap) {
return index;
}
}
return undefined;
}
private areViewsDistributed() {
let min = undefined, max = undefined;
for (const view of this.viewItems) {
min = min === undefined ? view.size : Math.min(min, view.size);
max = max === undefined ? view.size : Math.max(max, view.size);
if (max - min > 2) {
return false;
}
}
return true;
}
override dispose(): void {
this.sashDragState?.disposable.dispose();
dispose(this.viewItems);
this.viewItems = [];
this.sashItems.forEach(i => i.disposable.dispose());
this.sashItems = [];
super.dispose();
}
}
| src/vs/base/browser/ui/splitview/splitview.ts | 0 | https://github.com/microsoft/vscode/commit/9ed8380e54351b3aa29002b55bd10098f8866fc1 | [
0.9975958466529846,
0.030438732355833054,
0.00016367963689845055,
0.00016949330165516585,
0.16261300444602966
] |
{
"id": 0,
"code_window": [
"\t\t}\n",
"\t\tthis._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\tpublic layout(dimension?: IDimension): void {\n",
"\t\tthis._configuration.observeContainer(dimension);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tpublic layout(dimension?: IDimension, postponeRendering: boolean = false): void {\n"
],
"file_path": "src/vs/editor/browser/widget/codeEditorWidget.ts",
"type": "replace",
"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.
*--------------------------------------------------------------------------------------------*/
import { OutputItem, RendererContext } from 'vscode-notebook-renderer';
import { Event } from 'vscode';
export interface IDisposable {
dispose(): void;
}
export interface HtmlRenderingHook {
/**
* Invoked after the output item has been rendered but before it has been appended to the document.
*
* @return A new `HTMLElement` or `undefined` to continue using the provided element.
*/
postRender(outputItem: OutputItem, element: HTMLElement, signal: AbortSignal): HTMLElement | undefined | Promise<HTMLElement | undefined>;
}
export interface JavaScriptRenderingHook {
/**
* Invoked before the script is evaluated.
*
* @return A new string of JavaScript or `undefined` to continue using the provided string.
*/
preEvaluate(outputItem: OutputItem, element: HTMLElement, script: string, signal: AbortSignal): string | undefined | Promise<string | undefined>;
}
export interface RenderOptions {
readonly lineLimit: number;
readonly outputScrolling: boolean;
readonly outputWordWrap: boolean;
}
export type IRichRenderContext = RendererContext<void> & { readonly settings: RenderOptions; readonly onDidChangeSettings: Event<RenderOptions> };
export type OutputElementOptions = {
linesLimit: number;
scrollable?: boolean;
error?: boolean;
trustHtml?: boolean;
};
export interface OutputWithAppend extends OutputItem {
appendedText?(): string | undefined;
}
| extensions/notebook-renderers/src/rendererTypes.ts | 0 | https://github.com/microsoft/vscode/commit/9ed8380e54351b3aa29002b55bd10098f8866fc1 | [
0.00017297269369009882,
0.00016847792721819133,
0.00016522764053661376,
0.00016840930038597435,
0.000002681063506315695
] |
{
"id": 0,
"code_window": [
" \"@babel/plugin-syntax-jsx\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-object-rest-spread\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-optional-catch-binding\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-pipeline-operator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-arrow-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-async-to-generator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoped-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoping\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-syntax-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 40
} | /**
* Entry point for @babel/standalone. This wraps Babel's API in a version that's
* friendlier for use in web browers. It removes the automagical detection of
* plugins, instead explicitly registering all the available plugins and
* presets, and requiring custom ones to be registered through `registerPlugin`
* and `registerPreset` respectively.
*/
/* global VERSION */
/* eslint-disable max-len */
import * as Babel from "@babel/core";
import { runScripts } from "./transformScriptTags";
const isArray =
Array.isArray ||
(arg => Object.prototype.toString.call(arg) === "[object Array]");
/**
* Loads the given name (or [name, options] pair) from the given table object
* holding the available presets or plugins.
*
* Returns undefined if the preset or plugin is not available; passes through
* name unmodified if it (or the first element of the pair) is not a string.
*/
function loadBuiltin(builtinTable, name) {
if (isArray(name) && typeof name[0] === "string") {
if (builtinTable.hasOwnProperty(name[0])) {
return [builtinTable[name[0]]].concat(name.slice(1));
}
return;
} else if (typeof name === "string") {
return builtinTable[name];
}
// Could be an actual preset/plugin module
return name;
}
/**
* Parses plugin names and presets from the specified options.
*/
function processOptions(options) {
// Parse preset names
const presets = (options.presets || []).map(presetName => {
const preset = loadBuiltin(availablePresets, presetName);
if (preset) {
// workaround for babel issue
// at some point, babel copies the preset, losing the non-enumerable
// buildPreset key; convert it into an enumerable key.
if (
isArray(preset) &&
typeof preset[0] === "object" &&
preset[0].hasOwnProperty("buildPreset")
) {
preset[0] = { ...preset[0], buildPreset: preset[0].buildPreset };
}
} else {
throw new Error(
`Invalid preset specified in Babel options: "${presetName}"`,
);
}
return preset;
});
// Parse plugin names
const plugins = (options.plugins || []).map(pluginName => {
const plugin = loadBuiltin(availablePlugins, pluginName);
if (!plugin) {
throw new Error(
`Invalid plugin specified in Babel options: "${pluginName}"`,
);
}
return plugin;
});
return {
babelrc: false,
...options,
presets,
plugins,
};
}
export function transform(code, options) {
return Babel.transform(code, processOptions(options));
}
export function transformFromAst(ast, code, options) {
return Babel.transformFromAst(ast, code, processOptions(options));
}
export const availablePlugins = {};
export const availablePresets = {};
export const buildExternalHelpers = Babel.buildExternalHelpers;
/**
* Registers a named plugin for use with Babel.
*/
export function registerPlugin(name, plugin) {
if (availablePlugins.hasOwnProperty(name)) {
console.warn(
`A plugin named "${name}" is already registered, it will be overridden`,
);
}
availablePlugins[name] = plugin;
}
/**
* Registers multiple plugins for use with Babel. `newPlugins` should be an object where the key
* is the name of the plugin, and the value is the plugin itself.
*/
export function registerPlugins(newPlugins) {
Object.keys(newPlugins).forEach(name =>
registerPlugin(name, newPlugins[name]),
);
}
/**
* Registers a named preset for use with Babel.
*/
export function registerPreset(name, preset) {
if (availablePresets.hasOwnProperty(name)) {
console.warn(
`A preset named "${name}" is already registered, it will be overridden`,
);
}
availablePresets[name] = preset;
}
/**
* Registers multiple presets for use with Babel. `newPresets` should be an object where the key
* is the name of the preset, and the value is the preset itself.
*/
export function registerPresets(newPresets) {
Object.keys(newPresets).forEach(name =>
registerPreset(name, newPresets[name]),
);
}
// All the plugins we should bundle
// Want to get rid of this long whitelist of plugins?
// Wait! Please read https://github.com/babel/babel/pull/6177 first.
registerPlugins({
"check-constants": require("@babel/plugin-check-constants"),
"external-helpers": require("@babel/plugin-external-helpers"),
"syntax-async-generators": require("@babel/plugin-syntax-async-generators"),
"syntax-class-properties": require("@babel/plugin-syntax-class-properties"),
"syntax-decorators": require("@babel/plugin-syntax-decorators"),
"syntax-do-expressions": require("@babel/plugin-syntax-do-expressions"),
"syntax-dynamic-import": require("@babel/plugin-syntax-dynamic-import"),
"syntax-export-default-from": require("@babel/plugin-syntax-export-default-from"),
"syntax-export-namespace-from": require("@babel/plugin-syntax-export-namespace-from"),
"syntax-flow": require("@babel/plugin-syntax-flow"),
"syntax-function-bind": require("@babel/plugin-syntax-function-bind"),
"syntax-function-sent": require("@babel/plugin-syntax-function-sent"),
"syntax-import-meta": require("@babel/plugin-syntax-import-meta"),
"syntax-jsx": require("@babel/plugin-syntax-jsx"),
"syntax-object-rest-spread": require("@babel/plugin-syntax-object-rest-spread"),
"syntax-optional-catch-binding": require("@babel/plugin-syntax-optional-catch-binding"),
"syntax-pipeline-operator": require("@babel/plugin-syntax-pipeline-operator"),
"transform-async-to-generator": require("@babel/plugin-transform-async-to-generator"),
"proposal-async-generator-functions": require("@babel/plugin-proposal-async-generator-functions"),
"proposal-class-properties": require("@babel/plugin-proposal-class-properties"),
"proposal-decorators": require("@babel/plugin-proposal-decorators"),
"proposal-do-expressions": require("@babel/plugin-proposal-do-expressions"),
"proposal-export-default-from": require("@babel/plugin-proposal-export-default-from"),
"proposal-export-namespace-from": require("@babel/plugin-proposal-export-namespace-from"),
"proposal-pipeline-operator": require("@babel/plugin-proposal-pipeline-operator"),
"transform-arrow-functions": require("@babel/plugin-transform-arrow-functions"),
"transform-block-scoped-functions": require("@babel/plugin-transform-block-scoped-functions"),
"transform-block-scoping": require("@babel/plugin-transform-block-scoping"),
"transform-classes": require("@babel/plugin-transform-classes"),
"transform-computed-properties": require("@babel/plugin-transform-computed-properties"),
"transform-destructuring": require("@babel/plugin-transform-destructuring"),
"transform-dotall-regex": require("@babel/plugin-transform-dotall-regex"),
"transform-duplicate-keys": require("@babel/plugin-transform-duplicate-keys"),
"transform-for-of": require("@babel/plugin-transform-for-of"),
"transform-function-name": require("@babel/plugin-transform-function-name"),
"transform-instanceof": require("@babel/plugin-transform-instanceof"),
"transform-literals": require("@babel/plugin-transform-literals"),
"transform-modules-amd": require("@babel/plugin-transform-modules-amd"),
"transform-modules-commonjs": require("@babel/plugin-transform-modules-commonjs"),
"transform-modules-systemjs": require("@babel/plugin-transform-modules-systemjs"),
"transform-modules-umd": require("@babel/plugin-transform-modules-umd"),
"transform-object-super": require("@babel/plugin-transform-object-super"),
"transform-parameters": require("@babel/plugin-transform-parameters"),
"transform-shorthand-properties": require("@babel/plugin-transform-shorthand-properties"),
"transform-spread": require("@babel/plugin-transform-spread"),
"transform-sticky-regex": require("@babel/plugin-transform-sticky-regex"),
"transform-template-literals": require("@babel/plugin-transform-template-literals"),
"transform-typeof-symbol": require("@babel/plugin-transform-typeof-symbol"),
"transform-unicode-regex": require("@babel/plugin-transform-unicode-regex"),
"transform-member-expression-literals": require("@babel/plugin-transform-member-expression-literals"),
"transform-property-literals": require("@babel/plugin-transform-property-literals"),
"transform-property-mutators": require("@babel/plugin-transform-property-mutators"),
"transform-eval": require("@babel/plugin-transform-eval"),
"transform-exponentiation-operator": require("@babel/plugin-transform-exponentiation-operator"),
"transform-flow-comments": require("@babel/plugin-transform-flow-comments"),
"transform-flow-strip-types": require("@babel/plugin-transform-flow-strip-types"),
"proposal-function-bind": require("@babel/plugin-proposal-function-bind"),
"transform-jscript": require("@babel/plugin-transform-jscript"),
"transform-new-target": require("@babel/plugin-transform-new-target"),
"transform-object-assign": require("@babel/plugin-transform-object-assign"),
"proposal-object-rest-spread": require("@babel/plugin-proposal-object-rest-spread"),
"transform-object-set-prototype-of-to-assign": require("@babel/plugin-transform-object-set-prototype-of-to-assign"),
"proposal-optional-catch-binding": require("@babel/plugin-proposal-optional-catch-binding"),
"transform-proto-to-assign": require("@babel/plugin-transform-proto-to-assign"),
"transform-react-constant-elements": require("@babel/plugin-transform-react-constant-elements"),
"transform-react-display-name": require("@babel/plugin-transform-react-display-name"),
"transform-react-inline-elements": require("@babel/plugin-transform-react-inline-elements"),
"transform-react-jsx": require("@babel/plugin-transform-react-jsx"),
"transform-react-jsx-compat": require("@babel/plugin-transform-react-jsx-compat"),
"transform-react-jsx-self": require("@babel/plugin-transform-react-jsx-self"),
"transform-react-jsx-source": require("@babel/plugin-transform-react-jsx-source"),
"transform-regenerator": require("@babel/plugin-transform-regenerator"),
"transform-runtime": require("@babel/plugin-transform-runtime"),
"transform-strict-mode": require("@babel/plugin-transform-strict-mode"),
"proposal-unicode-property-regex": require("@babel/plugin-proposal-unicode-property-regex"),
});
// All the presets we should bundle
// Want to get rid of this whitelist of presets?
// Wait! Please read https://github.com/babel/babel/pull/6177 first.
registerPresets({
es2015: require("@babel/preset-es2015"),
es2016: require("@babel/preset-es2016"),
es2017: require("@babel/preset-es2017"),
react: require("@babel/preset-react"),
"stage-0": require("@babel/preset-stage-0"),
"stage-1": require("@babel/preset-stage-1"),
"stage-2": require("@babel/preset-stage-2"),
"stage-3": require("@babel/preset-stage-3"),
"es2015-loose": {
presets: [[require("@babel/preset-es2015"), { loose: true }]],
},
// ES2015 preset with es2015-modules-commonjs removed
"es2015-no-commonjs": {
presets: [[require("@babel/preset-es2015"), { modules: false }]],
},
typescript: require("@babel/preset-typescript"),
flow: require("@babel/preset-flow"),
});
export const version = VERSION;
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts with "text/babel" type.
if (typeof window !== "undefined" && window && window.addEventListener) {
window.addEventListener(
"DOMContentLoaded",
() => transformScriptTags(),
false,
);
}
/**
* Transform <script> tags with "text/babel" type.
* @param {Array} scriptTags specify script tags to transform, transform all in the <head> if not given
*/
export function transformScriptTags(scriptTags) {
runScripts(transform, scriptTags);
}
/**
* Disables automatic transformation of <script> tags with "text/babel" type.
*/
export function disableScriptTags() {
window.removeEventListener("DOMContentLoaded", transformScriptTags);
}
| packages/babel-standalone/src/index.js | 1 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0008177387644536793,
0.00020278204465284944,
0.0001576876238686964,
0.00016954987950157374,
0.00012293831969145685
] |
{
"id": 0,
"code_window": [
" \"@babel/plugin-syntax-jsx\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-object-rest-spread\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-optional-catch-binding\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-pipeline-operator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-arrow-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-async-to-generator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoped-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoping\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-syntax-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 40
} | {
"type": "File",
"start": 0,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 11
}
},
"program": {
"type": "Program",
"start": 0,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 11
}
},
"sourceType": "script",
"body": [
{
"type": "ExpressionStatement",
"start": 0,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 11
}
},
"expression": {
"type": "LogicalExpression",
"start": 0,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 11
}
},
"left": {
"type": "LogicalExpression",
"start": 0,
"end": 6,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 6
}
},
"left": {
"type": "Identifier",
"start": 0,
"end": 1,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
},
"identifierName": "x"
},
"name": "x"
},
"operator": "||",
"right": {
"type": "Identifier",
"start": 5,
"end": 6,
"loc": {
"start": {
"line": 1,
"column": 5
},
"end": {
"line": 1,
"column": 6
},
"identifierName": "y"
},
"name": "y"
}
},
"operator": "||",
"right": {
"type": "Identifier",
"start": 10,
"end": 11,
"loc": {
"start": {
"line": 1,
"column": 10
},
"end": {
"line": 1,
"column": 11
},
"identifierName": "z"
},
"name": "z"
}
}
}
],
"directives": []
}
} | packages/babylon/test/fixtures/esprima/expression-binary-logical/migrated_0002/expected.json | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0001771147653926164,
0.0001724063913570717,
0.00016868796956259757,
0.00017256999853998423,
0.000002132737563442788
] |
{
"id": 0,
"code_window": [
" \"@babel/plugin-syntax-jsx\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-object-rest-spread\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-optional-catch-binding\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-pipeline-operator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-arrow-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-async-to-generator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoped-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoping\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-syntax-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 40
} | {
"type": "File",
"start": 0,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
},
"program": {
"type": "Program",
"start": 0,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
},
"sourceType": "script",
"body": [
{
"type": "ExpressionStatement",
"start": 0,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
},
"expression": {
"type": "AssignmentExpression",
"start": 0,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
},
"operator": "=",
"left": {
"type": "Identifier",
"start": 0,
"end": 2,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 2
},
"identifierName": "T"
},
"name": "T"
},
"right": {
"type": "ArrayExpression",
"start": 5,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 5
},
"end": {
"line": 1,
"column": 7
}
},
"elements": []
}
}
}
],
"directives": []
}
} | packages/babylon/test/fixtures/core/uncategorised/17/expected.json | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.00017642471357248724,
0.00017249613301828504,
0.00016955813043750823,
0.00017256540013477206,
0.0000016347396467608633
] |
{
"id": 0,
"code_window": [
" \"@babel/plugin-syntax-jsx\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-object-rest-spread\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-optional-catch-binding\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-syntax-pipeline-operator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-arrow-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-async-to-generator\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoped-functions\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-block-scoping\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-syntax-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 40
} | declare export * as test from ''
| packages/babylon/test/fixtures/flow/declare-export/export-star-as/actual.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0001680382847553119,
0.0001680382847553119,
0.0001680382847553119,
0.0001680382847553119,
0
] |
{
"id": 1,
"code_window": [
" \"@babel/plugin-transform-sticky-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-strict-mode\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-template-literals\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-typeof-symbol\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-unicode-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2015\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2016\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2017\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-transform-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 86
} | /**
* Entry point for @babel/standalone. This wraps Babel's API in a version that's
* friendlier for use in web browers. It removes the automagical detection of
* plugins, instead explicitly registering all the available plugins and
* presets, and requiring custom ones to be registered through `registerPlugin`
* and `registerPreset` respectively.
*/
/* global VERSION */
/* eslint-disable max-len */
import * as Babel from "@babel/core";
import { runScripts } from "./transformScriptTags";
const isArray =
Array.isArray ||
(arg => Object.prototype.toString.call(arg) === "[object Array]");
/**
* Loads the given name (or [name, options] pair) from the given table object
* holding the available presets or plugins.
*
* Returns undefined if the preset or plugin is not available; passes through
* name unmodified if it (or the first element of the pair) is not a string.
*/
function loadBuiltin(builtinTable, name) {
if (isArray(name) && typeof name[0] === "string") {
if (builtinTable.hasOwnProperty(name[0])) {
return [builtinTable[name[0]]].concat(name.slice(1));
}
return;
} else if (typeof name === "string") {
return builtinTable[name];
}
// Could be an actual preset/plugin module
return name;
}
/**
* Parses plugin names and presets from the specified options.
*/
function processOptions(options) {
// Parse preset names
const presets = (options.presets || []).map(presetName => {
const preset = loadBuiltin(availablePresets, presetName);
if (preset) {
// workaround for babel issue
// at some point, babel copies the preset, losing the non-enumerable
// buildPreset key; convert it into an enumerable key.
if (
isArray(preset) &&
typeof preset[0] === "object" &&
preset[0].hasOwnProperty("buildPreset")
) {
preset[0] = { ...preset[0], buildPreset: preset[0].buildPreset };
}
} else {
throw new Error(
`Invalid preset specified in Babel options: "${presetName}"`,
);
}
return preset;
});
// Parse plugin names
const plugins = (options.plugins || []).map(pluginName => {
const plugin = loadBuiltin(availablePlugins, pluginName);
if (!plugin) {
throw new Error(
`Invalid plugin specified in Babel options: "${pluginName}"`,
);
}
return plugin;
});
return {
babelrc: false,
...options,
presets,
plugins,
};
}
export function transform(code, options) {
return Babel.transform(code, processOptions(options));
}
export function transformFromAst(ast, code, options) {
return Babel.transformFromAst(ast, code, processOptions(options));
}
export const availablePlugins = {};
export const availablePresets = {};
export const buildExternalHelpers = Babel.buildExternalHelpers;
/**
* Registers a named plugin for use with Babel.
*/
export function registerPlugin(name, plugin) {
if (availablePlugins.hasOwnProperty(name)) {
console.warn(
`A plugin named "${name}" is already registered, it will be overridden`,
);
}
availablePlugins[name] = plugin;
}
/**
* Registers multiple plugins for use with Babel. `newPlugins` should be an object where the key
* is the name of the plugin, and the value is the plugin itself.
*/
export function registerPlugins(newPlugins) {
Object.keys(newPlugins).forEach(name =>
registerPlugin(name, newPlugins[name]),
);
}
/**
* Registers a named preset for use with Babel.
*/
export function registerPreset(name, preset) {
if (availablePresets.hasOwnProperty(name)) {
console.warn(
`A preset named "${name}" is already registered, it will be overridden`,
);
}
availablePresets[name] = preset;
}
/**
* Registers multiple presets for use with Babel. `newPresets` should be an object where the key
* is the name of the preset, and the value is the preset itself.
*/
export function registerPresets(newPresets) {
Object.keys(newPresets).forEach(name =>
registerPreset(name, newPresets[name]),
);
}
// All the plugins we should bundle
// Want to get rid of this long whitelist of plugins?
// Wait! Please read https://github.com/babel/babel/pull/6177 first.
registerPlugins({
"check-constants": require("@babel/plugin-check-constants"),
"external-helpers": require("@babel/plugin-external-helpers"),
"syntax-async-generators": require("@babel/plugin-syntax-async-generators"),
"syntax-class-properties": require("@babel/plugin-syntax-class-properties"),
"syntax-decorators": require("@babel/plugin-syntax-decorators"),
"syntax-do-expressions": require("@babel/plugin-syntax-do-expressions"),
"syntax-dynamic-import": require("@babel/plugin-syntax-dynamic-import"),
"syntax-export-default-from": require("@babel/plugin-syntax-export-default-from"),
"syntax-export-namespace-from": require("@babel/plugin-syntax-export-namespace-from"),
"syntax-flow": require("@babel/plugin-syntax-flow"),
"syntax-function-bind": require("@babel/plugin-syntax-function-bind"),
"syntax-function-sent": require("@babel/plugin-syntax-function-sent"),
"syntax-import-meta": require("@babel/plugin-syntax-import-meta"),
"syntax-jsx": require("@babel/plugin-syntax-jsx"),
"syntax-object-rest-spread": require("@babel/plugin-syntax-object-rest-spread"),
"syntax-optional-catch-binding": require("@babel/plugin-syntax-optional-catch-binding"),
"syntax-pipeline-operator": require("@babel/plugin-syntax-pipeline-operator"),
"transform-async-to-generator": require("@babel/plugin-transform-async-to-generator"),
"proposal-async-generator-functions": require("@babel/plugin-proposal-async-generator-functions"),
"proposal-class-properties": require("@babel/plugin-proposal-class-properties"),
"proposal-decorators": require("@babel/plugin-proposal-decorators"),
"proposal-do-expressions": require("@babel/plugin-proposal-do-expressions"),
"proposal-export-default-from": require("@babel/plugin-proposal-export-default-from"),
"proposal-export-namespace-from": require("@babel/plugin-proposal-export-namespace-from"),
"proposal-pipeline-operator": require("@babel/plugin-proposal-pipeline-operator"),
"transform-arrow-functions": require("@babel/plugin-transform-arrow-functions"),
"transform-block-scoped-functions": require("@babel/plugin-transform-block-scoped-functions"),
"transform-block-scoping": require("@babel/plugin-transform-block-scoping"),
"transform-classes": require("@babel/plugin-transform-classes"),
"transform-computed-properties": require("@babel/plugin-transform-computed-properties"),
"transform-destructuring": require("@babel/plugin-transform-destructuring"),
"transform-dotall-regex": require("@babel/plugin-transform-dotall-regex"),
"transform-duplicate-keys": require("@babel/plugin-transform-duplicate-keys"),
"transform-for-of": require("@babel/plugin-transform-for-of"),
"transform-function-name": require("@babel/plugin-transform-function-name"),
"transform-instanceof": require("@babel/plugin-transform-instanceof"),
"transform-literals": require("@babel/plugin-transform-literals"),
"transform-modules-amd": require("@babel/plugin-transform-modules-amd"),
"transform-modules-commonjs": require("@babel/plugin-transform-modules-commonjs"),
"transform-modules-systemjs": require("@babel/plugin-transform-modules-systemjs"),
"transform-modules-umd": require("@babel/plugin-transform-modules-umd"),
"transform-object-super": require("@babel/plugin-transform-object-super"),
"transform-parameters": require("@babel/plugin-transform-parameters"),
"transform-shorthand-properties": require("@babel/plugin-transform-shorthand-properties"),
"transform-spread": require("@babel/plugin-transform-spread"),
"transform-sticky-regex": require("@babel/plugin-transform-sticky-regex"),
"transform-template-literals": require("@babel/plugin-transform-template-literals"),
"transform-typeof-symbol": require("@babel/plugin-transform-typeof-symbol"),
"transform-unicode-regex": require("@babel/plugin-transform-unicode-regex"),
"transform-member-expression-literals": require("@babel/plugin-transform-member-expression-literals"),
"transform-property-literals": require("@babel/plugin-transform-property-literals"),
"transform-property-mutators": require("@babel/plugin-transform-property-mutators"),
"transform-eval": require("@babel/plugin-transform-eval"),
"transform-exponentiation-operator": require("@babel/plugin-transform-exponentiation-operator"),
"transform-flow-comments": require("@babel/plugin-transform-flow-comments"),
"transform-flow-strip-types": require("@babel/plugin-transform-flow-strip-types"),
"proposal-function-bind": require("@babel/plugin-proposal-function-bind"),
"transform-jscript": require("@babel/plugin-transform-jscript"),
"transform-new-target": require("@babel/plugin-transform-new-target"),
"transform-object-assign": require("@babel/plugin-transform-object-assign"),
"proposal-object-rest-spread": require("@babel/plugin-proposal-object-rest-spread"),
"transform-object-set-prototype-of-to-assign": require("@babel/plugin-transform-object-set-prototype-of-to-assign"),
"proposal-optional-catch-binding": require("@babel/plugin-proposal-optional-catch-binding"),
"transform-proto-to-assign": require("@babel/plugin-transform-proto-to-assign"),
"transform-react-constant-elements": require("@babel/plugin-transform-react-constant-elements"),
"transform-react-display-name": require("@babel/plugin-transform-react-display-name"),
"transform-react-inline-elements": require("@babel/plugin-transform-react-inline-elements"),
"transform-react-jsx": require("@babel/plugin-transform-react-jsx"),
"transform-react-jsx-compat": require("@babel/plugin-transform-react-jsx-compat"),
"transform-react-jsx-self": require("@babel/plugin-transform-react-jsx-self"),
"transform-react-jsx-source": require("@babel/plugin-transform-react-jsx-source"),
"transform-regenerator": require("@babel/plugin-transform-regenerator"),
"transform-runtime": require("@babel/plugin-transform-runtime"),
"transform-strict-mode": require("@babel/plugin-transform-strict-mode"),
"proposal-unicode-property-regex": require("@babel/plugin-proposal-unicode-property-regex"),
});
// All the presets we should bundle
// Want to get rid of this whitelist of presets?
// Wait! Please read https://github.com/babel/babel/pull/6177 first.
registerPresets({
es2015: require("@babel/preset-es2015"),
es2016: require("@babel/preset-es2016"),
es2017: require("@babel/preset-es2017"),
react: require("@babel/preset-react"),
"stage-0": require("@babel/preset-stage-0"),
"stage-1": require("@babel/preset-stage-1"),
"stage-2": require("@babel/preset-stage-2"),
"stage-3": require("@babel/preset-stage-3"),
"es2015-loose": {
presets: [[require("@babel/preset-es2015"), { loose: true }]],
},
// ES2015 preset with es2015-modules-commonjs removed
"es2015-no-commonjs": {
presets: [[require("@babel/preset-es2015"), { modules: false }]],
},
typescript: require("@babel/preset-typescript"),
flow: require("@babel/preset-flow"),
});
export const version = VERSION;
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts with "text/babel" type.
if (typeof window !== "undefined" && window && window.addEventListener) {
window.addEventListener(
"DOMContentLoaded",
() => transformScriptTags(),
false,
);
}
/**
* Transform <script> tags with "text/babel" type.
* @param {Array} scriptTags specify script tags to transform, transform all in the <head> if not given
*/
export function transformScriptTags(scriptTags) {
runScripts(transform, scriptTags);
}
/**
* Disables automatic transformation of <script> tags with "text/babel" type.
*/
export function disableScriptTags() {
window.removeEventListener("DOMContentLoaded", transformScriptTags);
}
| packages/babel-standalone/src/index.js | 1 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0010938715422526002,
0.0002249381795991212,
0.00015821747365407646,
0.00016633636550977826,
0.0001849456602940336
] |
{
"id": 1,
"code_window": [
" \"@babel/plugin-transform-sticky-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-strict-mode\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-template-literals\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-typeof-symbol\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-unicode-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2015\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2016\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2017\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-transform-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 86
} | import { Modal } from "react-bootstrap";
export default CustomModal = () => <Modal.Header>foobar</Modal.Header>;
| packages/babel-plugin-transform-react-inline-elements/test/fixtures/inline-elements/member-expression/actual.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.00017006785492412746,
0.00017006785492412746,
0.00017006785492412746,
0.00017006785492412746,
0
] |
{
"id": 1,
"code_window": [
" \"@babel/plugin-transform-sticky-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-strict-mode\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-template-literals\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-typeof-symbol\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-unicode-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2015\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2016\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2017\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-transform-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 86
} | function hello() {'use strict'; ({ s: function eval() { } }); }
| packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0207/actual.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0001696250692475587,
0.0001696250692475587,
0.0001696250692475587,
0.0001696250692475587,
0
] |
{
"id": 1,
"code_window": [
" \"@babel/plugin-transform-sticky-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-strict-mode\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-template-literals\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-typeof-symbol\": \"7.0.0-beta.36\",\n",
" \"@babel/plugin-transform-unicode-regex\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2015\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2016\": \"7.0.0-beta.36\",\n",
" \"@babel/preset-es2017\": \"7.0.0-beta.36\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@babel/plugin-transform-typescript\": \"^7.0.0-beta.36\",\n"
],
"file_path": "packages/babel-standalone/package.json",
"type": "add",
"edit_start_line_idx": 86
} | done: while (true) { break done } | packages/babylon/test/fixtures/core/uncategorised/255/actual.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.00017074623610824347,
0.00017074623610824347,
0.00017074623610824347,
0.00017074623610824347,
0
] |
{
"id": 2,
"code_window": [
" \"syntax-import-meta\": require(\"@babel/plugin-syntax-import-meta\"),\n",
" \"syntax-jsx\": require(\"@babel/plugin-syntax-jsx\"),\n",
" \"syntax-object-rest-spread\": require(\"@babel/plugin-syntax-object-rest-spread\"),\n",
" \"syntax-optional-catch-binding\": require(\"@babel/plugin-syntax-optional-catch-binding\"),\n",
" \"syntax-pipeline-operator\": require(\"@babel/plugin-syntax-pipeline-operator\"),\n",
" \"transform-async-to-generator\": require(\"@babel/plugin-transform-async-to-generator\"),\n",
" \"proposal-async-generator-functions\": require(\"@babel/plugin-proposal-async-generator-functions\"),\n",
" \"proposal-class-properties\": require(\"@babel/plugin-proposal-class-properties\"),\n",
" \"proposal-decorators\": require(\"@babel/plugin-proposal-decorators\"),\n",
" \"proposal-do-expressions\": require(\"@babel/plugin-proposal-do-expressions\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"syntax-typescript\": require(\"@babel/plugin-syntax-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 159
} | /**
* Entry point for @babel/standalone. This wraps Babel's API in a version that's
* friendlier for use in web browers. It removes the automagical detection of
* plugins, instead explicitly registering all the available plugins and
* presets, and requiring custom ones to be registered through `registerPlugin`
* and `registerPreset` respectively.
*/
/* global VERSION */
/* eslint-disable max-len */
import * as Babel from "@babel/core";
import { runScripts } from "./transformScriptTags";
const isArray =
Array.isArray ||
(arg => Object.prototype.toString.call(arg) === "[object Array]");
/**
* Loads the given name (or [name, options] pair) from the given table object
* holding the available presets or plugins.
*
* Returns undefined if the preset or plugin is not available; passes through
* name unmodified if it (or the first element of the pair) is not a string.
*/
function loadBuiltin(builtinTable, name) {
if (isArray(name) && typeof name[0] === "string") {
if (builtinTable.hasOwnProperty(name[0])) {
return [builtinTable[name[0]]].concat(name.slice(1));
}
return;
} else if (typeof name === "string") {
return builtinTable[name];
}
// Could be an actual preset/plugin module
return name;
}
/**
* Parses plugin names and presets from the specified options.
*/
function processOptions(options) {
// Parse preset names
const presets = (options.presets || []).map(presetName => {
const preset = loadBuiltin(availablePresets, presetName);
if (preset) {
// workaround for babel issue
// at some point, babel copies the preset, losing the non-enumerable
// buildPreset key; convert it into an enumerable key.
if (
isArray(preset) &&
typeof preset[0] === "object" &&
preset[0].hasOwnProperty("buildPreset")
) {
preset[0] = { ...preset[0], buildPreset: preset[0].buildPreset };
}
} else {
throw new Error(
`Invalid preset specified in Babel options: "${presetName}"`,
);
}
return preset;
});
// Parse plugin names
const plugins = (options.plugins || []).map(pluginName => {
const plugin = loadBuiltin(availablePlugins, pluginName);
if (!plugin) {
throw new Error(
`Invalid plugin specified in Babel options: "${pluginName}"`,
);
}
return plugin;
});
return {
babelrc: false,
...options,
presets,
plugins,
};
}
export function transform(code, options) {
return Babel.transform(code, processOptions(options));
}
export function transformFromAst(ast, code, options) {
return Babel.transformFromAst(ast, code, processOptions(options));
}
export const availablePlugins = {};
export const availablePresets = {};
export const buildExternalHelpers = Babel.buildExternalHelpers;
/**
* Registers a named plugin for use with Babel.
*/
export function registerPlugin(name, plugin) {
if (availablePlugins.hasOwnProperty(name)) {
console.warn(
`A plugin named "${name}" is already registered, it will be overridden`,
);
}
availablePlugins[name] = plugin;
}
/**
* Registers multiple plugins for use with Babel. `newPlugins` should be an object where the key
* is the name of the plugin, and the value is the plugin itself.
*/
export function registerPlugins(newPlugins) {
Object.keys(newPlugins).forEach(name =>
registerPlugin(name, newPlugins[name]),
);
}
/**
* Registers a named preset for use with Babel.
*/
export function registerPreset(name, preset) {
if (availablePresets.hasOwnProperty(name)) {
console.warn(
`A preset named "${name}" is already registered, it will be overridden`,
);
}
availablePresets[name] = preset;
}
/**
* Registers multiple presets for use with Babel. `newPresets` should be an object where the key
* is the name of the preset, and the value is the preset itself.
*/
export function registerPresets(newPresets) {
Object.keys(newPresets).forEach(name =>
registerPreset(name, newPresets[name]),
);
}
// All the plugins we should bundle
// Want to get rid of this long whitelist of plugins?
// Wait! Please read https://github.com/babel/babel/pull/6177 first.
registerPlugins({
"check-constants": require("@babel/plugin-check-constants"),
"external-helpers": require("@babel/plugin-external-helpers"),
"syntax-async-generators": require("@babel/plugin-syntax-async-generators"),
"syntax-class-properties": require("@babel/plugin-syntax-class-properties"),
"syntax-decorators": require("@babel/plugin-syntax-decorators"),
"syntax-do-expressions": require("@babel/plugin-syntax-do-expressions"),
"syntax-dynamic-import": require("@babel/plugin-syntax-dynamic-import"),
"syntax-export-default-from": require("@babel/plugin-syntax-export-default-from"),
"syntax-export-namespace-from": require("@babel/plugin-syntax-export-namespace-from"),
"syntax-flow": require("@babel/plugin-syntax-flow"),
"syntax-function-bind": require("@babel/plugin-syntax-function-bind"),
"syntax-function-sent": require("@babel/plugin-syntax-function-sent"),
"syntax-import-meta": require("@babel/plugin-syntax-import-meta"),
"syntax-jsx": require("@babel/plugin-syntax-jsx"),
"syntax-object-rest-spread": require("@babel/plugin-syntax-object-rest-spread"),
"syntax-optional-catch-binding": require("@babel/plugin-syntax-optional-catch-binding"),
"syntax-pipeline-operator": require("@babel/plugin-syntax-pipeline-operator"),
"transform-async-to-generator": require("@babel/plugin-transform-async-to-generator"),
"proposal-async-generator-functions": require("@babel/plugin-proposal-async-generator-functions"),
"proposal-class-properties": require("@babel/plugin-proposal-class-properties"),
"proposal-decorators": require("@babel/plugin-proposal-decorators"),
"proposal-do-expressions": require("@babel/plugin-proposal-do-expressions"),
"proposal-export-default-from": require("@babel/plugin-proposal-export-default-from"),
"proposal-export-namespace-from": require("@babel/plugin-proposal-export-namespace-from"),
"proposal-pipeline-operator": require("@babel/plugin-proposal-pipeline-operator"),
"transform-arrow-functions": require("@babel/plugin-transform-arrow-functions"),
"transform-block-scoped-functions": require("@babel/plugin-transform-block-scoped-functions"),
"transform-block-scoping": require("@babel/plugin-transform-block-scoping"),
"transform-classes": require("@babel/plugin-transform-classes"),
"transform-computed-properties": require("@babel/plugin-transform-computed-properties"),
"transform-destructuring": require("@babel/plugin-transform-destructuring"),
"transform-dotall-regex": require("@babel/plugin-transform-dotall-regex"),
"transform-duplicate-keys": require("@babel/plugin-transform-duplicate-keys"),
"transform-for-of": require("@babel/plugin-transform-for-of"),
"transform-function-name": require("@babel/plugin-transform-function-name"),
"transform-instanceof": require("@babel/plugin-transform-instanceof"),
"transform-literals": require("@babel/plugin-transform-literals"),
"transform-modules-amd": require("@babel/plugin-transform-modules-amd"),
"transform-modules-commonjs": require("@babel/plugin-transform-modules-commonjs"),
"transform-modules-systemjs": require("@babel/plugin-transform-modules-systemjs"),
"transform-modules-umd": require("@babel/plugin-transform-modules-umd"),
"transform-object-super": require("@babel/plugin-transform-object-super"),
"transform-parameters": require("@babel/plugin-transform-parameters"),
"transform-shorthand-properties": require("@babel/plugin-transform-shorthand-properties"),
"transform-spread": require("@babel/plugin-transform-spread"),
"transform-sticky-regex": require("@babel/plugin-transform-sticky-regex"),
"transform-template-literals": require("@babel/plugin-transform-template-literals"),
"transform-typeof-symbol": require("@babel/plugin-transform-typeof-symbol"),
"transform-unicode-regex": require("@babel/plugin-transform-unicode-regex"),
"transform-member-expression-literals": require("@babel/plugin-transform-member-expression-literals"),
"transform-property-literals": require("@babel/plugin-transform-property-literals"),
"transform-property-mutators": require("@babel/plugin-transform-property-mutators"),
"transform-eval": require("@babel/plugin-transform-eval"),
"transform-exponentiation-operator": require("@babel/plugin-transform-exponentiation-operator"),
"transform-flow-comments": require("@babel/plugin-transform-flow-comments"),
"transform-flow-strip-types": require("@babel/plugin-transform-flow-strip-types"),
"proposal-function-bind": require("@babel/plugin-proposal-function-bind"),
"transform-jscript": require("@babel/plugin-transform-jscript"),
"transform-new-target": require("@babel/plugin-transform-new-target"),
"transform-object-assign": require("@babel/plugin-transform-object-assign"),
"proposal-object-rest-spread": require("@babel/plugin-proposal-object-rest-spread"),
"transform-object-set-prototype-of-to-assign": require("@babel/plugin-transform-object-set-prototype-of-to-assign"),
"proposal-optional-catch-binding": require("@babel/plugin-proposal-optional-catch-binding"),
"transform-proto-to-assign": require("@babel/plugin-transform-proto-to-assign"),
"transform-react-constant-elements": require("@babel/plugin-transform-react-constant-elements"),
"transform-react-display-name": require("@babel/plugin-transform-react-display-name"),
"transform-react-inline-elements": require("@babel/plugin-transform-react-inline-elements"),
"transform-react-jsx": require("@babel/plugin-transform-react-jsx"),
"transform-react-jsx-compat": require("@babel/plugin-transform-react-jsx-compat"),
"transform-react-jsx-self": require("@babel/plugin-transform-react-jsx-self"),
"transform-react-jsx-source": require("@babel/plugin-transform-react-jsx-source"),
"transform-regenerator": require("@babel/plugin-transform-regenerator"),
"transform-runtime": require("@babel/plugin-transform-runtime"),
"transform-strict-mode": require("@babel/plugin-transform-strict-mode"),
"proposal-unicode-property-regex": require("@babel/plugin-proposal-unicode-property-regex"),
});
// All the presets we should bundle
// Want to get rid of this whitelist of presets?
// Wait! Please read https://github.com/babel/babel/pull/6177 first.
registerPresets({
es2015: require("@babel/preset-es2015"),
es2016: require("@babel/preset-es2016"),
es2017: require("@babel/preset-es2017"),
react: require("@babel/preset-react"),
"stage-0": require("@babel/preset-stage-0"),
"stage-1": require("@babel/preset-stage-1"),
"stage-2": require("@babel/preset-stage-2"),
"stage-3": require("@babel/preset-stage-3"),
"es2015-loose": {
presets: [[require("@babel/preset-es2015"), { loose: true }]],
},
// ES2015 preset with es2015-modules-commonjs removed
"es2015-no-commonjs": {
presets: [[require("@babel/preset-es2015"), { modules: false }]],
},
typescript: require("@babel/preset-typescript"),
flow: require("@babel/preset-flow"),
});
export const version = VERSION;
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts with "text/babel" type.
if (typeof window !== "undefined" && window && window.addEventListener) {
window.addEventListener(
"DOMContentLoaded",
() => transformScriptTags(),
false,
);
}
/**
* Transform <script> tags with "text/babel" type.
* @param {Array} scriptTags specify script tags to transform, transform all in the <head> if not given
*/
export function transformScriptTags(scriptTags) {
runScripts(transform, scriptTags);
}
/**
* Disables automatic transformation of <script> tags with "text/babel" type.
*/
export function disableScriptTags() {
window.removeEventListener("DOMContentLoaded", transformScriptTags);
}
| packages/babel-standalone/src/index.js | 1 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.988946259021759,
0.03847040981054306,
0.0001572298351675272,
0.0001695835089776665,
0.18651682138442993
] |
{
"id": 2,
"code_window": [
" \"syntax-import-meta\": require(\"@babel/plugin-syntax-import-meta\"),\n",
" \"syntax-jsx\": require(\"@babel/plugin-syntax-jsx\"),\n",
" \"syntax-object-rest-spread\": require(\"@babel/plugin-syntax-object-rest-spread\"),\n",
" \"syntax-optional-catch-binding\": require(\"@babel/plugin-syntax-optional-catch-binding\"),\n",
" \"syntax-pipeline-operator\": require(\"@babel/plugin-syntax-pipeline-operator\"),\n",
" \"transform-async-to-generator\": require(\"@babel/plugin-transform-async-to-generator\"),\n",
" \"proposal-async-generator-functions\": require(\"@babel/plugin-proposal-async-generator-functions\"),\n",
" \"proposal-class-properties\": require(\"@babel/plugin-proposal-class-properties\"),\n",
" \"proposal-decorators\": require(\"@babel/plugin-proposal-decorators\"),\n",
" \"proposal-do-expressions\": require(\"@babel/plugin-proposal-do-expressions\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"syntax-typescript\": require(\"@babel/plugin-syntax-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 159
} | var s = Symbol('s');
assert.equal(typeof s, 'symbol');
assert.equal(s.constructor, Symbol);
assert.isFalse(s instanceof Symbol);
assert.throws(() => {
new Symbol;
});
// TODO(jjb): Our impl not to spec so generators can use Symbols without
// requiring transcoding
// assert.equal(s.toString(), 'Symbol(s)');
assert.equal(s.valueOf(), s);
| packages/babel-preset-es2015/test/fixtures/traceur/Symbol/ObjectModel.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0001706334442133084,
0.00017013499746099114,
0.00016963656526058912,
0.00017013499746099114,
4.984394763596356e-7
] |
{
"id": 2,
"code_window": [
" \"syntax-import-meta\": require(\"@babel/plugin-syntax-import-meta\"),\n",
" \"syntax-jsx\": require(\"@babel/plugin-syntax-jsx\"),\n",
" \"syntax-object-rest-spread\": require(\"@babel/plugin-syntax-object-rest-spread\"),\n",
" \"syntax-optional-catch-binding\": require(\"@babel/plugin-syntax-optional-catch-binding\"),\n",
" \"syntax-pipeline-operator\": require(\"@babel/plugin-syntax-pipeline-operator\"),\n",
" \"transform-async-to-generator\": require(\"@babel/plugin-transform-async-to-generator\"),\n",
" \"proposal-async-generator-functions\": require(\"@babel/plugin-proposal-async-generator-functions\"),\n",
" \"proposal-class-properties\": require(\"@babel/plugin-proposal-class-properties\"),\n",
" \"proposal-decorators\": require(\"@babel/plugin-proposal-decorators\"),\n",
" \"proposal-do-expressions\": require(\"@babel/plugin-proposal-do-expressions\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"syntax-typescript\": require(\"@babel/plugin-syntax-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 159
} | interface X {
foobar<T>(): void;
delete<T>(): void;
yield<T>(): void;
do<T>(): void;
};
| packages/babylon/test/fixtures/flow/type-parameter-declaration/interface-reserved-word/actual.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.00017017425852827728,
0.00017017425852827728,
0.00017017425852827728,
0.00017017425852827728,
0
] |
{
"id": 2,
"code_window": [
" \"syntax-import-meta\": require(\"@babel/plugin-syntax-import-meta\"),\n",
" \"syntax-jsx\": require(\"@babel/plugin-syntax-jsx\"),\n",
" \"syntax-object-rest-spread\": require(\"@babel/plugin-syntax-object-rest-spread\"),\n",
" \"syntax-optional-catch-binding\": require(\"@babel/plugin-syntax-optional-catch-binding\"),\n",
" \"syntax-pipeline-operator\": require(\"@babel/plugin-syntax-pipeline-operator\"),\n",
" \"transform-async-to-generator\": require(\"@babel/plugin-transform-async-to-generator\"),\n",
" \"proposal-async-generator-functions\": require(\"@babel/plugin-proposal-async-generator-functions\"),\n",
" \"proposal-class-properties\": require(\"@babel/plugin-proposal-class-properties\"),\n",
" \"proposal-decorators\": require(\"@babel/plugin-proposal-decorators\"),\n",
" \"proposal-do-expressions\": require(\"@babel/plugin-proposal-do-expressions\"),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"syntax-typescript\": require(\"@babel/plugin-syntax-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 159
} | import transformTypeScript from "@babel/plugin-transform-typescript";
export default function() {
return {
plugins: [transformTypeScript],
};
}
| packages/babel-preset-typescript/src/index.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.00016360427252948284,
0.00016360427252948284,
0.00016360427252948284,
0.00016360427252948284,
0
] |
{
"id": 3,
"code_window": [
" \"transform-sticky-regex\": require(\"@babel/plugin-transform-sticky-regex\"),\n",
" \"transform-template-literals\": require(\"@babel/plugin-transform-template-literals\"),\n",
" \"transform-typeof-symbol\": require(\"@babel/plugin-transform-typeof-symbol\"),\n",
" \"transform-unicode-regex\": require(\"@babel/plugin-transform-unicode-regex\"),\n",
" \"transform-member-expression-literals\": require(\"@babel/plugin-transform-member-expression-literals\"),\n",
" \"transform-property-literals\": require(\"@babel/plugin-transform-property-literals\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-typescript\": require(\"@babel/plugin-transform-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 190
} | {
"name": "@babel/standalone",
"version": "7.0.0-beta.36",
"description": "Standalone build of Babel for use in non-Node.js environments.",
"main": "babel.js",
"files": [
"babel.js",
"babel.min.js",
"src"
],
"devDependencies": {
"@babel/core": "7.0.0-beta.36",
"@babel/plugin-check-constants": "7.0.0-beta.36",
"@babel/plugin-external-helpers": "7.0.0-beta.36",
"@babel/plugin-proposal-async-generator-functions": "7.0.0-beta.36",
"@babel/plugin-proposal-class-properties": "7.0.0-beta.36",
"@babel/plugin-proposal-decorators": "7.0.0-beta.36",
"@babel/plugin-proposal-do-expressions": "7.0.0-beta.36",
"@babel/plugin-proposal-export-default-from": "7.0.0-beta.36",
"@babel/plugin-proposal-export-namespace-from": "7.0.0-beta.36",
"@babel/plugin-proposal-function-bind": "7.0.0-beta.36",
"@babel/plugin-proposal-object-rest-spread": "7.0.0-beta.36",
"@babel/plugin-proposal-optional-catch-binding": "7.0.0-beta.36",
"@babel/plugin-proposal-pipeline-operator": "7.0.0-beta.36",
"@babel/plugin-proposal-unicode-property-regex": "7.0.0-beta.36",
"@babel/plugin-syntax-async-generators": "7.0.0-beta.36",
"@babel/plugin-syntax-class-properties": "7.0.0-beta.36",
"@babel/plugin-syntax-decorators": "7.0.0-beta.36",
"@babel/plugin-syntax-do-expressions": "7.0.0-beta.36",
"@babel/plugin-syntax-dynamic-import": "7.0.0-beta.36",
"@babel/plugin-syntax-export-default-from": "7.0.0-beta.36",
"@babel/plugin-syntax-export-namespace-from": "7.0.0-beta.36",
"@babel/plugin-syntax-flow": "7.0.0-beta.36",
"@babel/plugin-syntax-function-bind": "7.0.0-beta.36",
"@babel/plugin-syntax-function-sent": "7.0.0-beta.36",
"@babel/plugin-syntax-import-meta": "7.0.0-beta.36",
"@babel/plugin-syntax-jsx": "7.0.0-beta.36",
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.36",
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.36",
"@babel/plugin-syntax-pipeline-operator": "7.0.0-beta.36",
"@babel/plugin-transform-arrow-functions": "7.0.0-beta.36",
"@babel/plugin-transform-async-to-generator": "7.0.0-beta.36",
"@babel/plugin-transform-block-scoped-functions": "7.0.0-beta.36",
"@babel/plugin-transform-block-scoping": "7.0.0-beta.36",
"@babel/plugin-transform-classes": "7.0.0-beta.36",
"@babel/plugin-transform-computed-properties": "7.0.0-beta.36",
"@babel/plugin-transform-destructuring": "7.0.0-beta.36",
"@babel/plugin-transform-dotall-regex": "7.0.0-beta.36",
"@babel/plugin-transform-duplicate-keys": "7.0.0-beta.36",
"@babel/plugin-transform-eval": "7.0.0-beta.36",
"@babel/plugin-transform-exponentiation-operator": "7.0.0-beta.36",
"@babel/plugin-transform-flow-comments": "7.0.0-beta.36",
"@babel/plugin-transform-flow-strip-types": "7.0.0-beta.36",
"@babel/plugin-transform-for-of": "7.0.0-beta.36",
"@babel/plugin-transform-function-name": "7.0.0-beta.36",
"@babel/plugin-transform-instanceof": "7.0.0-beta.36",
"@babel/plugin-transform-jscript": "7.0.0-beta.36",
"@babel/plugin-transform-literals": "7.0.0-beta.36",
"@babel/plugin-transform-member-expression-literals": "7.0.0-beta.36",
"@babel/plugin-transform-modules-amd": "7.0.0-beta.36",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.36",
"@babel/plugin-transform-modules-systemjs": "7.0.0-beta.36",
"@babel/plugin-transform-modules-umd": "7.0.0-beta.36",
"@babel/plugin-transform-new-target": "7.0.0-beta.36",
"@babel/plugin-transform-object-assign": "7.0.0-beta.36",
"@babel/plugin-transform-object-set-prototype-of-to-assign": "7.0.0-beta.36",
"@babel/plugin-transform-object-super": "7.0.0-beta.36",
"@babel/plugin-transform-parameters": "7.0.0-beta.36",
"@babel/plugin-transform-property-literals": "7.0.0-beta.36",
"@babel/plugin-transform-property-mutators": "7.0.0-beta.36",
"@babel/plugin-transform-proto-to-assign": "7.0.0-beta.36",
"@babel/plugin-transform-react-constant-elements": "7.0.0-beta.36",
"@babel/plugin-transform-react-display-name": "7.0.0-beta.36",
"@babel/plugin-transform-react-inline-elements": "7.0.0-beta.36",
"@babel/plugin-transform-react-jsx": "7.0.0-beta.36",
"@babel/plugin-transform-react-jsx-compat": "7.0.0-beta.36",
"@babel/plugin-transform-react-jsx-self": "7.0.0-beta.36",
"@babel/plugin-transform-react-jsx-source": "7.0.0-beta.36",
"@babel/plugin-transform-regenerator": "7.0.0-beta.36",
"@babel/plugin-transform-runtime": "7.0.0-beta.36",
"@babel/plugin-transform-shorthand-properties": "7.0.0-beta.36",
"@babel/plugin-transform-spread": "7.0.0-beta.36",
"@babel/plugin-transform-sticky-regex": "7.0.0-beta.36",
"@babel/plugin-transform-strict-mode": "7.0.0-beta.36",
"@babel/plugin-transform-template-literals": "7.0.0-beta.36",
"@babel/plugin-transform-typeof-symbol": "7.0.0-beta.36",
"@babel/plugin-transform-unicode-regex": "7.0.0-beta.36",
"@babel/preset-es2015": "7.0.0-beta.36",
"@babel/preset-es2016": "7.0.0-beta.36",
"@babel/preset-es2017": "7.0.0-beta.36",
"@babel/preset-flow": "7.0.0-beta.36",
"@babel/preset-react": "7.0.0-beta.36",
"@babel/preset-stage-0": "7.0.0-beta.36",
"@babel/preset-stage-1": "7.0.0-beta.36",
"@babel/preset-stage-2": "7.0.0-beta.36",
"@babel/preset-stage-3": "7.0.0-beta.36",
"@babel/preset-typescript": "7.0.0-beta.36"
},
"keywords": [
"babel",
"babeljs",
"6to5",
"transpile",
"transpiler"
],
"author": "Daniel Lo Nigro <[email protected]> (http://dan.cx/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/babel/babel-standalone/issues"
},
"homepage": "https://github.com/babel/babel-standalone#readme"
}
| packages/babel-standalone/package.json | 1 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0011337980395182967,
0.00037260272074490786,
0.00016476085875183344,
0.0002120003046002239,
0.00030514755053445697
] |
{
"id": 3,
"code_window": [
" \"transform-sticky-regex\": require(\"@babel/plugin-transform-sticky-regex\"),\n",
" \"transform-template-literals\": require(\"@babel/plugin-transform-template-literals\"),\n",
" \"transform-typeof-symbol\": require(\"@babel/plugin-transform-typeof-symbol\"),\n",
" \"transform-unicode-regex\": require(\"@babel/plugin-transform-unicode-regex\"),\n",
" \"transform-member-expression-literals\": require(\"@babel/plugin-transform-member-expression-literals\"),\n",
" \"transform-property-literals\": require(\"@babel/plugin-transform-property-literals\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-typescript\": require(\"@babel/plugin-transform-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 190
} | {
"throws": "Expected number in radix 2 (1:2)"
} | packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0017/options.json | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0001667392352828756,
0.0001667392352828756,
0.0001667392352828756,
0.0001667392352828756,
0
] |
{
"id": 3,
"code_window": [
" \"transform-sticky-regex\": require(\"@babel/plugin-transform-sticky-regex\"),\n",
" \"transform-template-literals\": require(\"@babel/plugin-transform-template-literals\"),\n",
" \"transform-typeof-symbol\": require(\"@babel/plugin-transform-typeof-symbol\"),\n",
" \"transform-unicode-regex\": require(\"@babel/plugin-transform-unicode-regex\"),\n",
" \"transform-member-expression-literals\": require(\"@babel/plugin-transform-member-expression-literals\"),\n",
" \"transform-property-literals\": require(\"@babel/plugin-transform-property-literals\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-typescript\": require(\"@babel/plugin-transform-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 190
} | const typedArrayMethods = [
"typed arrays / %TypedArray%.from",
"typed arrays / %TypedArray%.of",
"typed arrays / %TypedArray%.prototype.subarray",
"typed arrays / %TypedArray%.prototype.join",
"typed arrays / %TypedArray%.prototype.indexOf",
"typed arrays / %TypedArray%.prototype.lastIndexOf",
"typed arrays / %TypedArray%.prototype.slice",
"typed arrays / %TypedArray%.prototype.every",
"typed arrays / %TypedArray%.prototype.filter",
"typed arrays / %TypedArray%.prototype.forEach",
"typed arrays / %TypedArray%.prototype.map",
"typed arrays / %TypedArray%.prototype.reduce",
"typed arrays / %TypedArray%.prototype.reduceRight",
"typed arrays / %TypedArray%.prototype.reverse",
"typed arrays / %TypedArray%.prototype.some",
"typed arrays / %TypedArray%.prototype.sort",
"typed arrays / %TypedArray%.prototype.copyWithin",
"typed arrays / %TypedArray%.prototype.find",
"typed arrays / %TypedArray%.prototype.findIndex",
"typed arrays / %TypedArray%.prototype.fill",
"typed arrays / %TypedArray%.prototype.keys",
"typed arrays / %TypedArray%.prototype.values",
"typed arrays / %TypedArray%.prototype.entries",
"typed arrays / %TypedArray%.prototype[Symbol.iterator]",
"typed arrays / %TypedArray%[Symbol.species]",
];
const es2015 = {
"es6.typed.array-buffer": "typed arrays / ArrayBuffer[Symbol.species]",
"es6.typed.data-view": "typed arrays / DataView",
"es6.typed.int8-array": {
features: ["typed arrays / Int8Array"].concat(typedArrayMethods)
},
"es6.typed.uint8-array": {
features: ["typed arrays / Uint8Array"].concat(typedArrayMethods)
},
"es6.typed.uint8-clamped-array": {
features: ["typed arrays / Uint8ClampedArray"].concat(typedArrayMethods)
},
"es6.typed.int16-array": {
features: ["typed arrays / Int16Array"].concat(typedArrayMethods)
},
"es6.typed.uint16-array": {
features: ["typed arrays / Uint16Array"].concat(typedArrayMethods)
},
"es6.typed.int32-array": {
features: ["typed arrays / Int32Array"].concat(typedArrayMethods)
},
"es6.typed.uint32-array": {
features: ["typed arrays / Uint32Array"].concat(typedArrayMethods)
},
"es6.typed.float32-array": {
features: ["typed arrays / Float32Array"].concat(typedArrayMethods)
},
"es6.typed.float64-array": {
features: ["typed arrays / Float64Array"].concat(typedArrayMethods)
},
"es6.map": "Map",
"es6.set": "Set",
"es6.weak-map": "WeakMap",
"es6.weak-set": "WeakSet",
// Proxy not implementable
"es6.reflect.apply": "Reflect / Reflect.apply",
"es6.reflect.construct": "Reflect / Reflect.construct",
"es6.reflect.define-property": "Reflect / Reflect.defineProperty",
"es6.reflect.delete-property": "Reflect / Reflect.deleteProperty",
"es6.reflect.get": "Reflect / Reflect.get",
"es6.reflect.get-own-property-descriptor": "Reflect / Reflect.getOwnPropertyDescriptor",
"es6.reflect.get-prototype-of": "Reflect / Reflect.getPrototypeOf",
"es6.reflect.has": "Reflect / Reflect.has",
"es6.reflect.is-extensible": "Reflect / Reflect.isExtensible",
"es6.reflect.own-keys": "Reflect / Reflect.ownKeys",
"es6.reflect.prevent-extensions": "Reflect / Reflect.preventExtensions",
"es6.reflect.set": "Reflect / Reflect.set",
"es6.reflect.set-prototype-of": "Reflect / Reflect.setPrototypeOf",
"es6.promise": {
features: [
"Promise / basic functionality",
"Promise / constructor requires new",
"Promise / Promise.prototype isn\'t an instance",
"Promise / Promise.all",
"Promise / Promise.all, generic iterables",
"Promise / Promise.race",
"Promise / Promise.race, generic iterables",
"Promise / Promise[Symbol.species]"
]
},
"es6.symbol": {
features: [
"Symbol",
"Object static methods / Object.getOwnPropertySymbols",
"well-known symbols / Symbol.hasInstance",
"well-known symbols / Symbol.isConcatSpreadable",
"well-known symbols / Symbol.iterator",
"well-known symbols / Symbol.match",
"well-known symbols / Symbol.replace",
"well-known symbols / Symbol.search",
"well-known symbols / Symbol.species",
"well-known symbols / Symbol.split",
"well-known symbols / Symbol.toPrimitive",
"well-known symbols / Symbol.toStringTag",
"well-known symbols / Symbol.unscopables",
]
},
"es6.object.freeze": "Object static methods accept primitives / Object.freeze",
"es6.object.seal": "Object static methods accept primitives / Object.seal",
"es6.object.prevent-extensions": "Object static methods accept primitives / Object.preventExtensions",
"es6.object.is-frozen": "Object static methods accept primitives / Object.isFrozen",
"es6.object.is-sealed": "Object static methods accept primitives / Object.isSealed",
"es6.object.is-extensible": "Object static methods accept primitives / Object.isExtensible",
"es6.object.get-own-property-descriptor":
"Object static methods accept primitives / Object.getOwnPropertyDescriptor",
"es6.object.get-prototype-of": "Object static methods accept primitives / Object.getPrototypeOf",
"es6.object.keys": "Object static methods accept primitives / Object.keys",
"es6.object.get-own-property-names": "Object static methods accept primitives / Object.getOwnPropertyNames",
"es6.object.assign": "Object static methods / Object.assign",
"es6.object.is": "Object static methods / Object.is",
"es6.object.set-prototype-of": "Object static methods / Object.setPrototypeOf",
"es6.function.name": "function \"name\" property",
"es6.string.raw": "String static methods / String.raw",
"es6.string.from-code-point": "String static methods / String.fromCodePoint",
"es6.string.code-point-at": "String.prototype methods / String.prototype.codePointAt",
// "String.prototype methods / String.prototype.normalize" not implemented
"es6.string.repeat": "String.prototype methods / String.prototype.repeat",
"es6.string.starts-with": "String.prototype methods / String.prototype.startsWith",
"es6.string.ends-with": "String.prototype methods / String.prototype.endsWith",
"es6.string.includes": "String.prototype methods / String.prototype.includes",
"es6.regexp.flags": "RegExp.prototype properties / RegExp.prototype.flags",
"es6.regexp.match": "RegExp.prototype properties / RegExp.prototype[Symbol.match]",
"es6.regexp.replace": "RegExp.prototype properties / RegExp.prototype[Symbol.replace]",
"es6.regexp.split": "RegExp.prototype properties / RegExp.prototype[Symbol.split]",
"es6.regexp.search": "RegExp.prototype properties / RegExp.prototype[Symbol.search]",
"es6.array.from": "Array static methods / Array.from",
"es6.array.of": "Array static methods / Array.of",
"es6.array.copy-within": "Array.prototype methods / Array.prototype.copyWithin",
"es6.array.find": "Array.prototype methods / Array.prototype.find",
"es6.array.find-index": "Array.prototype methods / Array.prototype.findIndex",
"es6.array.fill": "Array.prototype methods / Array.prototype.fill",
"es6.array.iterator": {
features: [
"Array.prototype methods / Array.prototype.keys",
// can use Symbol.iterator, not implemented in many environments
// "Array.prototype methods / Array.prototype.values",
"Array.prototype methods / Array.prototype.entries",
]
},
"es6.number.is-finite": "Number properties / Number.isFinite",
"es6.number.is-integer": "Number properties / Number.isInteger",
"es6.number.is-safe-integer": "Number properties / Number.isSafeInteger",
"es6.number.is-nan": "Number properties / Number.isNaN",
"es6.number.epsilon": "Number properties / Number.EPSILON",
"es6.number.min-safe-integer": "Number properties / Number.MIN_SAFE_INTEGER",
"es6.number.max-safe-integer": "Number properties / Number.MAX_SAFE_INTEGER",
"es6.number.parse-float": "Number properties / Number.parseFloat",
"es6.number.parse-int": "Number properties / Number.parseInt",
"es6.math.acosh": "Math methods / Math.acosh",
"es6.math.asinh": "Math methods / Math.asinh",
"es6.math.atanh": "Math methods / Math.atanh",
"es6.math.cbrt": "Math methods / Math.cbrt",
"es6.math.clz32": "Math methods / Math.clz32",
"es6.math.cosh": "Math methods / Math.cosh",
"es6.math.expm1": "Math methods / Math.expm1",
"es6.math.fround": "Math methods / Math.fround",
"es6.math.hypot": "Math methods / Math.hypot",
"es6.math.imul": "Math methods / Math.imul",
"es6.math.log1p": "Math methods / Math.log1p",
"es6.math.log10": "Math methods / Math.log10",
"es6.math.log2": "Math methods / Math.log2",
"es6.math.sign": "Math methods / Math.sign",
"es6.math.sinh": "Math methods / Math.sinh",
"es6.math.tanh": "Math methods / Math.tanh",
"es6.math.trunc": "Math methods / Math.trunc",
};
const es2016 = {
"es7.array.includes": "Array.prototype.includes",
};
const es2017 = {
"es7.object.values": "Object static methods / Object.values",
"es7.object.entries": "Object static methods / Object.entries",
"es7.object.get-own-property-descriptors": "Object static methods / Object.getOwnPropertyDescriptors",
"es7.string.pad-start": "String padding / String.prototype.padStart",
"es7.string.pad-end": "String padding / String.prototype.padEnd",
};
const proposals = require("./shipped-proposals").builtIns;
module.exports = Object.assign({}, es2015, es2016, es2017, proposals);
| packages/babel-preset-env/data/built-in-features.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.0001709140051389113,
0.00016752599913161248,
0.0001619012327864766,
0.00016784004401415586,
0.000002254455239381059
] |
{
"id": 3,
"code_window": [
" \"transform-sticky-regex\": require(\"@babel/plugin-transform-sticky-regex\"),\n",
" \"transform-template-literals\": require(\"@babel/plugin-transform-template-literals\"),\n",
" \"transform-typeof-symbol\": require(\"@babel/plugin-transform-typeof-symbol\"),\n",
" \"transform-unicode-regex\": require(\"@babel/plugin-transform-unicode-regex\"),\n",
" \"transform-member-expression-literals\": require(\"@babel/plugin-transform-member-expression-literals\"),\n",
" \"transform-property-literals\": require(\"@babel/plugin-transform-property-literals\"),\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-typescript\": require(\"@babel/plugin-transform-typescript\"),\n"
],
"file_path": "packages/babel-standalone/src/index.js",
"type": "add",
"edit_start_line_idx": 190
} | (x=1) => x * x
| packages/babylon/test/fixtures/esprima/es2015-arrow-function/migrated_0008/actual.js | 0 | https://github.com/babel/babel/commit/ad2019aa303fd0de6145f0cd5ddf264ab831d590 | [
0.00016669632168486714,
0.00016669632168486714,
0.00016669632168486714,
0.00016669632168486714,
0
] |
{
"id": 0,
"code_window": [
"\t/**\n",
"\t * The items to be displayed in the quick pick.\n",
"\t */\n",
"\titems: ReadonlyArray<T | IQuickPickSeparator>;\n",
"\n",
"\t/**\n",
"\t * The scroll position of the quick pick input. Used by keepScrollPosition.\n",
"\t * @todo this should be private\n",
"\t */\n",
"\tscrollTop: number;\n",
"\n",
"\t/**\n",
"\t * Whether multiple items can be selected. If so, checkboxes will be rendered.\n",
"\t */\n",
"\tcanSelectMany: boolean;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/quickinput/common/quickInput.ts",
"type": "replace",
"edit_start_line_idx": 426
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { Event } from 'vs/base/common/event';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IQuickAccessController } from 'vs/platform/quickinput/common/quickAccess';
import { IMatch } from 'vs/base/common/filters';
import { IItemAccessor } from 'vs/base/common/fuzzyScorer';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import Severity from 'vs/base/common/severity';
import { URI } from 'vs/base/common/uri';
import { IMarkdownString } from 'vs/base/common/htmlContent';
export interface IQuickPickItemHighlights {
label?: IMatch[];
description?: IMatch[];
detail?: IMatch[];
}
export type QuickPickItem = IQuickPickSeparator | IQuickPickItem;
export interface IQuickPickItem {
type?: 'item';
id?: string;
label: string;
ariaLabel?: string;
description?: string;
detail?: string;
tooltip?: string | IMarkdownString;
/**
* Allows to show a keybinding next to the item to indicate
* how the item can be triggered outside of the picker using
* keyboard shortcut.
*/
keybinding?: ResolvedKeybinding;
iconClasses?: readonly string[];
iconPath?: { dark: URI; light?: URI };
iconClass?: string;
italic?: boolean;
strikethrough?: boolean;
highlights?: IQuickPickItemHighlights;
buttons?: readonly IQuickInputButton[];
picked?: boolean;
alwaysShow?: boolean;
}
export interface IQuickPickSeparator {
type: 'separator';
id?: string;
label?: string;
ariaLabel?: string;
buttons?: readonly IQuickInputButton[];
tooltip?: string | IMarkdownString;
}
export interface IKeyMods {
readonly ctrlCmd: boolean;
readonly alt: boolean;
}
export const NO_KEY_MODS: IKeyMods = { ctrlCmd: false, alt: false };
export interface IQuickNavigateConfiguration {
keybindings: readonly ResolvedKeybinding[];
}
export interface IPickOptions<T extends IQuickPickItem> {
/**
* an optional string to show as the title of the quick input
*/
title?: string;
/**
* an optional string to show as placeholder in the input box to guide the user what she picks on
*/
placeHolder?: string;
/**
* an optional flag to include the description when filtering the picks
*/
matchOnDescription?: boolean;
/**
* an optional flag to include the detail when filtering the picks
*/
matchOnDetail?: boolean;
/**
* an optional flag to filter the picks based on label. Defaults to true.
*/
matchOnLabel?: boolean;
/**
* an optional flag to not close the picker on focus lost
*/
ignoreFocusLost?: boolean;
/**
* an optional flag to make this picker multi-select
*/
canPickMany?: boolean;
/**
* enables quick navigate in the picker to open an element without typing
*/
quickNavigate?: IQuickNavigateConfiguration;
/**
* Hides the input box from the picker UI. This is typically used
* in combination with quick-navigation where no search UI should
* be presented.
*/
hideInput?: boolean;
/**
* a context key to set when this picker is active
*/
contextKey?: string;
/**
* an optional property for the item to focus initially.
*/
activeItem?: Promise<T> | T;
onKeyMods?: (keyMods: IKeyMods) => void;
onDidFocus?: (entry: T) => void;
onDidTriggerItemButton?: (context: IQuickPickItemButtonContext<T>) => void;
onDidTriggerSeparatorButton?: (context: IQuickPickSeparatorButtonEvent) => void;
}
export interface IInputOptions {
/**
* an optional string to show as the title of the quick input
*/
title?: string;
/**
* the value to prefill in the input box
*/
value?: string;
/**
* the selection of value, default to the whole prefilled value
*/
valueSelection?: readonly [number, number];
/**
* the text to display underneath the input box
*/
prompt?: string;
/**
* an optional string to show as placeholder in the input box to guide the user what to type
*/
placeHolder?: string;
/**
* Controls if a password input is shown. Password input hides the typed text.
*/
password?: boolean;
/**
* an optional flag to not close the input on focus lost
*/
ignoreFocusLost?: boolean;
/**
* an optional function that is used to validate user input.
*/
validateInput?: (input: string) => Promise<string | null | undefined | { content: string; severity: Severity }>;
}
export enum QuickInputHideReason {
/**
* Focus moved away from the quick input.
*/
Blur = 1,
/**
* An explicit user gesture, e.g. pressing Escape key.
*/
Gesture,
/**
* Anything else.
*/
Other
}
export interface IQuickInputHideEvent {
reason: QuickInputHideReason;
}
/**
* Represents a quick input control that allows users to make selections or provide input quickly.
*/
export interface IQuickInput extends IDisposable {
/**
* An event that is fired when the quick input is hidden.
*/
readonly onDidHide: Event<IQuickInputHideEvent>;
/**
* An event that is fired when the quick input is disposed.
*/
readonly onDispose: Event<void>;
/**
* The title of the quick input.
*/
title: string | undefined;
/**
* The description of the quick input. This is rendered right below the input box.
*/
description: string | undefined;
/**
* An HTML widget rendered below the input.
* @deprecated Use an IQuickWidget instead.
*/
widget: any | undefined;
/**
* The current step of the quick input rendered in the titlebar.
*/
step: number | undefined;
/**
* The total number of steps in the quick input rendered in the titlebar.
*/
totalSteps: number | undefined;
/**
* The buttons displayed in the quick input titlebar.
*/
buttons: ReadonlyArray<IQuickInputButton>;
/**
* An event that is fired when a button in the quick input is triggered.
*/
readonly onDidTriggerButton: Event<IQuickInputButton>;
/**
* Indicates whether the input is enabled.
*/
enabled: boolean;
/**
* The context key associated with the quick input.
*/
contextKey: string | undefined;
/**
* Indicates whether the quick input is busy. Renders a progress bar if true.
*/
busy: boolean;
/**
* Indicates whether the quick input should be hidden when it loses focus.
*/
ignoreFocusOut: boolean;
/**
* Shows the quick input.
*/
show(): void;
/**
* Hides the quick input.
*/
hide(): void;
/**
* Notifies that the quick input has been hidden.
* @param reason The reason why the quick input was hidden.
*/
didHide(reason?: QuickInputHideReason): void;
}
export interface IQuickWidget extends IQuickInput {
/**
* Should be an HTMLElement (TODO: move this entire file into browser)
* @override
*/
widget: any | undefined;
}
export interface IQuickPickWillAcceptEvent {
/**
* Allows to disable the default accept handling
* of the picker. If `veto` is called, the picker
* will not trigger the `onDidAccept` event.
*/
veto(): void;
}
export interface IQuickPickDidAcceptEvent {
/**
* Signals if the picker item is to be accepted
* in the background while keeping the picker open.
*/
inBackground: boolean;
}
/**
* Represents the activation behavior for items in a quick input. This means which item will be
* "active" (aka focused).
*/
export enum ItemActivation {
/**
* No item will be active.
*/
NONE,
/**
* First item will be active.
*/
FIRST,
/**
* Second item will be active.
*/
SECOND,
/**
* Last item will be active.
*/
LAST
}
/**
* Represents a quick pick control that allows the user to select an item from a list of options.
*/
export interface IQuickPick<T extends IQuickPickItem> extends IQuickInput {
/**
* The current value of the quick pick input.
*/
value: string;
/**
* A method that allows to massage the value used for filtering, e.g, to remove certain parts.
* @param value The value to be filtered.
* @returns The filtered value.
*/
filterValue: (value: string) => string;
/**
* The ARIA label for the quick pick input.
*/
ariaLabel: string | undefined;
/**
* The placeholder text for the quick pick input.
*/
placeholder: string | undefined;
/**
* An event that is fired when the value of the quick pick input changes.
*/
readonly onDidChangeValue: Event<string>;
/**
* An event that is fired when the quick pick is about to accept the selected item.
*/
readonly onWillAccept: Event<IQuickPickWillAcceptEvent>;
/**
* An event that is fired when the quick pick has accepted the selected item.
*/
readonly onDidAccept: Event<IQuickPickDidAcceptEvent>;
/**
* If enabled, the `onDidAccept` event will be fired when pressing the arrow-right key to accept the selected item without closing the picker.
*/
canAcceptInBackground: boolean;
/**
* The OK button state. It can be a boolean value or the string 'default'.
*/
ok: boolean | 'default';
/**
* An event that is fired when the custom button is triggered. The custom button is a button with text rendered to the right of the input.
*/
readonly onDidCustom: Event<void>;
/**
* Whether to show the custom button. The custom button is a button with text rendered to the right of the input.
*/
customButton: boolean;
/**
* The label for the custom button. The custom button is a button with text rendered to the right of the input.
*/
customLabel: string | undefined;
/**
* The hover text for the custom button. The custom button is a button with text rendered to the right of the input.
*/
customHover: string | undefined;
/**
* An event that is fired when an item button is triggered.
*/
readonly onDidTriggerItemButton: Event<IQuickPickItemButtonEvent<T>>;
/**
* An event that is fired when a separator button is triggered.
*/
readonly onDidTriggerSeparatorButton: Event<IQuickPickSeparatorButtonEvent>;
/**
* The items to be displayed in the quick pick.
*/
items: ReadonlyArray<T | IQuickPickSeparator>;
/**
* The scroll position of the quick pick input. Used by keepScrollPosition.
* @todo this should be private
*/
scrollTop: number;
/**
* Whether multiple items can be selected. If so, checkboxes will be rendered.
*/
canSelectMany: boolean;
/**
* Whether to match on the description of the items.
*/
matchOnDescription: boolean;
/**
* Whether to match on the detail of the items.
*/
matchOnDetail: boolean;
/**
* Whether to match on the label of the items.
*/
matchOnLabel: boolean;
/**
* The mode to filter the label with. It can be 'fuzzy' or 'contiguous'. Defaults to 'fuzzy'.
*/
matchOnLabelMode: 'fuzzy' | 'contiguous';
/**
* Whether to sort the items by label.
*/
sortByLabel: boolean;
/**
* Whether to keep the scroll position when the quick pick input is updated.
*/
keepScrollPosition: boolean;
/**
* The configuration for quick navigation.
*/
quickNavigate: IQuickNavigateConfiguration | undefined;
/**
* The currently active items.
*/
activeItems: ReadonlyArray<T>;
/**
* An event that is fired when the active items change.
*/
readonly onDidChangeActive: Event<T[]>;
/**
* The item activation behavior for the next time `items` is set. Item activation means which
* item is "active" (aka focused) when the quick pick is opened or when `items` is set.
*/
itemActivation: ItemActivation;
/**
* The currently selected items.
*/
selectedItems: ReadonlyArray<T>;
/**
* An event that is fired when the selected items change.
*/
readonly onDidChangeSelection: Event<T[]>;
/**
* The key modifiers.
*/
readonly keyMods: IKeyMods;
/**
* The selection range for the value in the input.
*/
valueSelection: Readonly<[number, number]> | undefined;
/**
* The validation message for the quick pick. This is rendered below the input.
*/
validationMessage: string | undefined;
/**
* The severity of the validation message.
*/
severity: Severity;
/**
* Checks if the quick pick input has focus.
* @returns `true` if the quick pick input has focus, `false` otherwise.
*/
inputHasFocus(): boolean;
/**
* Focuses on the quick pick input.
*/
focusOnInput(): void;
/**
* Hides the input box from the picker UI. This is typically used in combination with quick-navigation where no search UI should be presented.
*/
hideInput: boolean;
/**
* Controls whether the count for the items should be shown.
*/
hideCountBadge: boolean;
/**
* Whether to hide the "Check All" checkbox.
*/
hideCheckAll: boolean;
/**
* The toggle buttons to be added to the input box.
*/
toggles: IQuickInputToggle[] | undefined;
}
/**
* Represents a toggle for quick input.
*/
export interface IQuickInputToggle {
/**
* Event that is fired when the toggle value changes.
* The boolean value indicates whether the change was triggered via keyboard.
*/
onChange: Event<boolean>;
}
/**
* Represents an input box in a quick input dialog.
*/
export interface IInputBox extends IQuickInput {
/**
* Value shown in the input box.
*/
value: string;
/**
* Provide start and end values to be selected in the input box.
*/
valueSelection: Readonly<[number, number]> | undefined;
/**
* Value shown as example for input.
*/
placeholder: string | undefined;
/**
* Determines if the input value should be hidden while typing.
*/
password: boolean;
/**
* Event called when the input value changes.
*/
readonly onDidChangeValue: Event<string>;
/**
* Event called when the user submits the input.
*/
readonly onDidAccept: Event<void>;
/**
* Text show below the input box.
*/
prompt: string | undefined;
/**
* An optional validation message indicating a problem with the current input value.
* Returning undefined clears the validation message.
*/
validationMessage: string | undefined;
/**
* Severity of the input validation message.
*/
severity: Severity;
}
/**
* Represents a button in the quick input UI.
*/
export interface IQuickInputButton {
/**
* The path to the icon for the button.
* Either `iconPath` or `iconClass` is required.
*/
iconPath?: { dark: URI; light?: URI };
/**
* The CSS class for the icon of the button.
* Either `iconPath` or `iconClass` is required.
*/
iconClass?: string;
/**
* The tooltip text for the button.
*/
tooltip?: string;
/**
* Whether to always show the button.
* By default, buttons are only visible when hovering over them with the mouse.
*/
alwaysVisible?: boolean;
}
/**
* Represents an event that occurs when a button associated with a quick pick item is clicked.
* @template T - The type of the quick pick item.
*/
export interface IQuickPickItemButtonEvent<T extends IQuickPickItem> {
/**
* The button that was clicked.
*/
button: IQuickInputButton;
/**
* The quick pick item associated with the button.
*/
item: T;
}
/**
* Represents an event that occurs when a separator button is clicked in a quick pick.
*/
export interface IQuickPickSeparatorButtonEvent {
/**
* The button that was clicked.
*/
button: IQuickInputButton;
/**
* The separator associated with the button.
*/
separator: IQuickPickSeparator;
}
/**
* Represents a context for a button associated with a quick pick item.
* @template T - The type of the quick pick item.
*/
export interface IQuickPickItemButtonContext<T extends IQuickPickItem> extends IQuickPickItemButtonEvent<T> {
/**
* Removes the associated item from the quick pick.
*/
removeItem(): void;
}
export type QuickPickInput<T = IQuickPickItem> = T | IQuickPickSeparator;
//#region Fuzzy Scorer Support
export type IQuickPickItemWithResource = IQuickPickItem & { resource?: URI };
export class QuickPickItemScorerAccessor implements IItemAccessor<IQuickPickItemWithResource> {
constructor(private options?: { skipDescription?: boolean; skipPath?: boolean }) { }
getItemLabel(entry: IQuickPickItemWithResource): string {
return entry.label;
}
getItemDescription(entry: IQuickPickItemWithResource): string | undefined {
if (this.options?.skipDescription) {
return undefined;
}
return entry.description;
}
getItemPath(entry: IQuickPickItemWithResource): string | undefined {
if (this.options?.skipPath) {
return undefined;
}
if (entry.resource?.scheme === Schemas.file) {
return entry.resource.fsPath;
}
return entry.resource?.path;
}
}
export const quickPickItemScorerAccessor = new QuickPickItemScorerAccessor();
//#endregion
export const IQuickInputService = createDecorator<IQuickInputService>('quickInputService');
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export interface IQuickInputService {
readonly _serviceBrand: undefined;
/**
* Provides access to the back button in quick input.
*/
readonly backButton: IQuickInputButton;
/**
* Provides access to the quick access providers.
*/
readonly quickAccess: IQuickAccessController;
/**
* Allows to register on the event that quick input is showing.
*/
readonly onShow: Event<void>;
/**
* Allows to register on the event that quick input is hiding.
*/
readonly onHide: Event<void>;
/**
* Opens the quick input box for selecting items and returns a promise
* with the user selected item(s) if any.
*/
pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: true }, token?: CancellationToken): Promise<T[] | undefined>;
pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: false }, token?: CancellationToken): Promise<T | undefined>;
pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: Omit<IPickOptions<T>, 'canPickMany'>, token?: CancellationToken): Promise<T | undefined>;
/**
* Opens the quick input box for text input and returns a promise with the user typed value if any.
*/
input(options?: IInputOptions, token?: CancellationToken): Promise<string | undefined>;
/**
* Provides raw access to the quick pick controller.
*/
createQuickPick<T extends IQuickPickItem>(): IQuickPick<T>;
/**
* Provides raw access to the input box controller.
*/
createInputBox(): IInputBox;
/**
* Provides raw access to the quick widget controller.
*/
createQuickWidget(): IQuickWidget;
/**
* Moves focus into quick input.
*/
focus(): void;
/**
* Toggle the checked state of the selected item.
*/
toggle(): void;
/**
* Navigate inside the opened quick input list.
*/
navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void;
/**
* Navigate back in a multi-step quick input.
*/
back(): Promise<void>;
/**
* Accept the selected item.
*
* @param keyMods allows to override the state of key
* modifiers that should be present when invoking.
*/
accept(keyMods?: IKeyMods): Promise<void>;
/**
* Cancels quick input and closes it.
*/
cancel(): Promise<void>;
}
| src/vs/platform/quickinput/common/quickInput.ts | 1 | https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5 | [
0.9953762292861938,
0.02681824006140232,
0.0001658065157243982,
0.00033617886947467923,
0.15329045057296753
] |
{
"id": 0,
"code_window": [
"\t/**\n",
"\t * The items to be displayed in the quick pick.\n",
"\t */\n",
"\titems: ReadonlyArray<T | IQuickPickSeparator>;\n",
"\n",
"\t/**\n",
"\t * The scroll position of the quick pick input. Used by keepScrollPosition.\n",
"\t * @todo this should be private\n",
"\t */\n",
"\tscrollTop: number;\n",
"\n",
"\t/**\n",
"\t * Whether multiple items can be selected. If so, checkboxes will be rendered.\n",
"\t */\n",
"\tcanSelectMany: boolean;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/quickinput/common/quickInput.ts",
"type": "replace",
"edit_start_line_idx": 426
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as uri from 'vscode-uri';
import { ILogger } from '../logging';
import { MarkdownContributionProvider } from '../markdownExtensions';
import { Disposable } from '../util/dispose';
import { isMarkdownFile } from '../util/file';
import { MdLinkOpener } from '../util/openDocumentLink';
import { WebviewResourceProvider } from '../util/resources';
import { urlToUri } from '../util/url';
import { ImageInfo, MdDocumentRenderer } from './documentRenderer';
import { MarkdownPreviewConfigurationManager } from './previewConfig';
import { scrollEditorToLine, StartingScrollFragment, StartingScrollLine, StartingScrollLocation } from './scrolling';
import { getVisibleLine, LastScrollLocation, TopmostLineMonitor } from './topmostLineMonitor';
import type { FromWebviewMessage, ToWebviewMessage } from '../../types/previewMessaging';
export class PreviewDocumentVersion {
public readonly resource: vscode.Uri;
private readonly _version: number;
public constructor(document: vscode.TextDocument) {
this.resource = document.uri;
this._version = document.version;
}
public equals(other: PreviewDocumentVersion): boolean {
return this.resource.fsPath === other.resource.fsPath
&& this._version === other._version;
}
}
interface MarkdownPreviewDelegate {
getTitle?(resource: vscode.Uri): string;
getAdditionalState(): {};
openPreviewLinkToMarkdownFile(markdownLink: vscode.Uri, fragment: string | undefined): void;
}
class MarkdownPreview extends Disposable implements WebviewResourceProvider {
private static readonly _unwatchedImageSchemes = new Set(['https', 'http', 'data']);
private _disposed: boolean = false;
private readonly _delay = 300;
private _throttleTimer: any;
private readonly _resource: vscode.Uri;
private readonly _webviewPanel: vscode.WebviewPanel;
private _line: number | undefined;
private _scrollToFragment: string | undefined;
private _firstUpdate = true;
private _currentVersion?: PreviewDocumentVersion;
private _isScrolling = false;
private _imageInfo: readonly ImageInfo[] = [];
private readonly _fileWatchersBySrc = new Map</* src: */ string, vscode.FileSystemWatcher>();
private readonly _onScrollEmitter = this._register(new vscode.EventEmitter<LastScrollLocation>());
public readonly onScroll = this._onScrollEmitter.event;
private readonly _disposeCts = this._register(new vscode.CancellationTokenSource());
constructor(
webview: vscode.WebviewPanel,
resource: vscode.Uri,
startingScroll: StartingScrollLocation | undefined,
private readonly _delegate: MarkdownPreviewDelegate,
private readonly _contentProvider: MdDocumentRenderer,
private readonly _previewConfigurations: MarkdownPreviewConfigurationManager,
private readonly _logger: ILogger,
private readonly _contributionProvider: MarkdownContributionProvider,
private readonly _opener: MdLinkOpener,
) {
super();
this._webviewPanel = webview;
this._resource = resource;
switch (startingScroll?.type) {
case 'line':
if (!isNaN(startingScroll.line!)) {
this._line = startingScroll.line;
}
break;
case 'fragment':
this._scrollToFragment = startingScroll.fragment;
break;
}
this._register(_contributionProvider.onContributionsChanged(() => {
setTimeout(() => this.refresh(true), 0);
}));
this._register(vscode.workspace.onDidChangeTextDocument(event => {
if (this.isPreviewOf(event.document.uri)) {
this.refresh();
}
}));
this._register(vscode.workspace.onDidOpenTextDocument(document => {
if (this.isPreviewOf(document.uri)) {
this.refresh();
}
}));
const watcher = this._register(vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(resource, '*')));
this._register(watcher.onDidChange(uri => {
if (this.isPreviewOf(uri)) {
// Only use the file system event when VS Code does not already know about the file
if (!vscode.workspace.textDocuments.some(doc => doc.uri.toString() === uri.toString())) {
this.refresh();
}
}
}));
this._register(this._webviewPanel.webview.onDidReceiveMessage((e: FromWebviewMessage.Type) => {
if (e.source !== this._resource.toString()) {
return;
}
switch (e.type) {
case 'cacheImageSizes':
this._imageInfo = e.imageData;
break;
case 'revealLine':
this._onDidScrollPreview(e.line);
break;
case 'didClick':
this._onDidClickPreview(e.line);
break;
case 'openLink':
this._onDidClickPreviewLink(e.href);
break;
case 'showPreviewSecuritySelector':
vscode.commands.executeCommand('markdown.showPreviewSecuritySelector', e.source);
break;
case 'previewStyleLoadError':
vscode.window.showWarningMessage(
vscode.l10n.t("Could not load 'markdown.styles': {0}", e.unloadedStyles.join(', ')));
break;
}
}));
this.refresh();
}
override dispose() {
this._disposeCts.cancel();
super.dispose();
this._disposed = true;
clearTimeout(this._throttleTimer);
for (const entry of this._fileWatchersBySrc.values()) {
entry.dispose();
}
this._fileWatchersBySrc.clear();
}
public get resource(): vscode.Uri {
return this._resource;
}
public get state() {
return {
resource: this._resource.toString(),
line: this._line,
fragment: this._scrollToFragment,
...this._delegate.getAdditionalState(),
};
}
/**
* The first call immediately refreshes the preview,
* calls happening shortly thereafter are debounced.
*/
public refresh(forceUpdate: boolean = false) {
// Schedule update if none is pending
if (!this._throttleTimer) {
if (this._firstUpdate) {
this._updatePreview(true);
} else {
this._throttleTimer = setTimeout(() => this._updatePreview(forceUpdate), this._delay);
}
}
this._firstUpdate = false;
}
public isPreviewOf(resource: vscode.Uri): boolean {
return this._resource.fsPath === resource.fsPath;
}
public postMessage(msg: ToWebviewMessage.Type) {
if (!this._disposed) {
this._webviewPanel.webview.postMessage(msg);
}
}
public scrollTo(topLine: number) {
if (this._disposed) {
return;
}
if (this._isScrolling) {
this._isScrolling = false;
return;
}
this._logger.verbose('MarkdownPreview', 'updateForView', { markdownFile: this._resource });
this._line = topLine;
this.postMessage({
type: 'updateView',
line: topLine,
source: this._resource.toString()
});
}
private async _updatePreview(forceUpdate?: boolean): Promise<void> {
clearTimeout(this._throttleTimer);
this._throttleTimer = undefined;
if (this._disposed) {
return;
}
let document: vscode.TextDocument;
try {
document = await vscode.workspace.openTextDocument(this._resource);
} catch {
if (!this._disposed) {
await this._showFileNotFoundError();
}
return;
}
if (this._disposed) {
return;
}
const pendingVersion = new PreviewDocumentVersion(document);
if (!forceUpdate && this._currentVersion?.equals(pendingVersion)) {
if (this._line) {
this.scrollTo(this._line);
}
return;
}
const shouldReloadPage = forceUpdate || !this._currentVersion || this._currentVersion.resource.toString() !== pendingVersion.resource.toString() || !this._webviewPanel.visible;
this._currentVersion = pendingVersion;
let selectedLine: number | undefined = undefined;
for (const editor of vscode.window.visibleTextEditors) {
if (this.isPreviewOf(editor.document.uri)) {
selectedLine = editor.selection.active.line;
break;
}
}
const content = await (shouldReloadPage
? this._contentProvider.renderDocument(document, this, this._previewConfigurations, this._line, selectedLine, this.state, this._imageInfo, this._disposeCts.token)
: this._contentProvider.renderBody(document, this));
// Another call to `doUpdate` may have happened.
// Make sure we are still updating for the correct document
if (this._currentVersion?.equals(pendingVersion)) {
this._updateWebviewContent(content.html, shouldReloadPage);
this._updateImageWatchers(content.containingImages);
}
}
private _onDidScrollPreview(line: number) {
this._line = line;
this._onScrollEmitter.fire({ line: this._line, uri: this._resource });
const config = this._previewConfigurations.loadAndCacheConfiguration(this._resource);
if (!config.scrollEditorWithPreview) {
return;
}
for (const editor of vscode.window.visibleTextEditors) {
if (!this.isPreviewOf(editor.document.uri)) {
continue;
}
this._isScrolling = true;
scrollEditorToLine(line, editor);
}
}
private async _onDidClickPreview(line: number): Promise<void> {
// fix #82457, find currently opened but unfocused source tab
await vscode.commands.executeCommand('markdown.showSource');
const revealLineInEditor = (editor: vscode.TextEditor) => {
const position = new vscode.Position(line, 0);
const newSelection = new vscode.Selection(position, position);
editor.selection = newSelection;
editor.revealRange(newSelection, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
};
for (const visibleEditor of vscode.window.visibleTextEditors) {
if (this.isPreviewOf(visibleEditor.document.uri)) {
const editor = await vscode.window.showTextDocument(visibleEditor.document, visibleEditor.viewColumn);
revealLineInEditor(editor);
return;
}
}
await vscode.workspace.openTextDocument(this._resource)
.then(vscode.window.showTextDocument)
.then((editor) => {
revealLineInEditor(editor);
}, () => {
vscode.window.showErrorMessage(vscode.l10n.t('Could not open {0}', this._resource.toString()));
});
}
private async _showFileNotFoundError() {
this._webviewPanel.webview.html = this._contentProvider.renderFileNotFoundDocument(this._resource);
}
private _updateWebviewContent(html: string, reloadPage: boolean): void {
if (this._disposed) {
return;
}
if (this._delegate.getTitle) {
this._webviewPanel.title = this._delegate.getTitle(this._resource);
}
this._webviewPanel.webview.options = this._getWebviewOptions();
if (reloadPage) {
this._webviewPanel.webview.html = html;
} else {
this.postMessage({
type: 'updateContent',
content: html,
source: this._resource.toString(),
});
}
}
private _updateImageWatchers(srcs: Set<string>) {
// Delete stale file watchers.
for (const [src, watcher] of this._fileWatchersBySrc) {
if (!srcs.has(src)) {
watcher.dispose();
this._fileWatchersBySrc.delete(src);
}
}
// Create new file watchers.
const root = vscode.Uri.joinPath(this._resource, '../');
for (const src of srcs) {
const uri = urlToUri(src, root);
if (uri && !MarkdownPreview._unwatchedImageSchemes.has(uri.scheme) && !this._fileWatchersBySrc.has(src)) {
const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(uri, '*'));
watcher.onDidChange(() => {
this.refresh(true);
});
this._fileWatchersBySrc.set(src, watcher);
}
}
}
private _getWebviewOptions(): vscode.WebviewOptions {
return {
enableScripts: true,
enableForms: false,
localResourceRoots: this._getLocalResourceRoots()
};
}
private _getLocalResourceRoots(): ReadonlyArray<vscode.Uri> {
const baseRoots = Array.from(this._contributionProvider.contributions.previewResourceRoots);
const folder = vscode.workspace.getWorkspaceFolder(this._resource);
if (folder) {
const workspaceRoots = vscode.workspace.workspaceFolders?.map(folder => folder.uri);
if (workspaceRoots) {
baseRoots.push(...workspaceRoots);
}
} else {
baseRoots.push(uri.Utils.dirname(this._resource));
}
return baseRoots;
}
private async _onDidClickPreviewLink(href: string) {
const config = vscode.workspace.getConfiguration('markdown', this.resource);
const openLinks = config.get<string>('preview.openMarkdownLinks', 'inPreview');
if (openLinks === 'inPreview') {
const resolved = await this._opener.resolveDocumentLink(href, this.resource);
if (resolved.kind === 'file') {
try {
const doc = await vscode.workspace.openTextDocument(vscode.Uri.from(resolved.uri));
if (isMarkdownFile(doc)) {
return this._delegate.openPreviewLinkToMarkdownFile(doc.uri, resolved.fragment ? decodeURIComponent(resolved.fragment) : undefined);
}
} catch {
// Noop
}
}
}
return this._opener.openDocumentLink(href, this.resource);
}
//#region WebviewResourceProvider
asWebviewUri(resource: vscode.Uri) {
return this._webviewPanel.webview.asWebviewUri(resource);
}
get cspSource() {
return this._webviewPanel.webview.cspSource;
}
//#endregion
}
export interface IManagedMarkdownPreview {
readonly resource: vscode.Uri;
readonly resourceColumn: vscode.ViewColumn;
readonly onDispose: vscode.Event<void>;
readonly onDidChangeViewState: vscode.Event<vscode.WebviewPanelOnDidChangeViewStateEvent>;
copyImage(id: string): void;
dispose(): void;
refresh(): void;
updateConfiguration(): void;
matchesResource(
otherResource: vscode.Uri,
otherPosition: vscode.ViewColumn | undefined,
otherLocked: boolean
): boolean;
}
export class StaticMarkdownPreview extends Disposable implements IManagedMarkdownPreview {
public static readonly customEditorViewType = 'vscode.markdown.preview.editor';
public static revive(
resource: vscode.Uri,
webview: vscode.WebviewPanel,
contentProvider: MdDocumentRenderer,
previewConfigurations: MarkdownPreviewConfigurationManager,
topmostLineMonitor: TopmostLineMonitor,
logger: ILogger,
contributionProvider: MarkdownContributionProvider,
opener: MdLinkOpener,
scrollLine?: number,
): StaticMarkdownPreview {
return new StaticMarkdownPreview(webview, resource, contentProvider, previewConfigurations, topmostLineMonitor, logger, contributionProvider, opener, scrollLine);
}
private readonly _preview: MarkdownPreview;
private constructor(
private readonly _webviewPanel: vscode.WebviewPanel,
resource: vscode.Uri,
contentProvider: MdDocumentRenderer,
private readonly _previewConfigurations: MarkdownPreviewConfigurationManager,
topmostLineMonitor: TopmostLineMonitor,
logger: ILogger,
contributionProvider: MarkdownContributionProvider,
opener: MdLinkOpener,
scrollLine?: number,
) {
super();
const topScrollLocation = scrollLine ? new StartingScrollLine(scrollLine) : undefined;
this._preview = this._register(new MarkdownPreview(this._webviewPanel, resource, topScrollLocation, {
getAdditionalState: () => { return {}; },
openPreviewLinkToMarkdownFile: (markdownLink, fragment) => {
return vscode.commands.executeCommand('vscode.openWith', markdownLink.with({
fragment
}), StaticMarkdownPreview.customEditorViewType, this._webviewPanel.viewColumn);
}
}, contentProvider, _previewConfigurations, logger, contributionProvider, opener));
this._register(this._webviewPanel.onDidDispose(() => {
this.dispose();
}));
this._register(this._webviewPanel.onDidChangeViewState(e => {
this._onDidChangeViewState.fire(e);
}));
this._register(this._preview.onScroll((scrollInfo) => {
topmostLineMonitor.setPreviousStaticEditorLine(scrollInfo);
}));
this._register(topmostLineMonitor.onDidChanged(event => {
if (this._preview.isPreviewOf(event.resource)) {
this._preview.scrollTo(event.line);
}
}));
}
copyImage(id: string) {
this._webviewPanel.reveal();
this._preview.postMessage({
type: 'copyImage',
source: this.resource.toString(),
id: id
});
}
private readonly _onDispose = this._register(new vscode.EventEmitter<void>());
public readonly onDispose = this._onDispose.event;
private readonly _onDidChangeViewState = this._register(new vscode.EventEmitter<vscode.WebviewPanelOnDidChangeViewStateEvent>());
public readonly onDidChangeViewState = this._onDidChangeViewState.event;
override dispose() {
this._onDispose.fire();
super.dispose();
}
public matchesResource(
_otherResource: vscode.Uri,
_otherPosition: vscode.ViewColumn | undefined,
_otherLocked: boolean
): boolean {
return false;
}
public refresh() {
this._preview.refresh(true);
}
public updateConfiguration() {
if (this._previewConfigurations.hasConfigurationChanged(this._preview.resource)) {
this.refresh();
}
}
public get resource() {
return this._preview.resource;
}
public get resourceColumn() {
return this._webviewPanel.viewColumn || vscode.ViewColumn.One;
}
}
interface DynamicPreviewInput {
readonly resource: vscode.Uri;
readonly resourceColumn: vscode.ViewColumn;
readonly locked: boolean;
readonly line?: number;
}
export class DynamicMarkdownPreview extends Disposable implements IManagedMarkdownPreview {
public static readonly viewType = 'markdown.preview';
private readonly _resourceColumn: vscode.ViewColumn;
private _locked: boolean;
private readonly _webviewPanel: vscode.WebviewPanel;
private _preview: MarkdownPreview;
public static revive(
input: DynamicPreviewInput,
webview: vscode.WebviewPanel,
contentProvider: MdDocumentRenderer,
previewConfigurations: MarkdownPreviewConfigurationManager,
logger: ILogger,
topmostLineMonitor: TopmostLineMonitor,
contributionProvider: MarkdownContributionProvider,
opener: MdLinkOpener,
): DynamicMarkdownPreview {
webview.iconPath = contentProvider.iconPath;
return new DynamicMarkdownPreview(webview, input,
contentProvider, previewConfigurations, logger, topmostLineMonitor, contributionProvider, opener);
}
public static create(
input: DynamicPreviewInput,
previewColumn: vscode.ViewColumn,
contentProvider: MdDocumentRenderer,
previewConfigurations: MarkdownPreviewConfigurationManager,
logger: ILogger,
topmostLineMonitor: TopmostLineMonitor,
contributionProvider: MarkdownContributionProvider,
opener: MdLinkOpener,
): DynamicMarkdownPreview {
const webview = vscode.window.createWebviewPanel(
DynamicMarkdownPreview.viewType,
DynamicMarkdownPreview._getPreviewTitle(input.resource, input.locked),
previewColumn, { enableFindWidget: true, });
webview.iconPath = contentProvider.iconPath;
return new DynamicMarkdownPreview(webview, input,
contentProvider, previewConfigurations, logger, topmostLineMonitor, contributionProvider, opener);
}
private constructor(
webview: vscode.WebviewPanel,
input: DynamicPreviewInput,
private readonly _contentProvider: MdDocumentRenderer,
private readonly _previewConfigurations: MarkdownPreviewConfigurationManager,
private readonly _logger: ILogger,
private readonly _topmostLineMonitor: TopmostLineMonitor,
private readonly _contributionProvider: MarkdownContributionProvider,
private readonly _opener: MdLinkOpener,
) {
super();
this._webviewPanel = webview;
this._resourceColumn = input.resourceColumn;
this._locked = input.locked;
this._preview = this._createPreview(input.resource, typeof input.line === 'number' ? new StartingScrollLine(input.line) : undefined);
this._register(webview.onDidDispose(() => { this.dispose(); }));
this._register(this._webviewPanel.onDidChangeViewState(e => {
this._onDidChangeViewStateEmitter.fire(e);
}));
this._register(this._topmostLineMonitor.onDidChanged(event => {
if (this._preview.isPreviewOf(event.resource)) {
this._preview.scrollTo(event.line);
}
}));
this._register(vscode.window.onDidChangeTextEditorSelection(event => {
if (this._preview.isPreviewOf(event.textEditor.document.uri)) {
this._preview.postMessage({
type: 'onDidChangeTextEditorSelection',
line: event.selections[0].active.line,
source: this._preview.resource.toString()
});
}
}));
this._register(vscode.window.onDidChangeActiveTextEditor(editor => {
// Only allow previewing normal text editors which have a viewColumn: See #101514
if (typeof editor?.viewColumn === 'undefined') {
return;
}
if (isMarkdownFile(editor.document) && !this._locked && !this._preview.isPreviewOf(editor.document.uri)) {
const line = getVisibleLine(editor);
this.update(editor.document.uri, line ? new StartingScrollLine(line) : undefined);
}
}));
}
copyImage(id: string) {
this._webviewPanel.reveal();
this._preview.postMessage({
type: 'copyImage',
source: this.resource.toString(),
id: id
});
}
private readonly _onDisposeEmitter = this._register(new vscode.EventEmitter<void>());
public readonly onDispose = this._onDisposeEmitter.event;
private readonly _onDidChangeViewStateEmitter = this._register(new vscode.EventEmitter<vscode.WebviewPanelOnDidChangeViewStateEvent>());
public readonly onDidChangeViewState = this._onDidChangeViewStateEmitter.event;
override dispose() {
this._preview.dispose();
this._webviewPanel.dispose();
this._onDisposeEmitter.fire();
this._onDisposeEmitter.dispose();
super.dispose();
}
public get resource() {
return this._preview.resource;
}
public get resourceColumn() {
return this._resourceColumn;
}
public reveal(viewColumn: vscode.ViewColumn) {
this._webviewPanel.reveal(viewColumn);
}
public refresh() {
this._preview.refresh(true);
}
public updateConfiguration() {
if (this._previewConfigurations.hasConfigurationChanged(this._preview.resource)) {
this.refresh();
}
}
public update(newResource: vscode.Uri, scrollLocation?: StartingScrollLocation) {
if (this._preview.isPreviewOf(newResource)) {
switch (scrollLocation?.type) {
case 'line':
this._preview.scrollTo(scrollLocation.line);
return;
case 'fragment':
// Workaround. For fragments, just reload the entire preview
break;
default:
return;
}
}
this._preview.dispose();
this._preview = this._createPreview(newResource, scrollLocation);
}
public toggleLock() {
this._locked = !this._locked;
this._webviewPanel.title = DynamicMarkdownPreview._getPreviewTitle(this._preview.resource, this._locked);
}
private static _getPreviewTitle(resource: vscode.Uri, locked: boolean): string {
const resourceLabel = uri.Utils.basename(resource);
return locked
? vscode.l10n.t('[Preview] {0}', resourceLabel)
: vscode.l10n.t('Preview {0}', resourceLabel);
}
public get position(): vscode.ViewColumn | undefined {
return this._webviewPanel.viewColumn;
}
public matchesResource(
otherResource: vscode.Uri,
otherPosition: vscode.ViewColumn | undefined,
otherLocked: boolean
): boolean {
if (this.position !== otherPosition) {
return false;
}
if (this._locked) {
return otherLocked && this._preview.isPreviewOf(otherResource);
} else {
return !otherLocked;
}
}
public matches(otherPreview: DynamicMarkdownPreview): boolean {
return this.matchesResource(otherPreview._preview.resource, otherPreview.position, otherPreview._locked);
}
private _createPreview(resource: vscode.Uri, startingScroll?: StartingScrollLocation): MarkdownPreview {
return new MarkdownPreview(this._webviewPanel, resource, startingScroll, {
getTitle: (resource) => DynamicMarkdownPreview._getPreviewTitle(resource, this._locked),
getAdditionalState: () => {
return {
resourceColumn: this.resourceColumn,
locked: this._locked,
};
},
openPreviewLinkToMarkdownFile: (link: vscode.Uri, fragment?: string) => {
this.update(link, fragment ? new StartingScrollFragment(fragment) : undefined);
}
},
this._contentProvider,
this._previewConfigurations,
this._logger,
this._contributionProvider,
this._opener);
}
}
| extensions/markdown-language-features/src/preview/preview.ts | 0 | https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5 | [
0.9699039459228516,
0.02303013950586319,
0.00016552282613702118,
0.00017169478815048933,
0.1326231062412262
] |
{
"id": 0,
"code_window": [
"\t/**\n",
"\t * The items to be displayed in the quick pick.\n",
"\t */\n",
"\titems: ReadonlyArray<T | IQuickPickSeparator>;\n",
"\n",
"\t/**\n",
"\t * The scroll position of the quick pick input. Used by keepScrollPosition.\n",
"\t * @todo this should be private\n",
"\t */\n",
"\tscrollTop: number;\n",
"\n",
"\t/**\n",
"\t * Whether multiple items can be selected. If so, checkboxes will be rendered.\n",
"\t */\n",
"\tcanSelectMany: boolean;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/quickinput/common/quickInput.ts",
"type": "replace",
"edit_start_line_idx": 426
} | test/**
src/**
tsconfig.json
out/**
extension.webpack.config.js
extension-browser.webpack.config.js
yarn.lock
| extensions/extension-editing/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5 | [
0.00017249424126930535,
0.00017249424126930535,
0.00017249424126930535,
0.00017249424126930535,
0
] |
{
"id": 0,
"code_window": [
"\t/**\n",
"\t * The items to be displayed in the quick pick.\n",
"\t */\n",
"\titems: ReadonlyArray<T | IQuickPickSeparator>;\n",
"\n",
"\t/**\n",
"\t * The scroll position of the quick pick input. Used by keepScrollPosition.\n",
"\t * @todo this should be private\n",
"\t */\n",
"\tscrollTop: number;\n",
"\n",
"\t/**\n",
"\t * Whether multiple items can be selected. If so, checkboxes will be rendered.\n",
"\t */\n",
"\tcanSelectMany: boolean;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/platform/quickinput/common/quickInput.ts",
"type": "replace",
"edit_start_line_idx": 426
} | [
{
"c": "package",
"t": "source.go keyword.package.go",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6",
"dark_modern": "keyword: #569CD6",
"hc_light": "keyword: #0F4A85",
"light_modern": "keyword: #0000FF"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "main",
"t": "source.go entity.name.package.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "import",
"t": "source.go keyword.import.go",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6",
"dark_modern": "keyword: #569CD6",
"hc_light": "keyword: #0F4A85",
"light_modern": "keyword: #0000FF"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.imports.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "encoding/base64",
"t": "source.go string.quoted.double.go entity.name.import.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "fmt",
"t": "source.go string.quoted.double.go entity.name.import.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.imports.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "func",
"t": "source.go keyword.function.go",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6",
"dark_modern": "keyword: #569CD6",
"hc_light": "keyword: #0F4A85",
"light_modern": "keyword: #0000FF"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "main",
"t": "source.go entity.name.function.go",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "entity.name.function: #DCDCAA",
"dark_modern": "entity.name.function: #DCDCAA",
"hc_light": "entity.name.function: #5E2CBC",
"light_modern": "entity.name.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "{",
"t": "source.go punctuation.definition.begin.bracket.curly.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "dnsName",
"t": "source.go variable.other.assignment.go",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE",
"dark_modern": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_modern": "variable: #001080"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ":=",
"t": "source.go keyword.operator.assignment.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "test-vm-from-go",
"t": "source.go string.quoted.double.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "storageAccount",
"t": "source.go variable.other.assignment.go",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE",
"dark_modern": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_modern": "variable: #001080"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ":=",
"t": "source.go keyword.operator.assignment.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "mystorageaccount",
"t": "source.go string.quoted.double.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "c",
"t": "source.go variable.other.assignment.go",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE",
"dark_modern": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_modern": "variable: #001080"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ":=",
"t": "source.go keyword.operator.assignment.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "make",
"t": "source.go support.function.builtin.go",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_modern": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_modern": "support.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "chan",
"t": "source.go keyword.channel.go",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6",
"dark_modern": "keyword: #569CD6",
"hc_light": "keyword: #0F4A85",
"light_modern": "keyword: #0000FF"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "int",
"t": "source.go storage.type.numeric.go",
"r": {
"dark_plus": "storage.type.numeric.go: #4EC9B0",
"light_plus": "storage.type.numeric.go: #267F99",
"dark_vs": "storage.type: #569CD6",
"light_vs": "storage.type: #0000FF",
"hc_black": "storage.type: #569CD6",
"dark_modern": "storage.type.numeric.go: #4EC9B0",
"hc_light": "storage.type.numeric.go: #185E73",
"light_modern": "storage.type.numeric.go: #267F99"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "client",
"t": "source.go variable.other.assignment.go",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE",
"dark_modern": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_modern": "variable: #001080"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "err",
"t": "source.go variable.other.assignment.go",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE",
"dark_modern": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_modern": "variable: #001080"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ":=",
"t": "source.go keyword.operator.assignment.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": " management",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ".",
"t": "source.go punctuation.other.period.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "ClientFromPublishSettingsFile",
"t": "source.go support.function.go",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_modern": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_modern": "support.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "path/to/downloaded.publishsettings",
"t": "source.go string.quoted.double.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "if",
"t": "source.go keyword.control.go",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0",
"dark_modern": "keyword.control: #C586C0",
"hc_light": "keyword.control: #B5200D",
"light_modern": "keyword.control: #AF00DB"
}
},
{
"c": " err ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "!=",
"t": "source.go keyword.operator.comparison.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "nil",
"t": "source.go constant.language.go",
"r": {
"dark_plus": "constant.language: #569CD6",
"light_plus": "constant.language: #0000FF",
"dark_vs": "constant.language: #569CD6",
"light_vs": "constant.language: #0000FF",
"hc_black": "constant.language: #569CD6",
"dark_modern": "constant.language: #569CD6",
"hc_light": "constant.language: #0F4A85",
"light_modern": "constant.language: #0000FF"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "{",
"t": "source.go punctuation.definition.begin.bracket.curly.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "panic",
"t": "source.go support.function.builtin.go",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_modern": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_modern": "support.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "err",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "}",
"t": "source.go punctuation.definition.end.bracket.curly.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "//",
"t": "source.go comment.line.double-slash.go punctuation.definition.comment.go",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668",
"dark_modern": "comment: #6A9955",
"hc_light": "comment: #515151",
"light_modern": "comment: #008000"
}
},
{
"c": " create virtual machine",
"t": "source.go comment.line.double-slash.go",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668",
"dark_modern": "comment: #6A9955",
"hc_light": "comment: #515151",
"light_modern": "comment: #008000"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "role",
"t": "source.go variable.other.assignment.go",
"r": {
"dark_plus": "variable: #9CDCFE",
"light_plus": "variable: #001080",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "variable: #9CDCFE",
"dark_modern": "variable: #9CDCFE",
"hc_light": "variable: #001080",
"light_modern": "variable: #001080"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ":=",
"t": "source.go keyword.operator.assignment.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": " vmutils",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ".",
"t": "source.go punctuation.other.period.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "NewVMConfiguration",
"t": "source.go support.function.go",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_modern": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_modern": "support.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "dnsName",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " vmSize",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " vmutils",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ".",
"t": "source.go punctuation.other.period.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "ConfigureDeploymentFromPlatformImage",
"t": "source.go support.function.go",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_modern": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_modern": "support.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "&",
"t": "source.go keyword.operator.address.go",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4",
"dark_modern": "keyword.operator: #D4D4D4",
"hc_light": "keyword.operator: #000000",
"light_modern": "keyword.operator: #000000"
}
},
{
"c": "role",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " vmImage",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " fmt",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ".",
"t": "source.go punctuation.other.period.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "Sprintf",
"t": "source.go support.function.go",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA",
"dark_modern": "support.function: #DCDCAA",
"hc_light": "support.function: #5E2CBC",
"light_modern": "support.function: #795E26"
}
},
{
"c": "(",
"t": "source.go punctuation.definition.begin.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "http://",
"t": "source.go string.quoted.double.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "%s",
"t": "source.go string.quoted.double.go constant.other.placeholder.go",
"r": {
"dark_plus": "constant.other.placeholder: #9CDCFE",
"light_plus": "constant.other.placeholder: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "constant.other.placeholder: #9CDCFE",
"hc_light": "constant.other.placeholder: #001080",
"light_modern": "constant.other.placeholder: #001080"
}
},
{
"c": ".blob.core.windows.net/sdktest/",
"t": "source.go string.quoted.double.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "%s",
"t": "source.go string.quoted.double.go constant.other.placeholder.go",
"r": {
"dark_plus": "constant.other.placeholder: #9CDCFE",
"light_plus": "constant.other.placeholder: #001080",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "constant.other.placeholder: #9CDCFE",
"hc_light": "constant.other.placeholder: #001080",
"light_modern": "constant.other.placeholder: #001080"
}
},
{
"c": ".vhd",
"t": "source.go string.quoted.double.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " storageAccount",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " dnsName",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": ",",
"t": "source.go punctuation.other.comma.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": " ",
"t": "source.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.begin.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": "\"",
"t": "source.go string.quoted.double.go punctuation.definition.string.end.go",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178",
"dark_modern": "string: #CE9178",
"hc_light": "string: #0F4A85",
"light_modern": "string: #A31515"
}
},
{
"c": ")",
"t": "source.go punctuation.definition.end.bracket.round.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
},
{
"c": "}",
"t": "source.go punctuation.definition.end.bracket.curly.go",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF",
"dark_modern": "default: #CCCCCC",
"hc_light": "default: #292929",
"light_modern": "default: #3B3B3B"
}
}
] | extensions/vscode-colorize-tests/test/colorize-results/test_go.json | 0 | https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5 | [
0.0001736066915327683,
0.00017150520579889417,
0.00017005050904117525,
0.0001715416001388803,
7.916585218481487e-7
] |
{
"id": 1,
"code_window": [
"import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';\n",
"import { toDisposable } from 'vs/base/common/lifecycle';\n",
"import { mainWindow } from 'vs/base/browser/window';\n",
"\n",
"// Sets up an `onShow` listener to allow us to wait until the quick pick is shown (useful when triggering an `accept()` right after launching a quick pick)\n",
"// kick this off before you launch the picker and then await the promise returned after you launch the picker.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { QuickPick } from 'vs/platform/quickinput/browser/quickInput';\n",
"import { IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n"
],
"file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts",
"type": "add",
"edit_start_line_idx": 20
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { Event } from 'vs/base/common/event';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IQuickAccessController } from 'vs/platform/quickinput/common/quickAccess';
import { IMatch } from 'vs/base/common/filters';
import { IItemAccessor } from 'vs/base/common/fuzzyScorer';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import Severity from 'vs/base/common/severity';
import { URI } from 'vs/base/common/uri';
import { IMarkdownString } from 'vs/base/common/htmlContent';
export interface IQuickPickItemHighlights {
label?: IMatch[];
description?: IMatch[];
detail?: IMatch[];
}
export type QuickPickItem = IQuickPickSeparator | IQuickPickItem;
export interface IQuickPickItem {
type?: 'item';
id?: string;
label: string;
ariaLabel?: string;
description?: string;
detail?: string;
tooltip?: string | IMarkdownString;
/**
* Allows to show a keybinding next to the item to indicate
* how the item can be triggered outside of the picker using
* keyboard shortcut.
*/
keybinding?: ResolvedKeybinding;
iconClasses?: readonly string[];
iconPath?: { dark: URI; light?: URI };
iconClass?: string;
italic?: boolean;
strikethrough?: boolean;
highlights?: IQuickPickItemHighlights;
buttons?: readonly IQuickInputButton[];
picked?: boolean;
alwaysShow?: boolean;
}
export interface IQuickPickSeparator {
type: 'separator';
id?: string;
label?: string;
ariaLabel?: string;
buttons?: readonly IQuickInputButton[];
tooltip?: string | IMarkdownString;
}
export interface IKeyMods {
readonly ctrlCmd: boolean;
readonly alt: boolean;
}
export const NO_KEY_MODS: IKeyMods = { ctrlCmd: false, alt: false };
export interface IQuickNavigateConfiguration {
keybindings: readonly ResolvedKeybinding[];
}
export interface IPickOptions<T extends IQuickPickItem> {
/**
* an optional string to show as the title of the quick input
*/
title?: string;
/**
* an optional string to show as placeholder in the input box to guide the user what she picks on
*/
placeHolder?: string;
/**
* an optional flag to include the description when filtering the picks
*/
matchOnDescription?: boolean;
/**
* an optional flag to include the detail when filtering the picks
*/
matchOnDetail?: boolean;
/**
* an optional flag to filter the picks based on label. Defaults to true.
*/
matchOnLabel?: boolean;
/**
* an optional flag to not close the picker on focus lost
*/
ignoreFocusLost?: boolean;
/**
* an optional flag to make this picker multi-select
*/
canPickMany?: boolean;
/**
* enables quick navigate in the picker to open an element without typing
*/
quickNavigate?: IQuickNavigateConfiguration;
/**
* Hides the input box from the picker UI. This is typically used
* in combination with quick-navigation where no search UI should
* be presented.
*/
hideInput?: boolean;
/**
* a context key to set when this picker is active
*/
contextKey?: string;
/**
* an optional property for the item to focus initially.
*/
activeItem?: Promise<T> | T;
onKeyMods?: (keyMods: IKeyMods) => void;
onDidFocus?: (entry: T) => void;
onDidTriggerItemButton?: (context: IQuickPickItemButtonContext<T>) => void;
onDidTriggerSeparatorButton?: (context: IQuickPickSeparatorButtonEvent) => void;
}
export interface IInputOptions {
/**
* an optional string to show as the title of the quick input
*/
title?: string;
/**
* the value to prefill in the input box
*/
value?: string;
/**
* the selection of value, default to the whole prefilled value
*/
valueSelection?: readonly [number, number];
/**
* the text to display underneath the input box
*/
prompt?: string;
/**
* an optional string to show as placeholder in the input box to guide the user what to type
*/
placeHolder?: string;
/**
* Controls if a password input is shown. Password input hides the typed text.
*/
password?: boolean;
/**
* an optional flag to not close the input on focus lost
*/
ignoreFocusLost?: boolean;
/**
* an optional function that is used to validate user input.
*/
validateInput?: (input: string) => Promise<string | null | undefined | { content: string; severity: Severity }>;
}
export enum QuickInputHideReason {
/**
* Focus moved away from the quick input.
*/
Blur = 1,
/**
* An explicit user gesture, e.g. pressing Escape key.
*/
Gesture,
/**
* Anything else.
*/
Other
}
export interface IQuickInputHideEvent {
reason: QuickInputHideReason;
}
/**
* Represents a quick input control that allows users to make selections or provide input quickly.
*/
export interface IQuickInput extends IDisposable {
/**
* An event that is fired when the quick input is hidden.
*/
readonly onDidHide: Event<IQuickInputHideEvent>;
/**
* An event that is fired when the quick input is disposed.
*/
readonly onDispose: Event<void>;
/**
* The title of the quick input.
*/
title: string | undefined;
/**
* The description of the quick input. This is rendered right below the input box.
*/
description: string | undefined;
/**
* An HTML widget rendered below the input.
* @deprecated Use an IQuickWidget instead.
*/
widget: any | undefined;
/**
* The current step of the quick input rendered in the titlebar.
*/
step: number | undefined;
/**
* The total number of steps in the quick input rendered in the titlebar.
*/
totalSteps: number | undefined;
/**
* The buttons displayed in the quick input titlebar.
*/
buttons: ReadonlyArray<IQuickInputButton>;
/**
* An event that is fired when a button in the quick input is triggered.
*/
readonly onDidTriggerButton: Event<IQuickInputButton>;
/**
* Indicates whether the input is enabled.
*/
enabled: boolean;
/**
* The context key associated with the quick input.
*/
contextKey: string | undefined;
/**
* Indicates whether the quick input is busy. Renders a progress bar if true.
*/
busy: boolean;
/**
* Indicates whether the quick input should be hidden when it loses focus.
*/
ignoreFocusOut: boolean;
/**
* Shows the quick input.
*/
show(): void;
/**
* Hides the quick input.
*/
hide(): void;
/**
* Notifies that the quick input has been hidden.
* @param reason The reason why the quick input was hidden.
*/
didHide(reason?: QuickInputHideReason): void;
}
export interface IQuickWidget extends IQuickInput {
/**
* Should be an HTMLElement (TODO: move this entire file into browser)
* @override
*/
widget: any | undefined;
}
export interface IQuickPickWillAcceptEvent {
/**
* Allows to disable the default accept handling
* of the picker. If `veto` is called, the picker
* will not trigger the `onDidAccept` event.
*/
veto(): void;
}
export interface IQuickPickDidAcceptEvent {
/**
* Signals if the picker item is to be accepted
* in the background while keeping the picker open.
*/
inBackground: boolean;
}
/**
* Represents the activation behavior for items in a quick input. This means which item will be
* "active" (aka focused).
*/
export enum ItemActivation {
/**
* No item will be active.
*/
NONE,
/**
* First item will be active.
*/
FIRST,
/**
* Second item will be active.
*/
SECOND,
/**
* Last item will be active.
*/
LAST
}
/**
* Represents a quick pick control that allows the user to select an item from a list of options.
*/
export interface IQuickPick<T extends IQuickPickItem> extends IQuickInput {
/**
* The current value of the quick pick input.
*/
value: string;
/**
* A method that allows to massage the value used for filtering, e.g, to remove certain parts.
* @param value The value to be filtered.
* @returns The filtered value.
*/
filterValue: (value: string) => string;
/**
* The ARIA label for the quick pick input.
*/
ariaLabel: string | undefined;
/**
* The placeholder text for the quick pick input.
*/
placeholder: string | undefined;
/**
* An event that is fired when the value of the quick pick input changes.
*/
readonly onDidChangeValue: Event<string>;
/**
* An event that is fired when the quick pick is about to accept the selected item.
*/
readonly onWillAccept: Event<IQuickPickWillAcceptEvent>;
/**
* An event that is fired when the quick pick has accepted the selected item.
*/
readonly onDidAccept: Event<IQuickPickDidAcceptEvent>;
/**
* If enabled, the `onDidAccept` event will be fired when pressing the arrow-right key to accept the selected item without closing the picker.
*/
canAcceptInBackground: boolean;
/**
* The OK button state. It can be a boolean value or the string 'default'.
*/
ok: boolean | 'default';
/**
* An event that is fired when the custom button is triggered. The custom button is a button with text rendered to the right of the input.
*/
readonly onDidCustom: Event<void>;
/**
* Whether to show the custom button. The custom button is a button with text rendered to the right of the input.
*/
customButton: boolean;
/**
* The label for the custom button. The custom button is a button with text rendered to the right of the input.
*/
customLabel: string | undefined;
/**
* The hover text for the custom button. The custom button is a button with text rendered to the right of the input.
*/
customHover: string | undefined;
/**
* An event that is fired when an item button is triggered.
*/
readonly onDidTriggerItemButton: Event<IQuickPickItemButtonEvent<T>>;
/**
* An event that is fired when a separator button is triggered.
*/
readonly onDidTriggerSeparatorButton: Event<IQuickPickSeparatorButtonEvent>;
/**
* The items to be displayed in the quick pick.
*/
items: ReadonlyArray<T | IQuickPickSeparator>;
/**
* The scroll position of the quick pick input. Used by keepScrollPosition.
* @todo this should be private
*/
scrollTop: number;
/**
* Whether multiple items can be selected. If so, checkboxes will be rendered.
*/
canSelectMany: boolean;
/**
* Whether to match on the description of the items.
*/
matchOnDescription: boolean;
/**
* Whether to match on the detail of the items.
*/
matchOnDetail: boolean;
/**
* Whether to match on the label of the items.
*/
matchOnLabel: boolean;
/**
* The mode to filter the label with. It can be 'fuzzy' or 'contiguous'. Defaults to 'fuzzy'.
*/
matchOnLabelMode: 'fuzzy' | 'contiguous';
/**
* Whether to sort the items by label.
*/
sortByLabel: boolean;
/**
* Whether to keep the scroll position when the quick pick input is updated.
*/
keepScrollPosition: boolean;
/**
* The configuration for quick navigation.
*/
quickNavigate: IQuickNavigateConfiguration | undefined;
/**
* The currently active items.
*/
activeItems: ReadonlyArray<T>;
/**
* An event that is fired when the active items change.
*/
readonly onDidChangeActive: Event<T[]>;
/**
* The item activation behavior for the next time `items` is set. Item activation means which
* item is "active" (aka focused) when the quick pick is opened or when `items` is set.
*/
itemActivation: ItemActivation;
/**
* The currently selected items.
*/
selectedItems: ReadonlyArray<T>;
/**
* An event that is fired when the selected items change.
*/
readonly onDidChangeSelection: Event<T[]>;
/**
* The key modifiers.
*/
readonly keyMods: IKeyMods;
/**
* The selection range for the value in the input.
*/
valueSelection: Readonly<[number, number]> | undefined;
/**
* The validation message for the quick pick. This is rendered below the input.
*/
validationMessage: string | undefined;
/**
* The severity of the validation message.
*/
severity: Severity;
/**
* Checks if the quick pick input has focus.
* @returns `true` if the quick pick input has focus, `false` otherwise.
*/
inputHasFocus(): boolean;
/**
* Focuses on the quick pick input.
*/
focusOnInput(): void;
/**
* Hides the input box from the picker UI. This is typically used in combination with quick-navigation where no search UI should be presented.
*/
hideInput: boolean;
/**
* Controls whether the count for the items should be shown.
*/
hideCountBadge: boolean;
/**
* Whether to hide the "Check All" checkbox.
*/
hideCheckAll: boolean;
/**
* The toggle buttons to be added to the input box.
*/
toggles: IQuickInputToggle[] | undefined;
}
/**
* Represents a toggle for quick input.
*/
export interface IQuickInputToggle {
/**
* Event that is fired when the toggle value changes.
* The boolean value indicates whether the change was triggered via keyboard.
*/
onChange: Event<boolean>;
}
/**
* Represents an input box in a quick input dialog.
*/
export interface IInputBox extends IQuickInput {
/**
* Value shown in the input box.
*/
value: string;
/**
* Provide start and end values to be selected in the input box.
*/
valueSelection: Readonly<[number, number]> | undefined;
/**
* Value shown as example for input.
*/
placeholder: string | undefined;
/**
* Determines if the input value should be hidden while typing.
*/
password: boolean;
/**
* Event called when the input value changes.
*/
readonly onDidChangeValue: Event<string>;
/**
* Event called when the user submits the input.
*/
readonly onDidAccept: Event<void>;
/**
* Text show below the input box.
*/
prompt: string | undefined;
/**
* An optional validation message indicating a problem with the current input value.
* Returning undefined clears the validation message.
*/
validationMessage: string | undefined;
/**
* Severity of the input validation message.
*/
severity: Severity;
}
/**
* Represents a button in the quick input UI.
*/
export interface IQuickInputButton {
/**
* The path to the icon for the button.
* Either `iconPath` or `iconClass` is required.
*/
iconPath?: { dark: URI; light?: URI };
/**
* The CSS class for the icon of the button.
* Either `iconPath` or `iconClass` is required.
*/
iconClass?: string;
/**
* The tooltip text for the button.
*/
tooltip?: string;
/**
* Whether to always show the button.
* By default, buttons are only visible when hovering over them with the mouse.
*/
alwaysVisible?: boolean;
}
/**
* Represents an event that occurs when a button associated with a quick pick item is clicked.
* @template T - The type of the quick pick item.
*/
export interface IQuickPickItemButtonEvent<T extends IQuickPickItem> {
/**
* The button that was clicked.
*/
button: IQuickInputButton;
/**
* The quick pick item associated with the button.
*/
item: T;
}
/**
* Represents an event that occurs when a separator button is clicked in a quick pick.
*/
export interface IQuickPickSeparatorButtonEvent {
/**
* The button that was clicked.
*/
button: IQuickInputButton;
/**
* The separator associated with the button.
*/
separator: IQuickPickSeparator;
}
/**
* Represents a context for a button associated with a quick pick item.
* @template T - The type of the quick pick item.
*/
export interface IQuickPickItemButtonContext<T extends IQuickPickItem> extends IQuickPickItemButtonEvent<T> {
/**
* Removes the associated item from the quick pick.
*/
removeItem(): void;
}
export type QuickPickInput<T = IQuickPickItem> = T | IQuickPickSeparator;
//#region Fuzzy Scorer Support
export type IQuickPickItemWithResource = IQuickPickItem & { resource?: URI };
export class QuickPickItemScorerAccessor implements IItemAccessor<IQuickPickItemWithResource> {
constructor(private options?: { skipDescription?: boolean; skipPath?: boolean }) { }
getItemLabel(entry: IQuickPickItemWithResource): string {
return entry.label;
}
getItemDescription(entry: IQuickPickItemWithResource): string | undefined {
if (this.options?.skipDescription) {
return undefined;
}
return entry.description;
}
getItemPath(entry: IQuickPickItemWithResource): string | undefined {
if (this.options?.skipPath) {
return undefined;
}
if (entry.resource?.scheme === Schemas.file) {
return entry.resource.fsPath;
}
return entry.resource?.path;
}
}
export const quickPickItemScorerAccessor = new QuickPickItemScorerAccessor();
//#endregion
export const IQuickInputService = createDecorator<IQuickInputService>('quickInputService');
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export interface IQuickInputService {
readonly _serviceBrand: undefined;
/**
* Provides access to the back button in quick input.
*/
readonly backButton: IQuickInputButton;
/**
* Provides access to the quick access providers.
*/
readonly quickAccess: IQuickAccessController;
/**
* Allows to register on the event that quick input is showing.
*/
readonly onShow: Event<void>;
/**
* Allows to register on the event that quick input is hiding.
*/
readonly onHide: Event<void>;
/**
* Opens the quick input box for selecting items and returns a promise
* with the user selected item(s) if any.
*/
pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: true }, token?: CancellationToken): Promise<T[] | undefined>;
pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: false }, token?: CancellationToken): Promise<T | undefined>;
pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: Omit<IPickOptions<T>, 'canPickMany'>, token?: CancellationToken): Promise<T | undefined>;
/**
* Opens the quick input box for text input and returns a promise with the user typed value if any.
*/
input(options?: IInputOptions, token?: CancellationToken): Promise<string | undefined>;
/**
* Provides raw access to the quick pick controller.
*/
createQuickPick<T extends IQuickPickItem>(): IQuickPick<T>;
/**
* Provides raw access to the input box controller.
*/
createInputBox(): IInputBox;
/**
* Provides raw access to the quick widget controller.
*/
createQuickWidget(): IQuickWidget;
/**
* Moves focus into quick input.
*/
focus(): void;
/**
* Toggle the checked state of the selected item.
*/
toggle(): void;
/**
* Navigate inside the opened quick input list.
*/
navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void;
/**
* Navigate back in a multi-step quick input.
*/
back(): Promise<void>;
/**
* Accept the selected item.
*
* @param keyMods allows to override the state of key
* modifiers that should be present when invoking.
*/
accept(keyMods?: IKeyMods): Promise<void>;
/**
* Cancels quick input and closes it.
*/
cancel(): Promise<void>;
}
| src/vs/platform/quickinput/common/quickInput.ts | 1 | https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5 | [
0.002890805248171091,
0.00021081946033518761,
0.00016174338816199452,
0.00016877084271982312,
0.00030102135497145355
] |
{
"id": 1,
"code_window": [
"import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';\n",
"import { toDisposable } from 'vs/base/common/lifecycle';\n",
"import { mainWindow } from 'vs/base/browser/window';\n",
"\n",
"// Sets up an `onShow` listener to allow us to wait until the quick pick is shown (useful when triggering an `accept()` right after launching a quick pick)\n",
"// kick this off before you launch the picker and then await the promise returned after you launch the picker.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { QuickPick } from 'vs/platform/quickinput/browser/quickInput';\n",
"import { IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n"
],
"file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts",
"type": "add",
"edit_start_line_idx": 20
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Button } from 'vs/base/browser/ui/button/button';
import { IAction } from 'vs/base/common/actions';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { IMenu } from 'vs/platform/actions/common/actions';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
export class CommentFormActions implements IDisposable {
private _buttonElements: HTMLElement[] = [];
private readonly _toDispose = new DisposableStore();
private _actions: IAction[] = [];
constructor(
private container: HTMLElement,
private actionHandler: (action: IAction) => void,
private readonly maxActions?: number
) { }
setActions(menu: IMenu, hasOnlySecondaryActions: boolean = false) {
this._toDispose.clear();
this._buttonElements.forEach(b => b.remove());
this._buttonElements = [];
const groups = menu.getActions({ shouldForwardArgs: true });
let isPrimary: boolean = !hasOnlySecondaryActions;
for (const group of groups) {
const [, actions] = group;
this._actions = actions;
for (const action of actions) {
const button = new Button(this.container, { secondary: !isPrimary, ...defaultButtonStyles });
isPrimary = false;
this._buttonElements.push(button.element);
this._toDispose.add(button);
this._toDispose.add(button.onDidClick(() => this.actionHandler(action)));
button.enabled = action.enabled;
button.label = action.label;
if ((this.maxActions !== undefined) && (this._buttonElements.length >= this.maxActions)) {
console.warn(`An extension has contributed more than the allowable number of actions to a comments menu.`);
return;
}
}
}
}
triggerDefaultAction() {
if (this._actions.length) {
const lastAction = this._actions[0];
if (lastAction.enabled) {
return this.actionHandler(lastAction);
}
}
}
dispose() {
this._toDispose.dispose();
}
}
| src/vs/workbench/contrib/comments/browser/commentFormActions.ts | 0 | https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5 | [
0.00017034521442838013,
0.00016779683937784284,
0.00016634984058327973,
0.00016695083468221128,
0.000001413735958522011
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.