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": 0,
"code_window": [
" },\n",
" \"activationEvents\": [\n",
" \"onResolveRemoteAuthority:test\",\n",
" \"onCommand:vscode-testresolver.newWindow\",\n",
" \"onCommand:vscode-testresolver.newWindowWithError\",\n",
" \"onCommand:vscode-testresolver.showLog\",\n",
" \"onCommand:vscode-testresolver.openTunnel\",\n",
" \"onCommand:vscode-testresolver.startRemoteServer\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"onCommand:vscode-testresolver.currentWindow\",\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { ExtHostInteractiveShape, IMainContext } from 'vs/workbench/api/common/extHost.protocol';
import { ApiCommand, ApiCommandArgument, ApiCommandResult, ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { NotebookEditor } from 'vscode';
export class ExtHostInteractive implements ExtHostInteractiveShape {
constructor(
mainContext: IMainContext,
private _extHostNotebooks: ExtHostNotebookController,
private _textDocumentsAndEditors: ExtHostDocumentsAndEditors,
private _commands: ExtHostCommands
) {
const openApiCommand = new ApiCommand(
'interactive.open',
'_interactive.open',
'Open interactive window and return notebook editor and input URI',
[
new ApiCommandArgument('showOptions', 'Show Options', v => true, v => v),
new ApiCommandArgument('resource', 'Interactive resource Uri', v => true, v => v),
new ApiCommandArgument('controllerId', 'Notebook controller Id', v => true, v => v),
new ApiCommandArgument('title', 'Interactive editor title', v => true, v => v)
],
new ApiCommandResult<{ notebookUri: UriComponents, inputUri: UriComponents, notebookEditorId?: string }, { notebookUri: URI, inputUri: URI, notebookEditor?: NotebookEditor }>('Notebook and input URI', (v: { notebookUri: UriComponents, inputUri: UriComponents, notebookEditorId?: string }) => {
if (v.notebookEditorId !== undefined) {
const editor = this._extHostNotebooks.getEditorById(v.notebookEditorId);
return { notebookUri: URI.revive(v.notebookUri), inputUri: URI.revive(v.inputUri), notebookEditor: editor.apiEditor };
}
return { notebookUri: URI.revive(v.notebookUri), inputUri: URI.revive(v.inputUri) };
})
);
this._commands.registerApiCommand(openApiCommand);
}
$willAddInteractiveDocument(uri: UriComponents, eol: string, languageId: string, notebookUri: UriComponents) {
this._textDocumentsAndEditors.acceptDocumentsAndEditorsDelta({
addedDocuments: [{
EOL: eol,
lines: [''],
languageId: languageId,
uri: uri,
isDirty: false,
versionId: 1,
notebook: this._extHostNotebooks.getNotebookDocument(URI.revive(notebookUri))?.apiNotebook
}]
});
}
$willRemoveInteractiveDocument(uri: UriComponents, notebookUri: UriComponents) {
this._textDocumentsAndEditors.acceptDocumentsAndEditorsDelta({
removedDocuments: [uri]
});
}
}
| src/vs/workbench/api/common/extHostInteractive.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.0001728490460664034,
0.00017104313883464783,
0.00016860321920830756,
0.0001713946257950738,
0.0000014807843626840622
] |
{
"id": 0,
"code_window": [
" },\n",
" \"activationEvents\": [\n",
" \"onResolveRemoteAuthority:test\",\n",
" \"onCommand:vscode-testresolver.newWindow\",\n",
" \"onCommand:vscode-testresolver.newWindowWithError\",\n",
" \"onCommand:vscode-testresolver.showLog\",\n",
" \"onCommand:vscode-testresolver.openTunnel\",\n",
" \"onCommand:vscode-testresolver.startRemoteServer\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"onCommand:vscode-testresolver.currentWindow\",\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 25
} | {
"compilerOptions": {
"target": "es6"
}
} | extensions/vscode-colorize-tests/test/colorize-fixtures/tsconfig_off.json | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.00017021952953655273,
0.00017021952953655273,
0.00017021952953655273,
0.00017021952953655273,
0
] |
{
"id": 1,
"code_window": [
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.newWindow\"\n",
" },\n",
" {\n",
" \"title\": \"Show TestResolver Log\",\n",
" \"category\": \"Remote-TestResolver\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {\n",
" \"title\": \"Connect to TestResolver in Current Window\",\n",
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.currentWindow\"\n",
" },\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 61
} | {
"name": "vscode-test-resolver",
"description": "Test resolver for VS Code",
"version": "0.0.1",
"publisher": "vscode",
"license": "MIT",
"enableProposedApi": true,
"enabledApiProposals": [
"resolvers"
],
"private": true,
"engines": {
"vscode": "^1.25.0"
},
"icon": "media/icon.png",
"extensionKind": [
"ui"
],
"scripts": {
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"vscode:prepublish": "node ../../node_modules/gulp/bin/gulp.js --gulpfile ../../build/gulpfile.extensions.js compile-extension:vscode-test-resolver"
},
"activationEvents": [
"onResolveRemoteAuthority:test",
"onCommand:vscode-testresolver.newWindow",
"onCommand:vscode-testresolver.newWindowWithError",
"onCommand:vscode-testresolver.showLog",
"onCommand:vscode-testresolver.openTunnel",
"onCommand:vscode-testresolver.startRemoteServer",
"onCommand:vscode-testresolver.toggleConnectionPause"
],
"main": "./out/extension",
"devDependencies": {
"@types/node": "14.x"
},
"capabilities": {
"untrustedWorkspaces": {
"supported": true
},
"virtualWorkspaces": true
},
"contributes": {
"resourceLabelFormatters": [
{
"scheme": "vscode-remote",
"authority": "test+*",
"formatting": {
"label": "${path}",
"separator": "/",
"tildify": true,
"workspaceSuffix": "TestResolver",
"workspaceTooltip": "Remote running on the same machine"
}
}
],
"commands": [
{
"title": "New TestResolver Window",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.newWindow"
},
{
"title": "Show TestResolver Log",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.showLog"
},
{
"title": "Kill Remote Server and Trigger Handled Error",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.killServerAndTriggerHandledError"
},
{
"title": "Open Tunnel...",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.openTunnel"
},
{
"title": "Open a Remote Port...",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.startRemoteServer"
},
{
"title": "Pause Connection (Test Reconnect)",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.toggleConnectionPause"
}
],
"menus": {
"commandPalette": [
{
"command": "vscode-testresolver.openTunnel",
"when": "remoteName == test"
},
{
"command": "vscode-testresolver.startRemoteServer",
"when": "remoteName == test"
},
{
"command": "vscode-testresolver.toggleConnectionPause",
"when": "remoteName == test"
}
],
"statusBar/remoteIndicator": [
{
"command": "vscode-testresolver.newWindow",
"when": "!remoteName && !virtualWorkspace",
"group": "remote_90_test_1_local@2"
},
{
"command": "vscode-testresolver.showLog",
"when": "remoteName == test",
"group": "remote_90_test_1_open@3"
},
{
"command": "vscode-testresolver.newWindow",
"when": "remoteName == test",
"group": "remote_90_test_1_open@1"
},
{
"command": "vscode-testresolver.openTunnel",
"when": "remoteName == test",
"group": "remote_90_test_2_more@4"
},
{
"command": "vscode-testresolver.startRemoteServer",
"when": "remoteName == test",
"group": "remote_90_test_2_more@5"
},
{
"command": "vscode-testresolver.toggleConnectionPause",
"when": "remoteName == test",
"group": "remote_90_test_2_more@6"
}
]
},
"configuration": {
"properties": {
"testresolver.startupDelay": {
"description": "If set, the resolver will delay for the given amount of seconds. Use ths setting for testing a slow resolver",
"type": "number",
"default": 0
},
"testresolver.startupError": {
"description": "If set, the resolver will fail. Use ths setting for testing the failure of a resolver.",
"type": "boolean",
"default": false
},
"testresolver.supportPublicPorts": {
"description": "If set, the test resolver tunnel factory will support mock public ports. Forwarded ports will not actually be public. Requires reload.",
"type": "boolean",
"default": false
}
}
}
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/vscode-test-resolver/package.json | 1 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.01893978752195835,
0.0020153040532022715,
0.00016467164095956832,
0.00023598436382599175,
0.004583468660712242
] |
{
"id": 1,
"code_window": [
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.newWindow\"\n",
" },\n",
" {\n",
" \"title\": \"Show TestResolver Log\",\n",
" \"category\": \"Remote-TestResolver\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {\n",
" \"title\": \"Connect to TestResolver in Current Window\",\n",
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.currentWindow\"\n",
" },\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 61
} | /*---------------------------------------------------------------------------------------------
* 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 { findExpressionInStackFrame } from 'vs/workbench/contrib/debug/browser/debugHover';
import { createMockSession } from 'vs/workbench/contrib/debug/test/browser/callStack.test';
import { StackFrame, Thread, Scope, Variable } from 'vs/workbench/contrib/debug/common/debugModel';
import { Source } from 'vs/workbench/contrib/debug/common/debugSource';
import type { IScope, IExpression } from 'vs/workbench/contrib/debug/common/debug';
import { createMockDebugModel, mockUriIdentityService } from 'vs/workbench/contrib/debug/test/browser/mockDebug';
suite('Debug - Hover', () => {
test('find expression in stack frame', async () => {
const model = createMockDebugModel();
const session = createMockSession(model);
let stackFrame: StackFrame;
const thread = new class extends Thread {
public override getCallStack(): StackFrame[] {
return [stackFrame];
}
}(session, 'mockthread', 1);
const firstSource = new Source({
name: 'internalModule.js',
path: 'a/b/c/d/internalModule.js',
sourceReference: 10,
}, 'aDebugSessionId', mockUriIdentityService);
let scope: Scope;
stackFrame = new class extends StackFrame {
override getScopes(): Promise<IScope[]> {
return Promise.resolve([scope]);
}
}(thread, 1, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true);
let variableA: Variable;
let variableB: Variable;
scope = new class extends Scope {
override getChildren(): Promise<IExpression[]> {
return Promise.resolve([variableA]);
}
}(stackFrame, 1, 'local', 1, false, 10, 10);
variableA = new class extends Variable {
override getChildren(): Promise<IExpression[]> {
return Promise.resolve([variableB]);
}
}(session, 1, scope, 2, 'A', 'A', undefined!, 0, 0, {}, 'string');
variableB = new Variable(session, 1, scope, 2, 'B', 'A.B', undefined!, 0, 0, {}, 'string');
assert.strictEqual(await findExpressionInStackFrame(stackFrame, []), undefined);
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['A']), variableA);
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['doesNotExist', 'no']), undefined);
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['a']), undefined);
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['B']), undefined);
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['A', 'B']), variableB);
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['A', 'C']), undefined);
// We do not search in expensive scopes
scope.expensive = true;
assert.strictEqual(await findExpressionInStackFrame(stackFrame, ['A']), undefined);
});
});
| src/vs/workbench/contrib/debug/test/browser/debugHover.test.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.00017443535034544766,
0.00017181530711241066,
0.00017023950931616127,
0.0001714366371743381,
0.0000012964299003215274
] |
{
"id": 1,
"code_window": [
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.newWindow\"\n",
" },\n",
" {\n",
" \"title\": \"Show TestResolver Log\",\n",
" \"category\": \"Remote-TestResolver\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {\n",
" \"title\": \"Connect to TestResolver in Current Window\",\n",
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.currentWindow\"\n",
" },\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 61
} | <div class="entry">
<h1>{{title}}</h1>
{{#if author}}
<h2>{{author.firstName}} {{author.lastName}}</h2>
{{else}}
<h2>Unknown Author</h2>
{{/if}}
{{contentBody}}
</div>
{{#unless license}}
<h3 class="warning">WARNING: This entry does not have a license!</h3>
{{/unless}}
<div class="footnotes">
<ul>
{{#each footnotes}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>
<h1>Comments</h1>
<div id="comments">
{{#each comments}}
<h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2>
<div>{{body}}</div>
{{/each}}
</div> | extensions/vscode-colorize-tests/test/colorize-fixtures/test.handlebars | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.00017606845358386636,
0.00017283426132053137,
0.00016978365601971745,
0.00017274246783927083,
0.0000022473450371762738
] |
{
"id": 1,
"code_window": [
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.newWindow\"\n",
" },\n",
" {\n",
" \"title\": \"Show TestResolver Log\",\n",
" \"category\": \"Remote-TestResolver\",\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" {\n",
" \"title\": \"Connect to TestResolver in Current Window\",\n",
" \"category\": \"Remote-TestResolver\",\n",
" \"command\": \"vscode-testresolver.currentWindow\"\n",
" },\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 61
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { getCodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorOption, RenderLineNumbersType } from 'vs/editor/common/config/editorOptions';
import { IPosition } from 'vs/editor/common/core/position';
import { IRange } from 'vs/editor/common/core/range';
import { IEditor, ScrollType } from 'vs/editor/common/editorCommon';
import { AbstractEditorNavigationQuickAccessProvider, IQuickAccessTextEditorContext } from 'vs/editor/contrib/quickAccess/editorNavigationQuickAccess';
import { localize } from 'vs/nls';
import { IQuickPick, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
interface IGotoLineQuickPickItem extends IQuickPickItem, Partial<IPosition> { }
export abstract class AbstractGotoLineQuickAccessProvider extends AbstractEditorNavigationQuickAccessProvider {
static PREFIX = ':';
constructor() {
super({ canAcceptInBackground: true });
}
protected provideWithoutTextEditor(picker: IQuickPick<IGotoLineQuickPickItem>): IDisposable {
const label = localize('cannotRunGotoLine', "Open a text editor first to go to a line.");
picker.items = [{ label }];
picker.ariaLabel = label;
return Disposable.None;
}
protected provideWithTextEditor(context: IQuickAccessTextEditorContext, picker: IQuickPick<IGotoLineQuickPickItem>, token: CancellationToken): IDisposable {
const editor = context.editor;
const disposables = new DisposableStore();
// Goto line once picked
disposables.add(picker.onDidAccept(event => {
const [item] = picker.selectedItems;
if (item) {
if (!this.isValidLineNumber(editor, item.lineNumber)) {
return;
}
this.gotoLocation(context, { range: this.toRange(item.lineNumber, item.column), keyMods: picker.keyMods, preserveFocus: event.inBackground });
if (!event.inBackground) {
picker.hide();
}
}
}));
// React to picker changes
const updatePickerAndEditor = () => {
const position = this.parsePosition(editor, picker.value.trim().substr(AbstractGotoLineQuickAccessProvider.PREFIX.length));
const label = this.getPickLabel(editor, position.lineNumber, position.column);
// Picker
picker.items = [{
lineNumber: position.lineNumber,
column: position.column,
label
}];
// ARIA Label
picker.ariaLabel = label;
// Clear decorations for invalid range
if (!this.isValidLineNumber(editor, position.lineNumber)) {
this.clearDecorations(editor);
return;
}
// Reveal
const range = this.toRange(position.lineNumber, position.column);
editor.revealRangeInCenter(range, ScrollType.Smooth);
// Decorate
this.addDecorations(editor, range);
};
updatePickerAndEditor();
disposables.add(picker.onDidChangeValue(() => updatePickerAndEditor()));
// Adjust line number visibility as needed
const codeEditor = getCodeEditor(editor);
if (codeEditor) {
const options = codeEditor.getOptions();
const lineNumbers = options.get(EditorOption.lineNumbers);
if (lineNumbers.renderType === RenderLineNumbersType.Relative) {
codeEditor.updateOptions({ lineNumbers: 'on' });
disposables.add(toDisposable(() => codeEditor.updateOptions({ lineNumbers: 'relative' })));
}
}
return disposables;
}
private toRange(lineNumber = 1, column = 1): IRange {
return {
startLineNumber: lineNumber,
startColumn: column,
endLineNumber: lineNumber,
endColumn: column
};
}
private parsePosition(editor: IEditor, value: string): IPosition {
// Support line-col formats of `line,col`, `line:col`, `line#col`
const numbers = value.split(/,|:|#/).map(part => parseInt(part, 10)).filter(part => !isNaN(part));
const endLine = this.lineCount(editor) + 1;
return {
lineNumber: numbers[0] > 0 ? numbers[0] : endLine + numbers[0],
column: numbers[1]
};
}
private getPickLabel(editor: IEditor, lineNumber: number, column: number | undefined): string {
// Location valid: indicate this as picker label
if (this.isValidLineNumber(editor, lineNumber)) {
if (this.isValidColumn(editor, lineNumber, column)) {
return localize('gotoLineColumnLabel', "Go to line {0} and character {1}.", lineNumber, column);
}
return localize('gotoLineLabel', "Go to line {0}.", lineNumber);
}
// Location invalid: show generic label
const position = editor.getPosition() || { lineNumber: 1, column: 1 };
const lineCount = this.lineCount(editor);
if (lineCount > 1) {
return localize('gotoLineLabelEmptyWithLimit', "Current Line: {0}, Character: {1}. Type a line number between 1 and {2} to navigate to.", position.lineNumber, position.column, lineCount);
}
return localize('gotoLineLabelEmpty', "Current Line: {0}, Character: {1}. Type a line number to navigate to.", position.lineNumber, position.column);
}
private isValidLineNumber(editor: IEditor, lineNumber: number | undefined): boolean {
if (!lineNumber || typeof lineNumber !== 'number') {
return false;
}
return lineNumber > 0 && lineNumber <= this.lineCount(editor);
}
private isValidColumn(editor: IEditor, lineNumber: number, column: number | undefined): boolean {
if (!column || typeof column !== 'number') {
return false;
}
const model = this.getModel(editor);
if (!model) {
return false;
}
const positionCandidate = { lineNumber, column };
return model.validatePosition(positionCandidate).equals(positionCandidate);
}
private lineCount(editor: IEditor): number {
return this.getModel(editor)?.getLineCount() ?? 0;
}
}
| src/vs/editor/contrib/quickAccess/gotoLineQuickAccess.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.00017523771384730935,
0.00017258910520467907,
0.00016978365601971745,
0.00017276096332352608,
0.0000014094582638790598
] |
{
"id": 2,
"code_window": [
"\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test' });\n",
"\t}));\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindowWithError', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+error' });\n",
"\t}));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.currentWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test', reuseWindow: true });\n",
"\t}));\n"
],
"file_path": "extensions/vscode-test-resolver/src/extension.ts",
"type": "add",
"edit_start_line_idx": 265
} | /*---------------------------------------------------------------------------------------------
* 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 cp from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import * as net from 'net';
import * as http from 'http';
import { downloadAndUnzipVSCodeServer } from './download';
import { terminateProcess } from './util/processes';
let extHostProcess: cp.ChildProcess | undefined;
const enum CharCode {
Backspace = 8,
LineFeed = 10
}
let outputChannel: vscode.OutputChannel;
export function activate(context: vscode.ExtensionContext) {
function doResolve(_authority: string, progress: vscode.Progress<{ message?: string; increment?: number }>): Promise<vscode.ResolvedAuthority> {
// eslint-disable-next-line no-async-promise-executor
const serverPromise = new Promise<vscode.ResolvedAuthority>(async (res, rej) => {
progress.report({ message: 'Starting Test Resolver' });
outputChannel = vscode.window.createOutputChannel('TestResolver');
let isResolved = false;
async function processError(message: string) {
outputChannel.appendLine(message);
if (!isResolved) {
isResolved = true;
outputChannel.show();
const result = await vscode.window.showErrorMessage(message, { modal: true }, ...getActions());
if (result) {
await result.execute();
}
rej(vscode.RemoteAuthorityResolverError.NotAvailable(message, true));
}
}
let lastProgressLine = '';
function processOutput(output: string) {
outputChannel.append(output);
for (let i = 0; i < output.length; i++) {
const chr = output.charCodeAt(i);
if (chr === CharCode.LineFeed) {
const match = lastProgressLine.match(/Extension host agent listening on (\d+)/);
if (match) {
isResolved = true;
res(new vscode.ResolvedAuthority('127.0.0.1', parseInt(match[1], 10))); // success!
}
lastProgressLine = '';
} else if (chr === CharCode.Backspace) {
lastProgressLine = lastProgressLine.substr(0, lastProgressLine.length - 1);
} else {
lastProgressLine += output.charAt(i);
}
}
}
const delay = getConfiguration('startupDelay');
if (typeof delay === 'number') {
let remaining = Math.ceil(delay);
outputChannel.append(`Delaying startup by ${remaining} seconds (configured by "testresolver.startupDelay").`);
while (remaining > 0) {
progress.report({ message: `Delayed resolving: Remaining ${remaining}s` });
await (sleep(1000));
remaining--;
}
}
if (getConfiguration('startupError') === true) {
processError('Test Resolver failed for testing purposes (configured by "testresolver.startupError").');
return;
}
const { updateUrl, commit, quality, serverDataFolderName, dataFolderName } = getProductConfiguration();
const commandArgs = ['--port=0', '--disable-telemetry'];
const env = getNewEnv();
const remoteDataDir = process.env['TESTRESOLVER_DATA_FOLDER'] || path.join(os.homedir(), serverDataFolderName || `${dataFolderName}-testresolver`);
const logsDir = process.env['TESTRESOLVER_LOGS_FOLDER'];
if (logsDir) {
commandArgs.push('--logsPath', logsDir);
}
env['VSCODE_AGENT_FOLDER'] = remoteDataDir;
outputChannel.appendLine(`Using data folder at ${remoteDataDir}`);
if (!commit) { // dev mode
const serverCommand = process.platform === 'win32' ? 'server.bat' : 'server.sh';
const vscodePath = path.resolve(path.join(context.extensionPath, '..', '..'));
const serverCommandPath = path.join(vscodePath, 'resources', 'server', 'bin-dev', serverCommand);
extHostProcess = cp.spawn(serverCommandPath, commandArgs, { env, cwd: vscodePath });
} else {
const extensionToInstall = process.env['TESTRESOLVER_INSTALL_BUILTIN_EXTENSION'];
if (extensionToInstall) {
commandArgs.push('--install-builtin-extension', extensionToInstall);
commandArgs.push('--start-server');
}
const serverCommand = process.platform === 'win32' ? 'server.cmd' : 'server.sh';
let serverLocation = env['VSCODE_REMOTE_SERVER_PATH']; // support environment variable to specify location of server on disk
if (!serverLocation) {
const serverBin = path.join(remoteDataDir, 'bin');
progress.report({ message: 'Installing VSCode Server' });
serverLocation = await downloadAndUnzipVSCodeServer(updateUrl, commit, quality, serverBin, m => outputChannel.appendLine(m));
}
outputChannel.appendLine(`Using server build at ${serverLocation}`);
outputChannel.appendLine(`Server arguments ${commandArgs.join(' ')}`);
extHostProcess = cp.spawn(path.join(serverLocation, serverCommand), commandArgs, { env, cwd: serverLocation });
}
extHostProcess.stdout!.on('data', (data: Buffer) => processOutput(data.toString()));
extHostProcess.stderr!.on('data', (data: Buffer) => processOutput(data.toString()));
extHostProcess.on('error', (error: Error) => {
processError(`server failed with error:\n${error.message}`);
extHostProcess = undefined;
});
extHostProcess.on('close', (code: number) => {
processError(`server closed unexpectedly.\nError code: ${code}`);
extHostProcess = undefined;
});
context.subscriptions.push({
dispose: () => {
if (extHostProcess) {
terminateProcess(extHostProcess, context.extensionPath);
}
}
});
});
return serverPromise.then(serverAddr => {
return new Promise<vscode.ResolvedAuthority>((res, _rej) => {
const proxyServer = net.createServer(proxySocket => {
outputChannel.appendLine(`Proxy connection accepted`);
let remoteReady = true, localReady = true;
const remoteSocket = net.createConnection({ port: serverAddr.port });
let isDisconnected = connectionPaused;
connectionPausedEvent.event(_ => {
let newIsDisconnected = connectionPaused;
if (isDisconnected !== newIsDisconnected) {
outputChannel.appendLine(`Connection state: ${newIsDisconnected ? 'open' : 'paused'}`);
isDisconnected = newIsDisconnected;
if (!isDisconnected) {
outputChannel.appendLine(`Resume remote and proxy sockets.`);
if (remoteSocket.isPaused() && localReady) {
remoteSocket.resume();
}
if (proxySocket.isPaused() && remoteReady) {
proxySocket.resume();
}
} else {
outputChannel.appendLine(`Pausing remote and proxy sockets.`);
if (!remoteSocket.isPaused()) {
remoteSocket.pause();
}
if (!proxySocket.isPaused()) {
proxySocket.pause();
}
}
}
});
proxySocket.on('data', (data) => {
remoteReady = remoteSocket.write(data);
if (!remoteReady) {
proxySocket.pause();
}
});
remoteSocket.on('data', (data) => {
localReady = proxySocket.write(data);
if (!localReady) {
remoteSocket.pause();
}
});
proxySocket.on('drain', () => {
localReady = true;
if (!isDisconnected) {
remoteSocket.resume();
}
});
remoteSocket.on('drain', () => {
remoteReady = true;
if (!isDisconnected) {
proxySocket.resume();
}
});
proxySocket.on('close', () => {
outputChannel.appendLine(`Proxy socket closed, closing remote socket.`);
remoteSocket.end();
});
remoteSocket.on('close', () => {
outputChannel.appendLine(`Remote socket closed, closing proxy socket.`);
proxySocket.end();
});
context.subscriptions.push({
dispose: () => {
proxySocket.end();
remoteSocket.end();
}
});
});
proxyServer.listen(0, '127.0.0.1', () => {
const port = (<net.AddressInfo>proxyServer.address()).port;
outputChannel.appendLine(`Going through proxy at port ${port}`);
const r: vscode.ResolverResult = new vscode.ResolvedAuthority('127.0.0.1', port);
res(r);
});
context.subscriptions.push({
dispose: () => {
proxyServer.close();
}
});
});
});
}
let connectionPaused = false;
let connectionPausedEvent = new vscode.EventEmitter<boolean>();
const authorityResolverDisposable = vscode.workspace.registerRemoteAuthorityResolver('test', {
async getCanonicalURI(uri: vscode.Uri): Promise<vscode.Uri> {
return vscode.Uri.file(uri.path);
},
resolve(_authority: string): Thenable<vscode.ResolvedAuthority> {
return vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Open TestResolver Remote ([details](command:vscode-testresolver.showLog))',
cancellable: false
}, (progress) => doResolve(_authority, progress));
},
tunnelFactory,
tunnelFeatures: {
elevation: true,
public: !!vscode.workspace.getConfiguration('testresolver').get('supportPublicPorts'),
privacyOptions: vscode.workspace.getConfiguration('testresolver').get('supportPublicPorts') ? [
{
id: 'public',
label: 'Public',
themeIcon: 'eye'
},
{
id: 'other',
label: 'Other',
themeIcon: 'circuit-board'
},
{
id: 'private',
label: 'Private',
themeIcon: 'eye-closed'
}
] : []
},
showCandidatePort
});
context.subscriptions.push(authorityResolverDisposable);
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindow', () => {
return vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test' });
}));
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindowWithError', () => {
return vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+error' });
}));
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.killServerAndTriggerHandledError', () => {
authorityResolverDisposable.dispose();
if (extHostProcess) {
terminateProcess(extHostProcess, context.extensionPath);
}
vscode.workspace.registerRemoteAuthorityResolver('test', {
async resolve(_authority: string): Promise<vscode.ResolvedAuthority> {
setTimeout(async () => {
await vscode.window.showErrorMessage('Just a custom message.', { modal: true, useCustom: true }, 'OK', 'Great');
}, 2000);
throw vscode.RemoteAuthorityResolverError.NotAvailable('Intentional Error', true);
}
});
}));
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.showLog', () => {
if (outputChannel) {
outputChannel.show();
}
}));
const pauseStatusBarEntry = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
pauseStatusBarEntry.text = 'Remote connection paused. Click to undo';
pauseStatusBarEntry.command = 'vscode-testresolver.toggleConnectionPause';
pauseStatusBarEntry.backgroundColor = new vscode.ThemeColor('statusBarItem.errorBackground');
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.toggleConnectionPause', () => {
if (!connectionPaused) {
connectionPaused = true;
pauseStatusBarEntry.show();
} else {
connectionPaused = false;
pauseStatusBarEntry.hide();
}
connectionPausedEvent.fire(connectionPaused);
}));
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.openTunnel', async () => {
const result = await vscode.window.showInputBox({
prompt: 'Enter the remote port for the tunnel',
value: '5000',
validateInput: input => /^[\d]+$/.test(input) ? undefined : 'Not a valid number'
});
if (result) {
const port = Number.parseInt(result);
vscode.workspace.openTunnel({
remoteAddress: {
host: '127.0.0.1',
port: port
},
localAddressPort: port + 1
});
}
}));
context.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.startRemoteServer', async () => {
const result = await vscode.window.showInputBox({
prompt: 'Enter the port for the remote server',
value: '5000',
validateInput: input => /^[\d]+$/.test(input) ? undefined : 'Not a valid number'
});
if (result) {
runHTTPTestServer(Number.parseInt(result));
}
}));
vscode.commands.executeCommand('setContext', 'forwardedPortsViewEnabled', true);
}
type ActionItem = (vscode.MessageItem & { execute: () => void; });
function getActions(): ActionItem[] {
const actions: ActionItem[] = [];
const isDirty = vscode.workspace.textDocuments.some(d => d.isDirty) || vscode.workspace.workspaceFile && vscode.workspace.workspaceFile.scheme === 'untitled';
actions.push({
title: 'Retry',
execute: async () => {
await vscode.commands.executeCommand('workbench.action.reloadWindow');
}
});
if (!isDirty) {
actions.push({
title: 'Close Remote',
execute: async () => {
await vscode.commands.executeCommand('vscode.newWindow', { reuseWindow: true, remoteAuthority: null });
}
});
}
actions.push({
title: 'Ignore',
isCloseAffordance: true,
execute: async () => {
vscode.commands.executeCommand('vscode-testresolver.showLog'); // no need to wait
}
});
return actions;
}
export interface IProductConfiguration {
updateUrl: string;
commit: string;
quality: string;
dataFolderName: string;
serverDataFolderName?: string;
}
function getProductConfiguration(): IProductConfiguration {
const content = fs.readFileSync(path.join(vscode.env.appRoot, 'product.json')).toString();
return JSON.parse(content) as IProductConfiguration;
}
function getNewEnv(): { [x: string]: string | undefined } {
const env = { ...process.env };
delete env['ELECTRON_RUN_AS_NODE'];
return env;
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
function getConfiguration<T>(id: string): T | undefined {
return vscode.workspace.getConfiguration('testresolver').get<T>(id);
}
const remoteServers: number[] = [];
async function showCandidatePort(_host: string, port: number, _detail: string): Promise<boolean> {
return remoteServers.includes(port) || port === 100;
}
async function tunnelFactory(tunnelOptions: vscode.TunnelOptions, tunnelCreationOptions: vscode.TunnelCreationOptions): Promise<vscode.Tunnel> {
outputChannel.appendLine(`Tunnel factory request: Remote ${tunnelOptions.remoteAddress.port} -> local ${tunnelOptions.localAddressPort}`);
if (tunnelCreationOptions.elevationRequired) {
await vscode.window.showInformationMessage('This is a fake elevation message. A real resolver would show a native elevation prompt.', { modal: true }, 'Ok');
}
return createTunnelService();
function newTunnel(localAddress: { host: string, port: number }): vscode.Tunnel {
const onDidDispose: vscode.EventEmitter<void> = new vscode.EventEmitter();
let isDisposed = false;
return {
localAddress,
remoteAddress: tunnelOptions.remoteAddress,
public: !!vscode.workspace.getConfiguration('testresolver').get('supportPublicPorts') && tunnelOptions.public,
privacy: tunnelOptions.privacy,
protocol: tunnelOptions.protocol,
onDidDispose: onDidDispose.event,
dispose: () => {
if (!isDisposed) {
isDisposed = true;
onDidDispose.fire();
}
}
};
}
function createTunnelService(): Promise<vscode.Tunnel> {
return new Promise<vscode.Tunnel>((res, _rej) => {
const proxyServer = net.createServer(proxySocket => {
const remoteSocket = net.createConnection({ host: tunnelOptions.remoteAddress.host, port: tunnelOptions.remoteAddress.port });
remoteSocket.pipe(proxySocket);
proxySocket.pipe(remoteSocket);
});
let localPort = 0;
if (tunnelOptions.localAddressPort) {
// When the tunnelOptions include a localAddressPort, we should use that.
// However, the test resolver all runs on one machine, so if the localAddressPort is the same as the remote port,
// then we must use a different port number.
localPort = tunnelOptions.localAddressPort;
} else {
localPort = tunnelOptions.remoteAddress.port;
}
if (localPort === tunnelOptions.remoteAddress.port) {
localPort += 1;
}
// The test resolver can't actually handle privileged ports, it only pretends to.
if (localPort < 1024 && process.platform !== 'win32') {
localPort = 0;
}
proxyServer.listen(localPort, '127.0.0.1', () => {
const localPort = (<net.AddressInfo>proxyServer.address()).port;
outputChannel.appendLine(`New test resolver tunnel service: Remote ${tunnelOptions.remoteAddress.port} -> local ${localPort}`);
const tunnel = newTunnel({ host: '127.0.0.1', port: localPort });
tunnel.onDidDispose(() => proxyServer.close());
res(tunnel);
});
});
}
}
function runHTTPTestServer(port: number): vscode.Disposable {
const server = http.createServer((_req, res) => {
res.writeHead(200);
res.end(`Hello, World from test server running on port ${port}!`);
});
remoteServers.push(port);
server.listen(port, '127.0.0.1');
const message = `Opened HTTP server on http://127.0.0.1:${port}`;
console.log(message);
outputChannel.appendLine(message);
return {
dispose: () => {
server.close();
const index = remoteServers.indexOf(port);
if (index !== -1) {
remoteServers.splice(index, 1);
}
}
};
}
| extensions/vscode-test-resolver/src/extension.ts | 1 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.7551162242889404,
0.015956595540046692,
0.00016088540724013,
0.0001883301738416776,
0.10669251531362534
] |
{
"id": 2,
"code_window": [
"\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test' });\n",
"\t}));\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindowWithError', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+error' });\n",
"\t}));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.currentWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test', reuseWindow: true });\n",
"\t}));\n"
],
"file_path": "extensions/vscode-test-resolver/src/extension.ts",
"type": "add",
"edit_start_line_idx": 265
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import { tmpdir } from 'os';
import { promisify } from 'util';
import { ResourceQueue } from 'vs/base/common/async';
import { isEqualOrParent, isRootOrDriveLetter } from 'vs/base/common/extpath';
import { normalizeNFC } from 'vs/base/common/normalization';
import { join } from 'vs/base/common/path';
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
import { extUriBiasedIgnorePathCase } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
//#region rimraf
export enum RimRafMode {
/**
* Slow version that unlinks each file and folder.
*/
UNLINK,
/**
* Fast version that first moves the file/folder
* into a temp directory and then deletes that
* without waiting for it.
*/
MOVE
}
/**
* Allows to delete the provided path (either file or folder) recursively
* with the options:
* - `UNLINK`: direct removal from disk
* - `MOVE`: faster variant that first moves the target to temp dir and then
* deletes it in the background without waiting for that to finish.
*/
async function rimraf(path: string, mode = RimRafMode.UNLINK): Promise<void> {
if (isRootOrDriveLetter(path)) {
throw new Error('rimraf - will refuse to recursively delete root');
}
// delete: via rmDir
if (mode === RimRafMode.UNLINK) {
return rimrafUnlink(path);
}
// delete: via move
return rimrafMove(path);
}
async function rimrafMove(path: string): Promise<void> {
try {
const pathInTemp = join(tmpdir(), generateUuid());
try {
await Promises.rename(path, pathInTemp);
} catch (error) {
return rimrafUnlink(path); // if rename fails, delete without tmp dir
}
// Delete but do not return as promise
rimrafUnlink(pathInTemp).catch(error => {/* ignore */ });
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
}
async function rimrafUnlink(path: string): Promise<void> {
return Promises.rmdir(path, { recursive: true, maxRetries: 3 });
}
export function rimrafSync(path: string): void {
if (isRootOrDriveLetter(path)) {
throw new Error('rimraf - will refuse to recursively delete root');
}
fs.rmdirSync(path, { recursive: true });
}
//#endregion
//#region readdir with NFC support (macos)
export interface IDirent {
name: string;
isFile(): boolean;
isDirectory(): boolean;
isSymbolicLink(): boolean;
}
/**
* Drop-in replacement of `fs.readdir` with support
* for converting from macOS NFD unicon form to NFC
* (https://github.com/nodejs/node/issues/2165)
*/
async function readdir(path: string): Promise<string[]>;
async function readdir(path: string, options: { withFileTypes: true }): Promise<IDirent[]>;
async function readdir(path: string, options?: { withFileTypes: true }): Promise<(string | IDirent)[]> {
return handleDirectoryChildren(await (options ? safeReaddirWithFileTypes(path) : promisify(fs.readdir)(path)));
}
async function safeReaddirWithFileTypes(path: string): Promise<IDirent[]> {
try {
return await promisify(fs.readdir)(path, { withFileTypes: true });
} catch (error) {
console.warn('[node.js fs] readdir with filetypes failed with error: ', error);
}
// Fallback to manually reading and resolving each
// children of the folder in case we hit an error
// previously.
// This can only really happen on exotic file systems
// such as explained in #115645 where we get entries
// from `readdir` that we can later not `lstat`.
const result: IDirent[] = [];
const children = await readdir(path);
for (const child of children) {
let isFile = false;
let isDirectory = false;
let isSymbolicLink = false;
try {
const lstat = await Promises.lstat(join(path, child));
isFile = lstat.isFile();
isDirectory = lstat.isDirectory();
isSymbolicLink = lstat.isSymbolicLink();
} catch (error) {
console.warn('[node.js fs] unexpected error from lstat after readdir: ', error);
}
result.push({
name: child,
isFile: () => isFile,
isDirectory: () => isDirectory,
isSymbolicLink: () => isSymbolicLink
});
}
return result;
}
/**
* Drop-in replacement of `fs.readdirSync` with support
* for converting from macOS NFD unicon form to NFC
* (https://github.com/nodejs/node/issues/2165)
*/
export function readdirSync(path: string): string[] {
return handleDirectoryChildren(fs.readdirSync(path));
}
function handleDirectoryChildren(children: string[]): string[];
function handleDirectoryChildren(children: IDirent[]): IDirent[];
function handleDirectoryChildren(children: (string | IDirent)[]): (string | IDirent)[];
function handleDirectoryChildren(children: (string | IDirent)[]): (string | IDirent)[] {
return children.map(child => {
// Mac: uses NFD unicode form on disk, but we want NFC
// See also https://github.com/nodejs/node/issues/2165
if (typeof child === 'string') {
return isMacintosh ? normalizeNFC(child) : child;
}
child.name = isMacintosh ? normalizeNFC(child.name) : child.name;
return child;
});
}
/**
* A convenience method to read all children of a path that
* are directories.
*/
async function readDirsInDir(dirPath: string): Promise<string[]> {
const children = await readdir(dirPath);
const directories: string[] = [];
for (const child of children) {
if (await SymlinkSupport.existsDirectory(join(dirPath, child))) {
directories.push(child);
}
}
return directories;
}
//#endregion
//#region whenDeleted()
/**
* A `Promise` that resolves when the provided `path`
* is deleted from disk.
*/
export function whenDeleted(path: string, intervalMs = 1000): Promise<void> {
return new Promise<void>(resolve => {
let running = false;
const interval = setInterval(() => {
if (!running) {
running = true;
fs.access(path, err => {
running = false;
if (err) {
clearInterval(interval);
resolve(undefined);
}
});
}
}, intervalMs);
});
}
//#endregion
//#region Methods with symbolic links support
export namespace SymlinkSupport {
export interface IStats {
// The stats of the file. If the file is a symbolic
// link, the stats will be of that target file and
// not the link itself.
// If the file is a symbolic link pointing to a non
// existing file, the stat will be of the link and
// the `dangling` flag will indicate this.
stat: fs.Stats;
// Will be provided if the resource is a symbolic link
// on disk. Use the `dangling` flag to find out if it
// points to a resource that does not exist on disk.
symbolicLink?: { dangling: boolean };
}
/**
* Resolves the `fs.Stats` of the provided path. If the path is a
* symbolic link, the `fs.Stats` will be from the target it points
* to. If the target does not exist, `dangling: true` will be returned
* as `symbolicLink` value.
*/
export async function stat(path: string): Promise<IStats> {
// First stat the link
let lstats: fs.Stats | undefined;
try {
lstats = await Promises.lstat(path);
// Return early if the stat is not a symbolic link at all
if (!lstats.isSymbolicLink()) {
return { stat: lstats };
}
} catch (error) {
/* ignore - use stat() instead */
}
// If the stat is a symbolic link or failed to stat, use fs.stat()
// which for symbolic links will stat the target they point to
try {
const stats = await Promises.stat(path);
return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : undefined };
} catch (error) {
// If the link points to a nonexistent file we still want
// to return it as result while setting dangling: true flag
if (error.code === 'ENOENT' && lstats) {
return { stat: lstats, symbolicLink: { dangling: true } };
}
// Windows: workaround a node.js bug where reparse points
// are not supported (https://github.com/nodejs/node/issues/36790)
if (isWindows && error.code === 'EACCES') {
try {
const stats = await Promises.stat(await Promises.readlink(path));
return { stat: stats, symbolicLink: { dangling: false } };
} catch (error) {
// If the link points to a nonexistent file we still want
// to return it as result while setting dangling: true flag
if (error.code === 'ENOENT' && lstats) {
return { stat: lstats, symbolicLink: { dangling: true } };
}
throw error;
}
}
throw error;
}
}
/**
* Figures out if the `path` exists and is a file with support
* for symlinks.
*
* Note: this will return `false` for a symlink that exists on
* disk but is dangling (pointing to a nonexistent path).
*
* Use `exists` if you only care about the path existing on disk
* or not without support for symbolic links.
*/
export async function existsFile(path: string): Promise<boolean> {
try {
const { stat, symbolicLink } = await SymlinkSupport.stat(path);
return stat.isFile() && symbolicLink?.dangling !== true;
} catch (error) {
// Ignore, path might not exist
}
return false;
}
/**
* Figures out if the `path` exists and is a directory with support for
* symlinks.
*
* Note: this will return `false` for a symlink that exists on
* disk but is dangling (pointing to a nonexistent path).
*
* Use `exists` if you only care about the path existing on disk
* or not without support for symbolic links.
*/
export async function existsDirectory(path: string): Promise<boolean> {
try {
const { stat, symbolicLink } = await SymlinkSupport.stat(path);
return stat.isDirectory() && symbolicLink?.dangling !== true;
} catch (error) {
// Ignore, path might not exist
}
return false;
}
}
//#endregion
//#region Write File
// According to node.js docs (https://nodejs.org/docs/v6.5.0/api/fs.html#fs_fs_writefile_file_data_options_callback)
// it is not safe to call writeFile() on the same path multiple times without waiting for the callback to return.
// Therefor we use a Queue on the path that is given to us to sequentialize calls to the same path properly.
const writeQueues = new ResourceQueue();
/**
* Same as `fs.writeFile` but with an additional call to
* `fs.fdatasync` after writing to ensure changes are
* flushed to disk.
*
* In addition, multiple writes to the same path are queued.
*/
function writeFile(path: string, data: string, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: Buffer, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: Uint8Array, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: string | Buffer | Uint8Array, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: string | Buffer | Uint8Array, options?: IWriteFileOptions): Promise<void> {
return writeQueues.queueFor(URI.file(path), extUriBiasedIgnorePathCase).queue(() => {
const ensuredOptions = ensureWriteOptions(options);
return new Promise((resolve, reject) => doWriteFileAndFlush(path, data, ensuredOptions, error => error ? reject(error) : resolve()));
});
}
interface IWriteFileOptions {
mode?: number;
flag?: string;
}
interface IEnsuredWriteFileOptions extends IWriteFileOptions {
mode: number;
flag: string;
}
let canFlush = true;
// Calls fs.writeFile() followed by a fs.sync() call to flush the changes to disk
// We do this in cases where we want to make sure the data is really on disk and
// not in some cache.
//
// See https://github.com/nodejs/node/blob/v5.10.0/lib/fs.js#L1194
function doWriteFileAndFlush(path: string, data: string | Buffer | Uint8Array, options: IEnsuredWriteFileOptions, callback: (error: Error | null) => void): void {
if (!canFlush) {
return fs.writeFile(path, data, { mode: options.mode, flag: options.flag }, callback);
}
// Open the file with same flags and mode as fs.writeFile()
fs.open(path, options.flag, options.mode, (openError, fd) => {
if (openError) {
return callback(openError);
}
// It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
fs.writeFile(fd, data, writeError => {
if (writeError) {
return fs.close(fd, () => callback(writeError)); // still need to close the handle on error!
}
// Flush contents (not metadata) of the file to disk
// https://github.com/microsoft/vscode/issues/9589
fs.fdatasync(fd, (syncError: Error | null) => {
// In some exotic setups it is well possible that node fails to sync
// In that case we disable flushing and warn to the console
if (syncError) {
console.warn('[node.js fs] fdatasync is now disabled for this session because it failed: ', syncError);
canFlush = false;
}
return fs.close(fd, closeError => callback(closeError));
});
});
});
}
/**
* Same as `fs.writeFileSync` but with an additional call to
* `fs.fdatasyncSync` after writing to ensure changes are
* flushed to disk.
*/
export function writeFileSync(path: string, data: string | Buffer, options?: IWriteFileOptions): void {
const ensuredOptions = ensureWriteOptions(options);
if (!canFlush) {
return fs.writeFileSync(path, data, { mode: ensuredOptions.mode, flag: ensuredOptions.flag });
}
// Open the file with same flags and mode as fs.writeFile()
const fd = fs.openSync(path, ensuredOptions.flag, ensuredOptions.mode);
try {
// It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
fs.writeFileSync(fd, data);
// Flush contents (not metadata) of the file to disk
try {
fs.fdatasyncSync(fd); // https://github.com/microsoft/vscode/issues/9589
} catch (syncError) {
console.warn('[node.js fs] fdatasyncSync is now disabled for this session because it failed: ', syncError);
canFlush = false;
}
} finally {
fs.closeSync(fd);
}
}
function ensureWriteOptions(options?: IWriteFileOptions): IEnsuredWriteFileOptions {
if (!options) {
return { mode: 0o666 /* default node.js mode for files */, flag: 'w' };
}
return {
mode: typeof options.mode === 'number' ? options.mode : 0o666 /* default node.js mode for files */,
flag: typeof options.flag === 'string' ? options.flag : 'w'
};
}
//#endregion
//#region Move / Copy
/**
* A drop-in replacement for `fs.rename` that:
* - updates the `mtime` of the `source` after the operation
* - allows to move across multiple disks
*/
async function move(source: string, target: string): Promise<void> {
if (source === target) {
return; // simulate node.js behaviour here and do a no-op if paths match
}
// We have been updating `mtime` for move operations for files since the
// beginning for reasons that are no longer quite clear, but changing
// this could be risky as well. As such, trying to reason about it:
// It is very common as developer to have file watchers enabled that watch
// the current workspace for changes. Updating the `mtime` might make it
// easier for these watchers to recognize an actual change. Since changing
// a source code file also updates the `mtime`, moving a file should do so
// as well because conceptually it is a change of a similar category.
async function updateMtime(path: string): Promise<void> {
try {
const stat = await Promises.lstat(path);
if (stat.isDirectory() || stat.isSymbolicLink()) {
return; // only for files
}
await Promises.utimes(path, stat.atime, new Date());
} catch (error) {
// Ignore any error
}
}
try {
await Promises.rename(source, target);
await updateMtime(target);
} catch (error) {
// In two cases we fallback to classic copy and delete:
//
// 1.) The EXDEV error indicates that source and target are on different devices
// In this case, fallback to using a copy() operation as there is no way to
// rename() between different devices.
//
// 2.) The user tries to rename a file/folder that ends with a dot. This is not
// really possible to move then, at least on UNC devices.
if (source.toLowerCase() !== target.toLowerCase() && error.code === 'EXDEV' || source.endsWith('.')) {
await copy(source, target, { preserveSymlinks: false /* copying to another device */ });
await rimraf(source, RimRafMode.MOVE);
await updateMtime(target);
} else {
throw error;
}
}
}
interface ICopyPayload {
readonly root: { source: string, target: string };
readonly options: { preserveSymlinks: boolean };
readonly handledSourcePaths: Set<string>;
}
/**
* Recursively copies all of `source` to `target`.
*
* The options `preserveSymlinks` configures how symbolic
* links should be handled when encountered. Set to
* `false` to not preserve them and `true` otherwise.
*/
async function copy(source: string, target: string, options: { preserveSymlinks: boolean }): Promise<void> {
return doCopy(source, target, { root: { source, target }, options, handledSourcePaths: new Set<string>() });
}
// When copying a file or folder, we want to preserve the mode
// it had and as such provide it when creating. However, modes
// can go beyond what we expect (see link below), so we mask it.
// (https://github.com/nodejs/node-v0.x-archive/issues/3045#issuecomment-4862588)
const COPY_MODE_MASK = 0o777;
async function doCopy(source: string, target: string, payload: ICopyPayload): Promise<void> {
// Keep track of paths already copied to prevent
// cycles from symbolic links to cause issues
if (payload.handledSourcePaths.has(source)) {
return;
} else {
payload.handledSourcePaths.add(source);
}
const { stat, symbolicLink } = await SymlinkSupport.stat(source);
// Symlink
if (symbolicLink) {
// Try to re-create the symlink unless `preserveSymlinks: false`
if (payload.options.preserveSymlinks) {
try {
return await doCopySymlink(source, target, payload);
} catch (error) {
// in any case of an error fallback to normal copy via dereferencing
console.warn('[node.js fs] copy of symlink failed: ', error);
}
}
if (symbolicLink.dangling) {
return; // skip dangling symbolic links from here on (https://github.com/microsoft/vscode/issues/111621)
}
}
// Folder
if (stat.isDirectory()) {
return doCopyDirectory(source, target, stat.mode & COPY_MODE_MASK, payload);
}
// File or file-like
else {
return doCopyFile(source, target, stat.mode & COPY_MODE_MASK);
}
}
async function doCopyDirectory(source: string, target: string, mode: number, payload: ICopyPayload): Promise<void> {
// Create folder
await Promises.mkdir(target, { recursive: true, mode });
// Copy each file recursively
const files = await readdir(source);
for (const file of files) {
await doCopy(join(source, file), join(target, file), payload);
}
}
async function doCopyFile(source: string, target: string, mode: number): Promise<void> {
// Copy file
await Promises.copyFile(source, target);
// restore mode (https://github.com/nodejs/node/issues/1104)
await Promises.chmod(target, mode);
}
async function doCopySymlink(source: string, target: string, payload: ICopyPayload): Promise<void> {
// Figure out link target
let linkTarget = await Promises.readlink(source);
// Special case: the symlink points to a target that is
// actually within the path that is being copied. In that
// case we want the symlink to point to the target and
// not the source
if (isEqualOrParent(linkTarget, payload.root.source, !isLinux)) {
linkTarget = join(payload.root.target, linkTarget.substr(payload.root.source.length + 1));
}
// Create symlink
await Promises.symlink(linkTarget, target);
}
//#endregion
//#region Promise based fs methods
/**
* Prefer this helper class over the `fs.promises` API to
* enable `graceful-fs` to function properly. Given issue
* https://github.com/isaacs/node-graceful-fs/issues/160 it
* is evident that the module only takes care of the non-promise
* based fs methods.
*
* Another reason is `realpath` being entirely different in
* the promise based implementation compared to the other
* one (https://github.com/microsoft/vscode/issues/118562)
*
* Note: using getters for a reason, since `graceful-fs`
* patching might kick in later after modules have been
* loaded we need to defer access to fs methods.
* (https://github.com/microsoft/vscode/issues/124176)
*/
export const Promises = new class {
//#region Implemented by node.js
get access() { return promisify(fs.access); }
get stat() { return promisify(fs.stat); }
get lstat() { return promisify(fs.lstat); }
get utimes() { return promisify(fs.utimes); }
get read() { return promisify(fs.read); }
get readFile() { return promisify(fs.readFile); }
get write() { return promisify(fs.write); }
get appendFile() { return promisify(fs.appendFile); }
get fdatasync() { return promisify(fs.fdatasync); }
get truncate() { return promisify(fs.truncate); }
get rename() { return promisify(fs.rename); }
get copyFile() { return promisify(fs.copyFile); }
get open() { return promisify(fs.open); }
get close() { return promisify(fs.close); }
get symlink() { return promisify(fs.symlink); }
get readlink() { return promisify(fs.readlink); }
get chmod() { return promisify(fs.chmod); }
get mkdir() { return promisify(fs.mkdir); }
get unlink() { return promisify(fs.unlink); }
get rmdir() { return promisify(fs.rmdir); }
get realpath() { return promisify(fs.realpath); }
//#endregion
//#region Implemented by us
async exists(path: string): Promise<boolean> {
try {
await Promises.access(path);
return true;
} catch {
return false;
}
}
get readdir() { return readdir; }
get readDirsInDir() { return readDirsInDir; }
get writeFile() { return writeFile; }
get rm() { return rimraf; }
get move() { return move; }
get copy() { return copy; }
//#endregion
};
//#endregion
| src/vs/base/node/pfs.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.0001869897823780775,
0.0001708170457277447,
0.00016080334899015725,
0.00017233181279152632,
0.000004672158866014797
] |
{
"id": 2,
"code_window": [
"\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test' });\n",
"\t}));\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindowWithError', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+error' });\n",
"\t}));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.currentWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test', reuseWindow: true });\n",
"\t}));\n"
],
"file_path": "extensions/vscode-test-resolver/src/extension.ts",
"type": "add",
"edit_start_line_idx": 265
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { timeout } from 'vs/base/common/async';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { Emitter } from 'vs/base/common/event';
import { Disposable, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
/**
* A helper class to track requests that have replies. Using this it's easy to implement an event
* that accepts a reply.
*/
export class RequestStore<T, RequestArgs> extends Disposable {
private _lastRequestId = 0;
private readonly _timeout: number;
private _pendingRequests: Map<number, (resolved: T) => void> = new Map();
private _pendingRequestDisposables: Map<number, IDisposable[]> = new Map();
private readonly _onCreateRequest = this._register(new Emitter<RequestArgs & { requestId: number }>());
readonly onCreateRequest = this._onCreateRequest.event;
/**
* @param timeout How long in ms to allow requests to go unanswered for, undefined will use the
* default (15 seconds).
*/
constructor(
timeout: number | undefined,
@ILogService private readonly _logService: ILogService
) {
super();
this._timeout = timeout === undefined ? 15000 : timeout;
}
/**
* Creates a request.
* @param args The arguments to pass to the onCreateRequest event.
*/
createRequest(args: RequestArgs): Promise<T> {
return new Promise<T>((resolve, reject) => {
const requestId = ++this._lastRequestId;
this._pendingRequests.set(requestId, resolve);
this._onCreateRequest.fire({ requestId, ...args });
const tokenSource = new CancellationTokenSource();
timeout(this._timeout, tokenSource.token).then(() => reject(`Request ${requestId} timed out (${this._timeout}ms)`));
this._pendingRequestDisposables.set(requestId, [toDisposable(() => tokenSource.cancel())]);
});
}
/**
* Accept a reply to a request.
* @param requestId The request ID originating from the onCreateRequest event.
* @param data The reply data.
*/
acceptReply(requestId: number, data: T) {
const resolveRequest = this._pendingRequests.get(requestId);
if (resolveRequest) {
this._pendingRequests.delete(requestId);
dispose(this._pendingRequestDisposables.get(requestId) || []);
this._pendingRequestDisposables.delete(requestId);
resolveRequest(data);
} else {
this._logService.warn(`RequestStore#acceptReply was called without receiving a matching request ${requestId}`);
}
}
}
| src/vs/platform/terminal/common/requestStore.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.00017452203610446304,
0.00016827578656375408,
0.00016190879978239536,
0.0001687988406047225,
0.0000037307079310267
] |
{
"id": 2,
"code_window": [
"\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test' });\n",
"\t}));\n",
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.newWindowWithError', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+error' });\n",
"\t}));\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcontext.subscriptions.push(vscode.commands.registerCommand('vscode-testresolver.currentWindow', () => {\n",
"\t\treturn vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test', reuseWindow: true });\n",
"\t}));\n"
],
"file_path": "extensions/vscode-test-resolver/src/extension.ts",
"type": "add",
"edit_start_line_idx": 265
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as _fs from 'fs';
import * as _url from 'url';
import * as _cp from 'child_process';
import * as _http from 'http';
import * as _os from 'os';
import { cwd } from 'vs/base/common/process';
import { dirname, extname, resolve, join } from 'vs/base/common/path';
import { parseArgs, buildHelpMessage, buildVersionMessage, OPTIONS, OptionDescriptions, ErrorReporter } from 'vs/platform/environment/node/argv';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { createWaitMarkerFile } from 'vs/platform/environment/node/wait';
import { PipeCommand } from 'vs/workbench/api/node/extHostCLIServer';
import { hasStdinWithoutTty, getStdinFilePath, readFromStdin } from 'vs/platform/environment/node/stdin';
/*
* Implements a standalone CLI app that opens VS Code from a remote terminal.
* - In integrated terminals for remote windows this connects to the remote server though a pipe.
* The pipe is passed in env VSCODE_IPC_HOOK_CLI.
* - In external terminals for WSL this calls VS Code on the Windows side.
* The VS Code desktop executable path is passed in env VSCODE_CLIENT_COMMAND.
*/
interface ProductDescription {
productName: string;
version: string;
commit: string;
executableName: string;
}
interface RemoteParsedArgs extends NativeParsedArgs { 'gitCredential'?: string; 'openExternal'?: boolean; }
const isSupportedForCmd = (optionId: keyof RemoteParsedArgs) => {
switch (optionId) {
case 'user-data-dir':
case 'extensions-dir':
case 'export-default-configuration':
case 'install-source':
case 'driver':
case 'extensions-download-dir':
case 'builtin-extensions-dir':
case 'telemetry':
return false;
default:
return true;
}
};
const isSupportedForPipe = (optionId: keyof RemoteParsedArgs) => {
switch (optionId) {
case 'version':
case 'help':
case 'folder-uri':
case 'file-uri':
case 'add':
case 'diff':
case 'wait':
case 'goto':
case 'reuse-window':
case 'new-window':
case 'status':
case 'install-extension':
case 'uninstall-extension':
case 'list-extensions':
case 'force':
case 'show-versions':
case 'category':
case 'verbose':
case 'remote':
return true;
default:
return false;
}
};
const cliPipe = process.env['VSCODE_IPC_HOOK_CLI'] as string;
const cliCommand = process.env['VSCODE_CLIENT_COMMAND'] as string;
const cliCommandCwd = process.env['VSCODE_CLIENT_COMMAND_CWD'] as string;
const cliRemoteAuthority = process.env['VSCODE_CLI_AUTHORITY'] as string;
const cliStdInFilePath = process.env['VSCODE_STDIN_FILE_PATH'] as string;
export function main(desc: ProductDescription, args: string[]): void {
if (!cliPipe && !cliCommand) {
console.log('Command is only available in WSL or inside a Visual Studio Code terminal.');
return;
}
// take the local options and remove the ones that don't apply
const options: OptionDescriptions<RemoteParsedArgs> = { ...OPTIONS };
const isSupported = cliCommand ? isSupportedForCmd : isSupportedForPipe;
for (const optionId in OPTIONS) {
const optId = <keyof RemoteParsedArgs>optionId;
if (!isSupported(optId)) {
delete options[optId];
}
}
if (cliPipe) {
options['openExternal'] = { type: 'boolean' };
}
const errorReporter : ErrorReporter = {
onMultipleValues: (id: string, usedValue: string) => {
console.error(`Option ${id} can only be defined once. Using value ${usedValue}.`);
},
onUnknownOption: (id: string) => {
console.error(`Ignoring option ${id}: not supported for ${desc.executableName}.`);
},
onDeprecatedOption: (deprecatedOption: string, actualOption: string) => {
console.warn(`Option '${deprecatedOption}' is deprecated, please use '${actualOption}' instead`);
}
};
const parsedArgs = parseArgs(args, options, errorReporter);
const mapFileUri = cliRemoteAuthority ? mapFileToRemoteUri : (uri: string) => uri;
const verbose = !!parsedArgs['verbose'];
if (parsedArgs.help) {
console.log(buildHelpMessage(desc.productName, desc.executableName, desc.version, options));
return;
}
if (parsedArgs.version) {
console.log(buildVersionMessage(desc.version, desc.commit));
return;
}
if (cliPipe) {
if (parsedArgs['openExternal']) {
openInBrowser(parsedArgs['_'], verbose);
return;
}
}
let remote: string | null | undefined = parsedArgs.remote;
if (remote === 'local' || remote === 'false' || remote === '') {
remote = null; // null represent a local window
}
const folderURIs = (parsedArgs['folder-uri'] || []).map(mapFileUri);
parsedArgs['folder-uri'] = folderURIs;
const fileURIs = (parsedArgs['file-uri'] || []).map(mapFileUri);
parsedArgs['file-uri'] = fileURIs;
const inputPaths = parsedArgs['_'];
let hasReadStdinArg = false;
for (let input of inputPaths) {
if (input === '-') {
hasReadStdinArg = true;
} else {
translatePath(input, mapFileUri, folderURIs, fileURIs);
}
}
parsedArgs['_'] = [];
if (hasReadStdinArg && fileURIs.length === 0 && folderURIs.length === 0 && hasStdinWithoutTty()) {
try {
let stdinFilePath = cliStdInFilePath;
if (!stdinFilePath) {
stdinFilePath = getStdinFilePath();
readFromStdin(stdinFilePath, verbose); // throws error if file can not be written
}
// Make sure to open tmp file
translatePath(stdinFilePath, mapFileUri, folderURIs, fileURIs);
// Enable --wait to get all data and ignore adding this to history
parsedArgs.wait = true;
parsedArgs['skip-add-to-recently-opened'] = true;
console.log(`Reading from stdin via: ${stdinFilePath}`);
} catch (e) {
console.log(`Failed to create file to read via stdin: ${e.toString()}`);
}
}
if (parsedArgs.extensionDevelopmentPath) {
parsedArgs.extensionDevelopmentPath = parsedArgs.extensionDevelopmentPath.map(p => mapFileUri(pathToURI(p).href));
}
if (parsedArgs.extensionTestsPath) {
parsedArgs.extensionTestsPath = mapFileUri(pathToURI(parsedArgs['extensionTestsPath']).href);
}
const crashReporterDirectory = parsedArgs['crash-reporter-directory'];
if (crashReporterDirectory !== undefined && !crashReporterDirectory.match(/^([a-zA-Z]:[\\\/])/)) {
console.log(`The crash reporter directory '${crashReporterDirectory}' must be an absolute Windows path (e.g. c:/crashes)`);
return;
}
if (cliCommand) {
if (parsedArgs['install-extension'] !== undefined || parsedArgs['uninstall-extension'] !== undefined || parsedArgs['list-extensions']) {
const cmdLine: string[] = [];
parsedArgs['install-extension']?.forEach(id => cmdLine.push('--install-extension', id));
parsedArgs['uninstall-extension']?.forEach(id => cmdLine.push('--uninstall-extension', id));
['list-extensions', 'force', 'show-versions', 'category'].forEach(opt => {
const value = parsedArgs[<keyof NativeParsedArgs>opt];
if (value !== undefined) {
cmdLine.push(`--${opt}=${value}`);
}
});
const cp = _cp.fork(join(__dirname, 'main.js'), cmdLine, { stdio: 'inherit' });
cp.on('error', err => console.log(err));
return;
}
let newCommandline: string[] = [];
for (let key in parsedArgs) {
let val = parsedArgs[key as keyof typeof parsedArgs];
if (typeof val === 'boolean') {
if (val) {
newCommandline.push('--' + key);
}
} else if (Array.isArray(val)) {
for (let entry of val) {
newCommandline.push(`--${key}=${entry.toString()}`);
}
} else if (val) {
newCommandline.push(`--${key}=${val.toString()}`);
}
}
if (remote !== null) {
newCommandline.push(`--remote=${remote || cliRemoteAuthority}`);
}
const ext = extname(cliCommand);
if (ext === '.bat' || ext === '.cmd') {
const processCwd = cliCommandCwd || cwd();
if (verbose) {
console.log(`Invoking: cmd.exe /C ${cliCommand} ${newCommandline.join(' ')} in ${processCwd}`);
}
_cp.spawn('cmd.exe', ['/C', cliCommand, ...newCommandline], {
stdio: 'inherit',
cwd: processCwd
});
} else {
const cliCwd = dirname(cliCommand);
const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1' };
newCommandline.unshift('--ms-enable-electron-run-as-node');
newCommandline.unshift('resources/app/out/cli.js');
if (verbose) {
console.log(`Invoking: cd "${cliCwd}" && ELECTRON_RUN_AS_NODE=1 "${cliCommand}" "${newCommandline.join('" "')}"`);
}
_cp.spawn(cliCommand, newCommandline, { cwd: cliCwd, env, stdio: ['inherit'] });
}
} else {
if (parsedArgs.status) {
sendToPipe({
type: 'status'
}, verbose).then((res: string) => {
console.log(res);
});
return;
}
if (parsedArgs['install-extension'] !== undefined || parsedArgs['uninstall-extension'] !== undefined || parsedArgs['list-extensions']) {
sendToPipe({
type: 'extensionManagement',
list: parsedArgs['list-extensions'] ? { showVersions: parsedArgs['show-versions'], category: parsedArgs['category'] } : undefined,
install: asExtensionIdOrVSIX(parsedArgs['install-extension']),
uninstall: asExtensionIdOrVSIX(parsedArgs['uninstall-extension']),
force: parsedArgs['force']
}, verbose).then((res: string) => {
console.log(res);
});
return;
}
let waitMarkerFilePath: string | undefined = undefined;
if (parsedArgs['wait']) {
if (!fileURIs.length) {
console.log('At least one file must be provided to wait for.');
return;
}
waitMarkerFilePath = createWaitMarkerFile(verbose);
}
sendToPipe({
type: 'open',
fileURIs,
folderURIs,
diffMode: parsedArgs.diff,
addMode: parsedArgs.add,
gotoLineMode: parsedArgs.goto,
forceReuseWindow: parsedArgs['reuse-window'],
forceNewWindow: parsedArgs['new-window'],
waitMarkerFilePath,
remoteAuthority: remote
}, verbose);
if (waitMarkerFilePath) {
waitForFileDeleted(waitMarkerFilePath);
}
}
}
async function waitForFileDeleted(path: string) {
while (_fs.existsSync(path)) {
await new Promise(res => setTimeout(res, 1000));
}
}
function openInBrowser(args: string[], verbose: boolean) {
let uris: string[] = [];
for (let location of args) {
try {
if (/^(http|https|file):\/\//.test(location)) {
uris.push(_url.parse(location).href);
} else {
uris.push(pathToURI(location).href);
}
} catch (e) {
console.log(`Invalid url: ${location}`);
}
}
if (uris.length) {
sendToPipe({
type: 'openExternal',
uris
}, verbose);
}
}
function sendToPipe(args: PipeCommand, verbose: boolean): Promise<any> {
if (verbose) {
console.log(JSON.stringify(args, null, ' '));
}
return new Promise<string>(resolve => {
const message = JSON.stringify(args);
if (!cliPipe) {
console.log('Message ' + message);
resolve('');
return;
}
const opts: _http.RequestOptions = {
socketPath: cliPipe,
path: '/',
method: 'POST'
};
const req = _http.request(opts, res => {
const chunks: string[] = [];
res.setEncoding('utf8');
res.on('data', chunk => {
chunks.push(chunk);
});
res.on('error', () => fatal('Error in response'));
res.on('end', () => {
resolve(chunks.join(''));
});
});
req.on('error', () => fatal('Error in request'));
req.write(message);
req.end();
});
}
function asExtensionIdOrVSIX(inputs: string[] | undefined) {
return inputs?.map(input => /\.vsix$/i.test(input) ? pathToURI(input).href : input);
}
function fatal(err: any): void {
console.error('Unable to connect to VS Code server.');
console.error(err);
process.exit(1);
}
const preferredCwd = process.env.PWD || cwd(); // prefer process.env.PWD as it does not follow symlinks
function pathToURI(input: string): _url.URL {
input = input.trim();
input = resolve(preferredCwd, input);
return _url.pathToFileURL(input);
}
function translatePath(input: string, mapFileUri: (input: string) => string, folderURIS: string[], fileURIS: string[]) {
let url = pathToURI(input);
let mappedUri = mapFileUri(url.href);
try {
let stat = _fs.lstatSync(_fs.realpathSync(input));
if (stat.isFile()) {
fileURIS.push(mappedUri);
} else if (stat.isDirectory()) {
folderURIS.push(mappedUri);
} else if (input === '/dev/null') {
// handle /dev/null passed to us by external tools such as `git difftool`
fileURIS.push(mappedUri);
}
} catch (e) {
if (e.code === 'ENOENT') {
fileURIS.push(mappedUri);
} else {
console.log(`Problem accessing file ${input}. Ignoring file`, e);
}
}
}
function mapFileToRemoteUri(uri: string): string {
return uri.replace(/^file:\/\//, 'vscode-remote://' + cliRemoteAuthority);
}
let [, , productName, version, commit, executableName, ...remainingArgs] = process.argv;
main({ productName, version, commit, executableName }, remainingArgs);
| src/vs/server/remoteCli.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.00017496191139798611,
0.00017049440066330135,
0.00016052606224548072,
0.00017106310406234115,
0.0000033578835427761078
] |
{
"id": 0,
"code_window": [
" 'react',\n",
" 'react-dom',\n",
" 'react-redux',\n",
" 'redux',\n",
" 'rxjs',\n",
" 'react-router-dom',\n",
" 'd3',\n",
" 'angular',\n",
" '@grafana/ui',\n",
" '@grafana/runtime',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'react-router',\n"
],
"file_path": "packages/grafana-toolkit/src/config/webpack.plugin.config.ts",
"type": "add",
"edit_start_line_idx": 182
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00139548908919096,
0.00027378826052881777,
0.0001673475344432518,
0.00017552183999214321,
0.0003030987863894552
] |
{
"id": 0,
"code_window": [
" 'react',\n",
" 'react-dom',\n",
" 'react-redux',\n",
" 'redux',\n",
" 'rxjs',\n",
" 'react-router-dom',\n",
" 'd3',\n",
" 'angular',\n",
" '@grafana/ui',\n",
" '@grafana/runtime',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'react-router',\n"
],
"file_path": "packages/grafana-toolkit/src/config/webpack.plugin.config.ts",
"type": "add",
"edit_start_line_idx": 182
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { render, screen, within } from '@testing-library/react';
import React from 'react';
import GraphTicks from './GraphTicks';
const setup = (propOverrides) => {
const defaultProps = {
items: [
{ valueWidth: 100, valueOffset: 25, serviceName: 'a' },
{ valueWidth: 100, valueOffset: 50, serviceName: 'b' },
],
valueWidth: 200,
numTicks: 4,
...propOverrides,
};
return render(
<svg>
<GraphTicks {...defaultProps} />
</svg>
);
};
describe('GraphTicks tests', () => {
it('creates a <g> for ticks', () => {
setup();
expect(screen.getByTestId('ticks')).toBeInTheDocument();
});
it('creates a line for each ticks excluding the first and last', () => {
setup({ numTicks: 6 });
// defaultProps.numTicks - 1 === expect
expect(screen.getByTestId('ticks').children).toHaveLength(5);
});
});
| packages/jaeger-ui-components/src/TracePageHeader/SpanGraph/GraphTicks.test.js | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017720850883051753,
0.0001745910703903064,
0.0001706334442133084,
0.00017493678024038672,
0.0000023756031168886693
] |
{
"id": 0,
"code_window": [
" 'react',\n",
" 'react-dom',\n",
" 'react-redux',\n",
" 'redux',\n",
" 'rxjs',\n",
" 'react-router-dom',\n",
" 'd3',\n",
" 'angular',\n",
" '@grafana/ui',\n",
" '@grafana/runtime',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'react-router',\n"
],
"file_path": "packages/grafana-toolkit/src/config/webpack.plugin.config.ts",
"type": "add",
"edit_start_line_idx": 182
} | .admin-settings-section {
color: $variable;
font-weight: 500;
}
td.admin-settings-key {
padding-left: 20px;
}
.admin-list-table {
margin-bottom: 20px;
}
.admin-list-paging {
float: right;
li {
display: inline-block;
padding-left: 10px;
margin-bottom: 5px;
}
}
.admin-list-table {
.team-permissions {
padding-right: 120px;
}
}
| public/sass/pages/_admin.scss | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.0001773520343704149,
0.00017273436242248863,
0.00016643013805150986,
0.00017442088574171066,
0.000004615571469912538
] |
{
"id": 0,
"code_window": [
" 'react',\n",
" 'react-dom',\n",
" 'react-redux',\n",
" 'redux',\n",
" 'rxjs',\n",
" 'react-router-dom',\n",
" 'd3',\n",
" 'angular',\n",
" '@grafana/ui',\n",
" '@grafana/runtime',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'react-router',\n"
],
"file_path": "packages/grafana-toolkit/src/config/webpack.plugin.config.ts",
"type": "add",
"edit_start_line_idx": 182
} | import { config } from '../config';
import { locationService } from '../services';
import { getEchoSrv, EchoEventType } from '../services/EchoSrv';
import {
ExperimentViewEchoEvent,
InteractionEchoEvent,
MetaAnalyticsEvent,
MetaAnalyticsEventPayload,
PageviewEchoEvent,
} from '../types/analytics';
/**
* Helper function to report meta analytics to the {@link EchoSrv}.
*
* @public
*/
export const reportMetaAnalytics = (payload: MetaAnalyticsEventPayload) => {
getEchoSrv().addEvent<MetaAnalyticsEvent>({
type: EchoEventType.MetaAnalytics,
payload,
});
};
/**
* Helper function to report pageview events to the {@link EchoSrv}.
*
* @public
*/
export const reportPageview = () => {
const location = locationService.getLocation();
const page = `${config.appSubUrl ?? ''}${location.pathname}${location.search}${location.hash}`;
getEchoSrv().addEvent<PageviewEchoEvent>({
type: EchoEventType.Pageview,
payload: {
page,
},
});
};
/**
* Helper function to report interaction events to the {@link EchoSrv}.
*
* @public
*/
export const reportInteraction = (interactionName: string, properties?: Record<string, any>) => {
getEchoSrv().addEvent<InteractionEchoEvent>({
type: EchoEventType.Interaction,
payload: {
interactionName,
properties,
},
});
};
/**
* Helper function to report experimentview events to the {@link EchoSrv}.
*
* @public
*/
export const reportExperimentView = (id: string, group: string, variant: string) => {
getEchoSrv().addEvent<ExperimentViewEchoEvent>({
type: EchoEventType.ExperimentView,
payload: {
experimentId: id,
experimentGroup: group,
experimentVariant: variant,
},
});
};
| packages/grafana-runtime/src/utils/analytics.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017772936553228647,
0.0001749922666931525,
0.0001706891052890569,
0.00017468536680098623,
0.0000022547587832377758
] |
{
"id": 1,
"code_window": [
" beforeEach(() => {\n",
" jest.resetAllMocks();\n",
" setEchoSrv(new Echo());\n",
" });\n",
"\n",
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const pluginMeta = getMockPlugin({\n",
" id: 'my-awesome-plugin',\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" });\n",
"\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 83
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.39048460125923157,
0.02724946103990078,
0.00016399628657381982,
0.00017545373702887446,
0.09710709005594254
] |
{
"id": 1,
"code_window": [
" beforeEach(() => {\n",
" jest.resetAllMocks();\n",
" setEchoSrv(new Echo());\n",
" });\n",
"\n",
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const pluginMeta = getMockPlugin({\n",
" id: 'my-awesome-plugin',\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" });\n",
"\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 83
} | import { ArrayVector, Field, FieldType, MutableDataFrame, SelectableValue } from '@grafana/data';
import {
calculateUniqueFieldValues,
filterByValue,
getColumns,
getFilteredOptions,
getTextAlign,
rowToFieldValue,
sortNumber,
sortOptions,
valuesToOptions,
} from './utils';
function getData() {
const data = new MutableDataFrame({
fields: [
{ name: 'Time', type: FieldType.time, values: [] },
{
name: 'Value',
type: FieldType.number,
values: [],
config: {
custom: {
width: 100,
},
},
},
{
name: 'Message',
type: FieldType.string,
values: [],
config: {
custom: {
align: 'center',
},
},
},
],
});
return data;
}
describe('Table utils', () => {
describe('getColumns', () => {
it('Should build columns from DataFrame', () => {
const columns = getColumns(getData(), 1000, 120);
expect(columns[0].Header).toBe('Time');
expect(columns[1].Header).toBe('Value');
});
it('Should distribute width and use field config width', () => {
const columns = getColumns(getData(), 1000, 120);
expect(columns[0].width).toBe(450);
expect(columns[1].width).toBe(100);
});
it('Should set field on columns', () => {
const columns = getColumns(getData(), 1000, 120);
expect(columns[0].field.name).toBe('Time');
expect(columns[1].field.name).toBe('Value');
});
});
describe('getTextAlign', () => {
it('Should use textAlign from custom', () => {
const data = getData();
const textAlign = getTextAlign(data.fields[2]);
expect(textAlign).toBe('center');
});
it('Should set textAlign to right for number values', () => {
const data = getData();
const textAlign = getTextAlign(data.fields[1]);
expect(textAlign).toBe('flex-end');
});
});
describe('filterByValue', () => {
describe('happy path', () => {
const field: any = { values: new ArrayVector(['a', 'aa', 'ab', 'b', 'ba', 'bb', 'c']) };
const rows: any = [
{ index: 0, values: { 0: 'a' } },
{ index: 1, values: { 0: 'aa' } },
{ index: 2, values: { 0: 'ab' } },
{ index: 3, values: { 0: 'b' } },
{ index: 4, values: { 0: 'ba' } },
{ index: 5, values: { 0: 'bb' } },
{ index: 6, values: { 0: 'c' } },
];
const filterValues = [{ value: 'a' }, { value: 'b' }, { value: 'c' }];
const result = filterByValue(field)(rows, '0', filterValues);
expect(result).toEqual([
{ index: 0, values: { 0: 'a' } },
{ index: 3, values: { 0: 'b' } },
{ index: 6, values: { 0: 'c' } },
]);
});
describe('fast exit cases', () => {
describe('no rows', () => {
it('should return empty array', () => {
const field: any = { values: new ArrayVector(['a']) };
const rows: any = [];
const filterValues = [{ value: 'a' }];
const result = filterByValue(field)(rows, '', filterValues);
expect(result).toEqual([]);
});
});
describe('no filterValues', () => {
it('should return rows', () => {
const field: any = { values: new ArrayVector(['a']) };
const rows: any = [{}];
const filterValues = undefined;
const result = filterByValue(field)(rows, '', filterValues);
expect(result).toEqual([{}]);
});
});
describe('no field', () => {
it('should return rows', () => {
const field = undefined;
const rows: any = [{}];
const filterValues = [{ value: 'a' }];
const result = filterByValue(field)(rows, '', filterValues);
expect(result).toEqual([{}]);
});
});
describe('missing id in values', () => {
it('should return rows', () => {
const field: any = { values: new ArrayVector(['a', 'b', 'c']) };
const rows: any = [
{ index: 0, values: { 0: 'a' } },
{ index: 1, values: { 0: 'b' } },
{ index: 2, values: { 0: 'c' } },
];
const filterValues = [{ value: 'a' }, { value: 'b' }, { value: 'c' }];
const result = filterByValue(field)(rows, '1', filterValues);
expect(result).toEqual([]);
});
});
});
});
describe('calculateUniqueFieldValues', () => {
describe('when called without field', () => {
it('then it should return an empty object', () => {
const field = undefined;
const rows = [{ index: 0 }];
const result = calculateUniqueFieldValues(rows, field);
expect(result).toEqual({});
});
});
describe('when called with no rows', () => {
it('then it should return an empty object', () => {
const field: Field = {
config: {},
labels: {},
values: new ArrayVector([1]),
name: 'value',
type: FieldType.number,
getLinks: () => [],
state: null,
display: (value: any) => ({
numeric: 1,
percent: 0.01,
color: '',
title: '1.0',
text: '1.0',
}),
};
const rows: any[] = [];
const result = calculateUniqueFieldValues(rows, field);
expect(result).toEqual({});
});
});
describe('when called with rows and field with display processor', () => {
it('then it should return an array with unique values', () => {
const field: Field = {
config: {},
values: new ArrayVector([1, 2, 2, 1, 3, 5, 6]),
name: 'value',
type: FieldType.number,
display: jest.fn((value: any) => ({
numeric: 1,
percent: 0.01,
color: '',
title: `${value}.0`,
text: `${value}.0`,
})),
};
const rows: any[] = [{ index: 0 }, { index: 1 }, { index: 2 }, { index: 3 }, { index: 4 }];
const result = calculateUniqueFieldValues(rows, field);
expect(field.display).toHaveBeenCalledTimes(5);
expect(result).toEqual({
'1.0': '1.0',
'2.0': '2.0',
'3.0': '3.0',
});
});
});
describe('when called with rows and field without display processor', () => {
it('then it should return an array with unique values', () => {
const field: Field = {
config: {},
values: new ArrayVector([1, 2, 2, 1, 3, 5, 6]),
name: 'value',
type: FieldType.number,
};
const rows: any[] = [{ index: 0 }, { index: 1 }, { index: 2 }, { index: 3 }, { index: 4 }];
const result = calculateUniqueFieldValues(rows, field);
expect(result).toEqual({
'1': 1,
'2': 2,
'3': 3,
});
});
describe('when called with rows with blanks and field', () => {
it('then it should return an array with unique values and (Blanks)', () => {
const field: Field = {
config: {},
values: new ArrayVector([1, null, null, 1, 3, 5, 6]),
name: 'value',
type: FieldType.number,
};
const rows: any[] = [{ index: 0 }, { index: 1 }, { index: 2 }, { index: 3 }, { index: 4 }];
const result = calculateUniqueFieldValues(rows, field);
expect(result).toEqual({
'(Blanks)': null,
'1': 1,
'3': 3,
});
});
});
});
});
describe('rowToFieldValue', () => {
describe('happy paths', () => {
describe('field without field display', () => {
const field: any = { values: new ArrayVector(['a', 'b', 'c']) };
const row = { index: 1 };
const result = rowToFieldValue(row, field);
expect(result).toEqual('b');
});
describe('field with display processor', () => {
const field: Field = {
config: {},
values: new ArrayVector([1, 2, 2, 1, 3, 5, 6]),
name: 'value',
type: FieldType.number,
display: jest.fn((value: any) => ({
numeric: 1,
percent: 0.01,
color: '',
title: `${value}.0`,
text: `${value}.0`,
})),
};
const row = { index: 4 };
const result = rowToFieldValue(row, field);
expect(result).toEqual('3.0');
});
});
describe('quick exist paths', () => {
describe('field is missing', () => {
const field = undefined;
const row = { index: 0 };
const result = rowToFieldValue(row, field);
expect(result).toEqual('');
});
describe('row is missing', () => {
const field: any = { values: new ArrayVector(['a', 'b', 'c']) };
const row = undefined;
const result = rowToFieldValue(row, field);
expect(result).toEqual('');
});
});
});
describe('valuesToOptions', () => {
describe('when called with a record object', () => {
it('then it should return sorted options from that object', () => {
const date = new Date();
const unique = {
string: 'string',
numeric: 1,
date: date,
boolean: true,
};
const result = valuesToOptions(unique);
expect(result).toEqual([
{ label: 'boolean', value: true },
{ label: 'date', value: date },
{ label: 'numeric', value: 1 },
{ label: 'string', value: 'string' },
]);
});
});
});
describe('sortOptions', () => {
it.each`
a | b | expected
${{ label: undefined }} | ${{ label: undefined }} | ${0}
${{ label: undefined }} | ${{ label: 'b' }} | ${-1}
${{ label: 'a' }} | ${{ label: undefined }} | ${1}
${{ label: 'a' }} | ${{ label: 'b' }} | ${-1}
${{ label: 'b' }} | ${{ label: 'a' }} | ${1}
${{ label: 'a' }} | ${{ label: 'a' }} | ${0}
`("when called with a: '$a.toString', b: '$b.toString' then result should be '$expected'", ({ a, b, expected }) => {
expect(sortOptions(a, b)).toEqual(expected);
});
});
describe('getFilteredOptions', () => {
describe('when called without filterValues', () => {
it('then it should return an empty array', () => {
const options = [
{ label: 'a', value: 'a' },
{ label: 'b', value: 'b' },
{ label: 'c', value: 'c' },
];
const filterValues = undefined;
const result = getFilteredOptions(options, filterValues);
expect(result).toEqual([]);
});
});
describe('when called with no options', () => {
it('then it should return an empty array', () => {
const options: SelectableValue[] = [];
const filterValues = [
{ label: 'a', value: 'a' },
{ label: 'b', value: 'b' },
{ label: 'c', value: 'c' },
];
const result = getFilteredOptions(options, filterValues);
expect(result).toEqual(options);
});
});
describe('when called with options and matching filterValues', () => {
it('then it should return an empty array', () => {
const options: SelectableValue[] = [
{ label: 'a', value: 'a' },
{ label: 'b', value: 'b' },
{ label: 'c', value: 'c' },
];
const filterValues = [
{ label: 'a', value: 'a' },
{ label: 'b', value: 'b' },
];
const result = getFilteredOptions(options, filterValues);
expect(result).toEqual([
{ label: 'a', value: 'a' },
{ label: 'b', value: 'b' },
]);
});
});
describe('when called with options and non matching filterValues', () => {
it('then it should return an empty array', () => {
const options: SelectableValue[] = [
{ label: 'a', value: 'a' },
{ label: 'b', value: 'b' },
{ label: 'c', value: 'c' },
];
const filterValues = [{ label: 'q', value: 'q' }];
const result = getFilteredOptions(options, filterValues);
expect(result).toEqual([]);
});
});
});
describe('sortNumber', () => {
it.each`
a | b | expected
${{ values: [] }} | ${{ values: [] }} | ${0}
${{ values: [undefined] }} | ${{ values: [undefined] }} | ${0}
${{ values: [null] }} | ${{ values: [null] }} | ${0}
${{ values: [Number.POSITIVE_INFINITY] }} | ${{ values: [Number.POSITIVE_INFINITY] }} | ${0}
${{ values: [Number.NEGATIVE_INFINITY] }} | ${{ values: [Number.NEGATIVE_INFINITY] }} | ${0}
${{ values: [Number.POSITIVE_INFINITY] }} | ${{ values: [Number.NEGATIVE_INFINITY] }} | ${1}
${{ values: [Number.NEGATIVE_INFINITY] }} | ${{ values: [Number.POSITIVE_INFINITY] }} | ${-1}
${{ values: ['infinIty'] }} | ${{ values: ['infinIty'] }} | ${0}
${{ values: ['infinity'] }} | ${{ values: ['not infinity'] }} | ${0}
${{ values: [1] }} | ${{ values: [1] }} | ${0}
${{ values: [1.5] }} | ${{ values: [1.5] }} | ${0}
${{ values: [2] }} | ${{ values: [1] }} | ${1}
${{ values: [25] }} | ${{ values: [2.5] }} | ${1}
${{ values: [2.5] }} | ${{ values: [1.5] }} | ${1}
${{ values: [1] }} | ${{ values: [2] }} | ${-1}
${{ values: [2.5] }} | ${{ values: [25] }} | ${-1}
${{ values: [1.5] }} | ${{ values: [2.5] }} | ${-1}
${{ values: [1] }} | ${{ values: [] }} | ${1}
${{ values: [1] }} | ${{ values: [undefined] }} | ${1}
${{ values: [1] }} | ${{ values: [null] }} | ${1}
${{ values: [1] }} | ${{ values: [Number.POSITIVE_INFINITY] }} | ${-1}
${{ values: [1] }} | ${{ values: [Number.NEGATIVE_INFINITY] }} | ${1}
${{ values: [1] }} | ${{ values: ['infinIty'] }} | ${1}
${{ values: [-1] }} | ${{ values: ['infinIty'] }} | ${1}
${{ values: [] }} | ${{ values: [1] }} | ${-1}
${{ values: [undefined] }} | ${{ values: [1] }} | ${-1}
${{ values: [null] }} | ${{ values: [1] }} | ${-1}
${{ values: [Number.POSITIVE_INFINITY] }} | ${{ values: [1] }} | ${1}
${{ values: [Number.NEGATIVE_INFINITY] }} | ${{ values: [1] }} | ${-1}
${{ values: ['infinIty'] }} | ${{ values: [1] }} | ${-1}
${{ values: ['infinIty'] }} | ${{ values: [-1] }} | ${-1}
${{ values: [1] }} | ${{ values: [NaN] }} | ${1}
${{ values: [NaN] }} | ${{ values: [NaN] }} | ${0}
${{ values: [NaN] }} | ${{ values: [1] }} | ${-1}
`("when called with a: '$a.toString', b: '$b.toString' then result should be '$expected'", ({ a, b, expected }) => {
expect(sortNumber(a, b, '0')).toEqual(expected);
});
it.skip('should have good performance', () => {
const ITERATIONS = 100000;
const a: any = { values: Array(ITERATIONS) };
const b: any = { values: Array(ITERATIONS) };
for (let i = 0; i < ITERATIONS; i++) {
a.values[i] = Math.random() * Date.now();
b.values[i] = Math.random() * Date.now();
}
const start = performance.now();
for (let i = 0; i < ITERATIONS; i++) {
sortNumber(a, b, i.toString(10));
}
const stop = performance.now();
const diff = stop - start;
expect(diff).toBeLessThanOrEqual(20);
});
});
});
| packages/grafana-ui/src/components/Table/utils.test.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017877515347208828,
0.0001747939531924203,
0.00016719983250368387,
0.00017528333410155028,
0.0000025548101802996825
] |
{
"id": 1,
"code_window": [
" beforeEach(() => {\n",
" jest.resetAllMocks();\n",
" setEchoSrv(new Echo());\n",
" });\n",
"\n",
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const pluginMeta = getMockPlugin({\n",
" id: 'my-awesome-plugin',\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" });\n",
"\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 83
} | import { getBackendSrv } from '@grafana/runtime';
import { updateConfigurationSubtitle } from 'app/core/actions';
import { ThunkResult } from 'app/types';
import { organizationLoaded, userOrganizationsLoaded } from './reducers';
type OrganizationDependencies = { getBackendSrv: typeof getBackendSrv };
export function loadOrganization(
dependencies: OrganizationDependencies = { getBackendSrv: getBackendSrv }
): ThunkResult<any> {
return async (dispatch) => {
const organizationResponse = await dependencies.getBackendSrv().get('/api/org');
dispatch(organizationLoaded(organizationResponse));
return organizationResponse;
};
}
export function updateOrganization(
dependencies: OrganizationDependencies = { getBackendSrv: getBackendSrv }
): ThunkResult<any> {
return async (dispatch, getStore) => {
const organization = getStore().organization.organization;
await dependencies.getBackendSrv().put('/api/org', { name: organization.name });
dispatch(updateConfigurationSubtitle(organization.name));
dispatch(loadOrganization(dependencies));
};
}
export function setUserOrganization(
orgId: number,
dependencies: OrganizationDependencies = { getBackendSrv: getBackendSrv }
): ThunkResult<any> {
return async (dispatch) => {
const organizationResponse = await dependencies.getBackendSrv().post('/api/user/using/' + orgId);
dispatch(updateConfigurationSubtitle(organizationResponse.name));
};
}
export function createOrganization(
newOrg: { name: string },
dependencies: OrganizationDependencies = { getBackendSrv: getBackendSrv }
): ThunkResult<any> {
return async (dispatch) => {
const result = await dependencies.getBackendSrv().post('/api/orgs/', newOrg);
dispatch(setUserOrganization(result.orgId));
};
}
export function getUserOrganizations(
dependencies: OrganizationDependencies = { getBackendSrv: getBackendSrv }
): ThunkResult<any> {
return async (dispatch) => {
const result = await dependencies.getBackendSrv().get('/api/user/orgs');
dispatch(userOrganizationsLoaded(result));
return result;
};
}
| public/app/features/org/state/actions.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017808255506679416,
0.0001696030521998182,
0.00016525630780961365,
0.00016783218597993255,
0.0000040670825001143385
] |
{
"id": 1,
"code_window": [
" beforeEach(() => {\n",
" jest.resetAllMocks();\n",
" setEchoSrv(new Echo());\n",
" });\n",
"\n",
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const pluginMeta = getMockPlugin({\n",
" id: 'my-awesome-plugin',\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" });\n",
"\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 83
} | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/grafana/grafana/pkg/services/screenshot (interfaces: ScreenshotService)
// Package screenshot is a generated GoMock package.
package screenshot
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockScreenshotService is a mock of ScreenshotService interface.
type MockScreenshotService struct {
ctrl *gomock.Controller
recorder *MockScreenshotServiceMockRecorder
}
// MockScreenshotServiceMockRecorder is the mock recorder for MockScreenshotService.
type MockScreenshotServiceMockRecorder struct {
mock *MockScreenshotService
}
// NewMockScreenshotService creates a new mock instance.
func NewMockScreenshotService(ctrl *gomock.Controller) *MockScreenshotService {
mock := &MockScreenshotService{ctrl: ctrl}
mock.recorder = &MockScreenshotServiceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockScreenshotService) EXPECT() *MockScreenshotServiceMockRecorder {
return m.recorder
}
// Take mocks base method.
func (m *MockScreenshotService) Take(arg0 context.Context, arg1 ScreenshotOptions) (*Screenshot, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Take", arg0, arg1)
ret0, _ := ret[0].(*Screenshot)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Take indicates an expected call of Take.
func (mr *MockScreenshotServiceMockRecorder) Take(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Take", reflect.TypeOf((*MockScreenshotService)(nil).Take), arg0, arg1)
}
| pkg/services/screenshot/mock.go | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017631171795073897,
0.00017158857372123748,
0.00016691931523382664,
0.00017213044338859618,
0.000003839393684756942
] |
{
"id": 2,
"code_window": [
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n",
"\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" const plugin = new AppPlugin();\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 85
} | import * as webpack from 'webpack';
import { getStyleLoaders, getStylesheetEntries, getFileLoaders } from './webpack/loaders';
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const ReplaceInFileWebpackPlugin = require('replace-in-file-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const util = require('util');
const readdirPromise = util.promisify(fs.readdir);
const accessPromise = util.promisify(fs.access);
export interface WebpackConfigurationOptions {
watch?: boolean;
production?: boolean;
preserveConsole?: boolean;
}
type WebpackConfigurationGetter = (options: WebpackConfigurationOptions) => Promise<webpack.Configuration>;
export type CustomWebpackConfigurationGetter = (
originalConfig: webpack.Configuration,
options: WebpackConfigurationOptions
) => webpack.Configuration;
export const findModuleFiles = async (base: string, files?: string[], result?: string[]) => {
files = files || (await readdirPromise(base));
result = result || [];
if (files) {
await Promise.all(
files.map(async (file) => {
const newbase = path.join(base, file);
if (fs.statSync(newbase).isDirectory()) {
result = await findModuleFiles(newbase, await readdirPromise(newbase), result);
} else {
const filename = path.basename(file);
if (/^module.(t|j)sx?$/.exec(filename)) {
// @ts-ignore
result.push(newbase);
}
}
})
);
}
return result;
};
const getModuleFiles = () => {
return findModuleFiles(path.resolve(process.cwd(), 'src'));
};
const getManualChunk = (id: string) => {
if (id.endsWith('module.ts') || id.endsWith('module.js') || id.endsWith('module.tsx')) {
const idx = id.lastIndexOf(path.sep + 'src' + path.sep);
if (idx > 0) {
const name = id.substring(idx + 5, id.lastIndexOf('.'));
return {
name,
module: id,
};
}
}
return null;
};
const getEntries = async () => {
const entries: { [key: string]: string } = {};
const modules = await getModuleFiles();
modules.forEach((modFile) => {
const mod = getManualChunk(modFile);
// @ts-ignore
entries[mod.name] = mod.module;
});
return {
...entries,
...getStylesheetEntries(),
};
};
const getCommonPlugins = (options: WebpackConfigurationOptions) => {
const hasREADME = fs.existsSync(path.resolve(process.cwd(), 'src', 'README.md'));
const packageJson = require(path.resolve(process.cwd(), 'package.json'));
return [
new MiniCssExtractPlugin({
// both options are optional
filename: 'styles/[name].css',
}),
new CopyWebpackPlugin({
patterns: [
// If src/README.md exists use it; otherwise the root README
{ from: hasREADME ? 'README.md' : '../README.md', to: '.', force: true, priority: 1, noErrorOnMissing: true },
{ from: 'plugin.json', to: '.', noErrorOnMissing: true },
{ from: '**/README.md', to: '[path]README.md', priority: 0, noErrorOnMissing: true },
{ from: '../LICENSE', to: '.', noErrorOnMissing: true },
{ from: '../CHANGELOG.md', to: '.', force: true, noErrorOnMissing: true },
{ from: '**/*.{json,svg,png,html}', to: '.', noErrorOnMissing: true },
{ from: 'img/**/*', to: '.', noErrorOnMissing: true },
{ from: 'libs/**/*', to: '.', noErrorOnMissing: true },
{ from: 'static/**/*', to: '.', noErrorOnMissing: true },
],
}),
new ReplaceInFileWebpackPlugin([
{
dir: 'dist',
files: ['plugin.json', 'README.md'],
rules: [
{
search: '%VERSION%',
replace: packageJson.version,
},
{
search: '%TODAY%',
replace: new Date().toISOString().substring(0, 10),
},
],
},
]),
new ForkTsCheckerWebpackPlugin({
typescript: { configFile: path.join(process.cwd(), 'tsconfig.json') },
issue: {
include: [{ file: '**/*.{ts,tsx}' }],
},
}),
];
};
const getBaseWebpackConfig: WebpackConfigurationGetter = async (options) => {
const plugins = getCommonPlugins(options);
const optimization: { [key: string]: any } = {};
if (options.production) {
const compressOptions = { drop_console: !options.preserveConsole, drop_debugger: true };
optimization.minimizer = [
new TerserPlugin({ terserOptions: { compress: compressOptions } }),
new CssMinimizerPlugin(),
];
optimization.chunkIds = 'total-size';
optimization.moduleIds = 'size';
} else if (options.watch) {
plugins.push(new HtmlWebpackPlugin());
}
return {
mode: options.production ? 'production' : 'development',
target: 'web',
context: path.join(process.cwd(), 'src'),
devtool: 'source-map',
entry: await getEntries(),
output: {
filename: '[name].js',
path: path.join(process.cwd(), 'dist'),
libraryTarget: 'amd',
publicPath: '/',
},
performance: { hints: false },
externals: [
'lodash',
'jquery',
'moment',
'slate',
'emotion',
'@emotion/react',
'@emotion/css',
'prismjs',
'slate-plain-serializer',
'@grafana/slate-react',
'react',
'react-dom',
'react-redux',
'redux',
'rxjs',
'react-router-dom',
'd3',
'angular',
'@grafana/ui',
'@grafana/runtime',
'@grafana/data',
({ request }, callback) => {
const prefix = 'grafana/';
if (request?.indexOf(prefix) === 0) {
return callback(undefined, request.slice(prefix.length));
}
callback();
},
],
plugins,
resolve: {
extensions: ['.ts', '.tsx', '.js'],
modules: [path.resolve(process.cwd(), 'src'), 'node_modules'],
fallback: {
buffer: false,
fs: false,
stream: false,
http: false,
https: false,
string_decoder: false,
os: false,
timers: false,
},
},
module: {
rules: [
{
test: /\.[tj]sx?$/,
use: {
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
cacheCompression: false,
presets: [
[require.resolve('@babel/preset-env'), { modules: false }],
[
require.resolve('@babel/preset-typescript'),
{
allowNamespaces: true,
allowDeclareFields: true,
},
],
[require.resolve('@babel/preset-react')],
],
plugins: [
[
require.resolve('@babel/plugin-transform-typescript'),
{
allowNamespaces: true,
allowDeclareFields: true,
},
],
require.resolve('@babel/plugin-proposal-class-properties'),
[require.resolve('@babel/plugin-proposal-object-rest-spread'), { loose: true }],
require.resolve('@babel/plugin-transform-react-constant-elements'),
require.resolve('@babel/plugin-proposal-nullish-coalescing-operator'),
require.resolve('@babel/plugin-proposal-optional-chaining'),
require.resolve('@babel/plugin-syntax-dynamic-import'),
require.resolve('babel-plugin-angularjs-annotate'),
],
},
},
exclude: /node_modules/,
},
...getStyleLoaders(),
{
test: /\.html$/,
exclude: [/node_modules/],
use: {
loader: require.resolve('html-loader'),
},
},
...getFileLoaders(),
],
},
optimization,
};
};
export const loadWebpackConfig: WebpackConfigurationGetter = async (options) => {
const baseConfig = await getBaseWebpackConfig(options);
const customWebpackPath = path.resolve(process.cwd(), 'webpack.config.js');
try {
await accessPromise(customWebpackPath);
const customConfig = require(customWebpackPath);
const configGetter = customConfig.getWebpackConfig || customConfig;
if (typeof configGetter !== 'function') {
throw Error(
'Custom webpack config needs to export a function implementing CustomWebpackConfigurationGetter. Function needs to be ' +
'module export or named "getWebpackConfig"'
);
}
return (configGetter as CustomWebpackConfigurationGetter)(baseConfig, options);
} catch (err: any) {
if (err.code === 'ENOENT') {
return baseConfig;
}
throw err;
}
};
| packages/grafana-toolkit/src/config/webpack.plugin.config.ts | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017622952873352915,
0.00017125192971434444,
0.00016536253679078072,
0.0001716834813123569,
0.0000029873228868382284
] |
{
"id": 2,
"code_window": [
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n",
"\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" const plugin = new AppPlugin();\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 85
} | type StoreValue = string | number | boolean | null;
export class Store {
get(key: string) {
return window.localStorage[key];
}
set(key: string, value: StoreValue) {
window.localStorage[key] = value;
}
getBool(key: string, def: boolean): boolean {
if (def !== void 0 && !this.exists(key)) {
return def;
}
return window.localStorage[key] === 'true';
}
getObject<T = unknown>(key: string): T | undefined;
getObject<T = unknown>(key: string, def: T): T;
getObject<T = unknown>(key: string, def?: T) {
let ret = def;
if (this.exists(key)) {
const json = window.localStorage[key];
try {
ret = JSON.parse(json);
} catch (error) {
console.error(`Error parsing store object: ${key}. Returning default: ${def}. [${error}]`);
}
}
return ret;
}
/* Returns true when successfully stored, throws error if not successfully stored */
setObject(key: string, value: any) {
let json;
try {
json = JSON.stringify(value);
} catch (error) {
throw new Error(`Could not stringify object: ${key}. [${error}]`);
}
try {
this.set(key, json);
} catch (error) {
// Likely hitting storage quota
const errorToThrow = new Error(`Could not save item in localStorage: ${key}. [${error}]`);
if (error instanceof Error) {
errorToThrow.name = error.name;
}
throw errorToThrow;
}
return true;
}
exists(key: string) {
return window.localStorage[key] !== void 0;
}
delete(key: string) {
window.localStorage.removeItem(key);
}
}
const store = new Store();
export default store;
| public/app/core/store.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017580037820152938,
0.00017338003090117127,
0.0001707589253783226,
0.00017353735165670514,
0.0000014479312540061073
] |
{
"id": 2,
"code_window": [
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n",
"\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" const plugin = new AppPlugin();\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 85
} | <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M19,6h-3V5c0-1.1-0.9-2-2-2h-4C8.9,3,8,3.9,8,5v1H5C3.3,6,2,7.3,2,9v9c0,1.7,1.3,3,3,3h14c1.7,0,3-1.3,3-3V9C22,7.3,20.7,6,19,6z M10,5h4v1h-4V5z M20,18c0,0.6-0.4,1-1,1H5c-0.6,0-1-0.4-1-1v-5.6l4.7,1.6C8.8,14,8.9,14,9,14h6c0.1,0,0.2,0,0.3-0.1l4.7-1.6V18z"/></svg> | public/img/icons/solid/bag.svg | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017422839300706983,
0.00017422839300706983,
0.00017422839300706983,
0.00017422839300706983,
0
] |
{
"id": 2,
"code_window": [
" it('should not mount plugin twice if nav is changed', async () => {\n",
" // reproduces https://github.com/grafana/grafana/pull/28105\n",
"\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" const plugin = new AppPlugin();\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 85
} | import { css } from '@emotion/css';
import { GrafanaTheme2 } from '@grafana/data';
export const getBadgeColor = (theme: GrafanaTheme2) => css`
background: ${theme.colors.background.primary};
border-color: ${theme.colors.border.strong};
color: ${theme.colors.text.secondary};
`;
| public/app/features/plugins/admin/components/Badges/sharedStyles.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00016996523481793702,
0.00016996523481793702,
0.00016996523481793702,
0.00016996523481793702,
0
] |
{
"id": 3,
"code_window": [
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 94
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.9982477426528931,
0.1340419501066208,
0.00016566399426665157,
0.0007575387135148048,
0.3389681279659271
] |
{
"id": 3,
"code_window": [
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 94
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14,9.45H10a1,1,0,0,0,0,2h4a1,1,0,0,0,0-2Zm6.46.18A8.5,8.5,0,1,0,6,16.46l5.3,5.31a1,1,0,0,0,1.42,0L18,16.46A8.46,8.46,0,0,0,20.46,9.63ZM16.6,15.05,12,19.65l-4.6-4.6A6.49,6.49,0,0,1,5.53,9.83,6.57,6.57,0,0,1,8.42,5a6.47,6.47,0,0,1,7.16,0,6.57,6.57,0,0,1,2.89,4.81A6.49,6.49,0,0,1,16.6,15.05Z"/></svg> | public/img/icons/unicons/map-marker-minus.svg | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.0001696003309916705,
0.0001696003309916705,
0.0001696003309916705,
0.0001696003309916705,
0
] |
{
"id": 3,
"code_window": [
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 94
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17.71,11.29l-2.5-2.5a1,1,0,0,0-1.42,1.42l.8.79H9.41l.8-.79A1,1,0,0,0,8.79,8.79l-2.5,2.5a1,1,0,0,0-.21.33,1,1,0,0,0,0,.76,1,1,0,0,0,.21.33l2.5,2.5a1,1,0,0,0,1.42,0,1,1,0,0,0,0-1.42L9.41,13h5.18l-.8.79a1,1,0,0,0,0,1.42,1,1,0,0,0,1.42,0l2.5-2.5a1,1,0,0,0,.21-.33,1,1,0,0,0,0-.76A1,1,0,0,0,17.71,11.29ZM3,6A1,1,0,0,0,2,7V17a1,1,0,0,0,2,0V7A1,1,0,0,0,3,6ZM21,6a1,1,0,0,0-1,1V17a1,1,0,0,0,2,0V7A1,1,0,0,0,21,6Z"/></svg> | public/img/icons/unicons/arrows-shrink-h.svg | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017076186486519873,
0.00017076186486519873,
0.00017076186486519873,
0.00017076186486519873,
0
] |
{
"id": 3,
"code_window": [
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 94
} | import React, { FC, useMemo, useState } from 'react';
import { useObservable } from 'react-use';
import AutoSizer from 'react-virtualized-auto-sizer';
import {
ApplyFieldOverrideOptions,
DataTransformerConfig,
dateMath,
FieldColorModeId,
NavModelItem,
PanelData,
} from '@grafana/data';
import { Button, Table } from '@grafana/ui';
import { Page } from 'app/core/components/Page/Page';
import { config } from 'app/core/config';
import { useAppNotification } from 'app/core/copy/appNotification';
import { QueryGroupOptions } from 'app/types';
import { PanelRenderer } from '../panel/components/PanelRenderer';
import { QueryGroup } from '../query/components/QueryGroup';
import { PanelQueryRunner } from '../query/state/PanelQueryRunner';
interface State {
queryRunner: PanelQueryRunner;
queryOptions: QueryGroupOptions;
data?: PanelData;
}
export const TestStuffPage: FC = () => {
const [state, setState] = useState<State>(getDefaultState());
const { queryOptions, queryRunner } = state;
const onRunQueries = () => {
const timeRange = { from: 'now-1h', to: 'now' };
queryRunner.run({
queries: queryOptions.queries,
datasource: queryOptions.dataSource,
timezone: 'browser',
timeRange: { from: dateMath.parse(timeRange.from)!, to: dateMath.parse(timeRange.to)!, raw: timeRange },
maxDataPoints: queryOptions.maxDataPoints ?? 100,
minInterval: queryOptions.minInterval,
});
};
const onOptionsChange = (queryOptions: QueryGroupOptions) => {
setState({ ...state, queryOptions });
};
/**
* Subscribe to data
*/
const observable = useMemo(() => queryRunner.getData({ withFieldConfig: true, withTransforms: true }), [queryRunner]);
const data = useObservable(observable);
const node: NavModelItem = {
id: 'test-page',
text: 'Test page',
icon: 'dashboard',
subTitle: 'FOR TESTING!',
url: 'sandbox/test',
};
const notifyApp = useAppNotification();
return (
<Page navModel={{ node: node, main: node }}>
<Page.Contents>
{data && (
<AutoSizer style={{ width: '100%', height: '600px' }}>
{({ width }) => {
return (
<div>
<PanelRenderer
title="Hello"
pluginId="timeseries"
width={width}
height={300}
data={data}
options={{}}
fieldConfig={{ defaults: {}, overrides: [] }}
timeZone="browser"
/>
<Table data={data.series[0]} width={width} height={300} />
</div>
);
}}
</AutoSizer>
)}
<div style={{ marginTop: '16px', height: '45%' }}>
<QueryGroup
options={queryOptions}
queryRunner={queryRunner}
onRunQueries={onRunQueries}
onOptionsChange={onOptionsChange}
/>
</div>
<div style={{ display: 'flex', gap: '1em' }}>
<Button onClick={() => notifyApp.success('Success toast', 'some more text goes here')} variant="primary">
Success
</Button>
<Button
onClick={() => notifyApp.warning('Warning toast', 'some more text goes here', 'bogus-trace-99999')}
variant="secondary"
>
Warning
</Button>
<Button
onClick={() => notifyApp.error('Error toast', 'some more text goes here', 'bogus-trace-fdsfdfsfds')}
variant="destructive"
>
Error
</Button>
</div>
</Page.Contents>
</Page>
);
};
export function getDefaultState(): State {
const options: ApplyFieldOverrideOptions = {
fieldConfig: {
defaults: {
color: {
mode: FieldColorModeId.PaletteClassic,
},
},
overrides: [],
},
replaceVariables: (v: string) => v,
theme: config.theme2,
};
const dataConfig = {
getTransformations: () => [] as DataTransformerConfig[],
getFieldOverrideOptions: () => options,
getDataSupport: () => ({ annotations: false, alertStates: false }),
};
return {
queryRunner: new PanelQueryRunner(dataConfig),
queryOptions: {
queries: [],
dataSource: {
name: 'gdev-testdata',
},
maxDataPoints: 100,
},
};
}
export default TestStuffPage;
| public/app/features/sandbox/TestStuffPage.tsx | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017932387709151953,
0.00017287381342612207,
0.00016659415268804878,
0.0001728414063109085,
0.0000028695035325654317
] |
{
"id": 4,
"code_window": [
" expect(RootComponent.timesMounted).toEqual(1);\n",
" });\n",
"\n",
" it('should not render component if not at plugin path', async () => {\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" class RootComponent extends Component<AppRootProps> {\n",
" static timesRendered = 0;\n",
" render() {\n",
" RootComponent.timesRendered += 1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 108
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.9989006519317627,
0.36093461513519287,
0.00016414349374826998,
0.001877978560514748,
0.45983582735061646
] |
{
"id": 4,
"code_window": [
" expect(RootComponent.timesMounted).toEqual(1);\n",
" });\n",
"\n",
" it('should not render component if not at plugin path', async () => {\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" class RootComponent extends Component<AppRootProps> {\n",
" static timesRendered = 0;\n",
" render() {\n",
" RootComponent.timesRendered += 1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 108
} | var config = {
defaults: {
concurrency: 1,
runners: ['axe'],
useIncognitoBrowserContext: false,
standard: 'WCAG2AA',
chromeLaunchConfig: {
args: ['--no-sandbox'],
},
// see https://github.com/grafana/grafana/pull/41693#issuecomment-979921463 for context
// on why we're ignoring singleValue/react-select-*-placeholder elements
hideElements: '#updateVersion, [class*="-singleValue"], [id^="react-select-"][id$="-placeholder"]',
},
urls: [
{
url: '${HOST}/login',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/login', //skip password and login
actions: [
"wait for element input[name='user'] to be added",
"set field input[name='user'] to admin",
"set field input[name='password'] to admin",
"click element button[aria-label='Login button']",
"wait for element [aria-label='Skip change password button'] to be visible",
],
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/?orgId=1',
wait: 500,
},
{
url: '${HOST}/d/O6f11TZWk/panel-tests-bar-gauge',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/d/O6f11TZWk/panel-tests-bar-gauge?orgId=1&editview=settings',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/?orgId=1&search=open',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/alerting/list',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/datasources',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/org/users',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/org/teams',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/plugins',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/org',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/org/apikeys',
wait: 500,
rootElement: '.main-view',
},
{
url: '${HOST}/dashboards',
wait: 500,
rootElement: '.main-view',
},
],
};
function myPa11yCiConfiguration(urls, defaults) {
const HOST_SERVER = process.env.HOST || 'localhost';
const PORT_SERVER = process.env.PORT || '3001';
for (var idx = 0; idx < urls.length; idx++) {
urls[idx] = { ...urls[idx], url: urls[idx].url.replace('${HOST}', `${HOST_SERVER}:${PORT_SERVER}`) };
}
return {
defaults: defaults,
urls: urls,
};
}
module.exports = myPa11yCiConfiguration(config.urls, config.defaults);
| .pa11yci.conf.js | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017260463209822774,
0.00017015229968819767,
0.00016703187429811805,
0.0001705997419776395,
0.0000015503061376875849
] |
{
"id": 4,
"code_window": [
" expect(RootComponent.timesMounted).toEqual(1);\n",
" });\n",
"\n",
" it('should not render component if not at plugin path', async () => {\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" class RootComponent extends Component<AppRootProps> {\n",
" static timesRendered = 0;\n",
" render() {\n",
" RootComponent.timesRendered += 1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 108
} | ---
aliases:
- /docs/grafana/latest/developers/contribute/
keywords:
- grafana
- documentation
- developers
- resources
title: Contribute to Grafana
weight: 300
---
# Contribute to Grafana
This page lists resources for developers who want to contribute to the Grafana software ecosystem or build plugins for Grafana.
## General resources
These resources are useful for all developers.
- [Contributing to Grafana](https://github.com/grafana/grafana/blob/main/CONTRIBUTING.md): Start here to learn how you can contribute your skills to make Grafana even better.
- [Developer guide](https://github.com/grafana/grafana/blob/main/contribute/developer-guide.md): A guide to help you get started developing Grafana software, includes instructions for how to configure Grafana for development.
- [Contributing to documentation](https://github.com/grafana/grafana/blob/main/contribute/documentation): A guide to help you contribute to Grafana documentation, includes links to beginner-friendly issues.
- [Architecture guides](https://github.com/grafana/grafana/tree/main/contribute/architecture): These guides explain Grafana’s background architecture.
- [Create a pull request](https://github.com/grafana/grafana/blob/main/contribute/create-pull-request.md): A guide for new contributors about how to create your first Grafana pull request.
- [REST APIs](https://grafana.com/docs/grafana/next/developers/http_api) allow you to interact programmatically with the Grafana backend.
## Best practices and style
Our [style guides](https://github.com/grafana/grafana/tree/main/contribute/style-guides) outline Grafana style for frontend, backend, documentation, and more, including best practices. Please read through them before you start editing or coding!
- [Backend style guide](https://github.com/grafana/grafana/blob/main/contribute/style-guides/backend.md) explains how we want to write Go code in the future.
- [Documentation style guide](https://github.com/grafana/grafana/blob/main/contribute/style-guides/documentation-style-guide.md) applies to all documentation created for Grafana products.
- [End to end test framework](https://github.com/grafana/grafana/blob/main/contribute/style-guides/e2e.md) provides guidance for Grafana e2e tests.
- [Frontend style guide](https://github.com/grafana/grafana/blob/main/contribute/style-guides/frontend.md) provides rules and guidance on developing in React for Grafana.
- [Redux framework](https://github.com/grafana/grafana/blob/main/contribute/style-guides/redux.md) explains how Grafana handles Redux boilerplate code.
- [Styling Grafana](https://github.com/grafana/grafana/blob/main/contribute/style-guides/styling.md) expands on styling React components with Emotion.
- [Theming Grafana](https://github.com/grafana/grafana/blob/main/contribute/style-guides/themes.md) explains how to use themes and ThemeContext in Grafana code.
| docs/sources/developers/contribute.md | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.0001708807540126145,
0.0001679429115029052,
0.00016156212950590998,
0.00016915040032472461,
0.000003455453452261281
] |
{
"id": 4,
"code_window": [
" expect(RootComponent.timesMounted).toEqual(1);\n",
" });\n",
"\n",
" it('should not render component if not at plugin path', async () => {\n",
" getPluginSettingsMock.mockResolvedValue(\n",
" getMockPlugin({\n",
" type: PluginType.app,\n",
" enabled: true,\n",
" })\n",
" );\n",
"\n",
" class RootComponent extends Component<AppRootProps> {\n",
" static timesRendered = 0;\n",
" render() {\n",
" RootComponent.timesRendered += 1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" getPluginSettingsMock.mockResolvedValue(pluginMeta);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 108
} | import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import { RichHistoryQuery } from '../../types';
import { backendSrv } from '../services/backend_srv';
import { RichHistoryLocalStorageDTO } from './RichHistoryLocalStorage';
import { fromDTO, toDTO } from './localStorageConverter';
const dsMock = new DatasourceSrv();
dsMock.init(
{
// @ts-ignore
'name-of-dev-test': { uid: 'dev-test', name: 'name-of-dev-test' },
},
''
);
jest.mock('@grafana/runtime', () => ({
...jest.requireActual('@grafana/runtime'),
getBackendSrv: () => backendSrv,
getDataSourceSrv: () => dsMock,
}));
const validRichHistory: RichHistoryQuery = {
comment: 'comment',
createdAt: 1,
datasourceName: 'name-of-dev-test',
datasourceUid: 'dev-test',
id: '1',
queries: [{ refId: 'A' }],
starred: true,
};
const validDTO: RichHistoryLocalStorageDTO = {
comment: 'comment',
datasourceName: 'name-of-dev-test',
queries: [{ refId: 'A' }],
starred: true,
ts: 1,
};
describe('LocalStorage converted', () => {
it('converts RichHistoryQuery to local storage DTO', () => {
expect(toDTO(validRichHistory)).toMatchObject(validDTO);
});
it('throws an error when data source for RichHistory does not exist to avoid saving invalid items', () => {
const invalidRichHistory = { ...validRichHistory, datasourceUid: 'invalid' };
expect(() => {
toDTO(invalidRichHistory);
}).toThrow();
});
it('converts DTO to RichHistoryQuery', () => {
expect(fromDTO(validDTO)).toMatchObject(validRichHistory);
});
it('uses empty uid when datasource does not exist for a DTO to fail gracefully for queries from removed datasources', () => {
const invalidDto = { ...validDTO, datasourceName: 'removed' };
expect(fromDTO(invalidDto)).toMatchObject({
...validRichHistory,
datasourceName: 'removed',
datasourceUid: '',
});
});
});
| public/app/core/history/localStorageConverter.test.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017455198394600302,
0.00017226363706868142,
0.0001698626729194075,
0.00017270637908950448,
0.000001579148033670208
] |
{
"id": 5,
"code_window": [
" return <p>my great component</p>;\n",
" }\n",
" }\n",
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n",
"\n",
" renderUnderRouter();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 124
} | // Libraries
import React, { Component } from 'react';
import { createHtmlPortalNode, InPortal, OutPortal, HtmlPortalNode } from 'react-reverse-portal';
import { AppEvents, AppPlugin, AppPluginMeta, KeyValue, NavModel, PluginType } from '@grafana/data';
import { getNotFoundNav, getWarningNav, getExceptionNav } from 'app/angular/services/nav_model_srv';
import { Page } from 'app/core/components/Page/Page';
import PageLoader from 'app/core/components/PageLoader/PageLoader';
import { appEvents } from 'app/core/core';
import { GrafanaRouteComponentProps } from 'app/core/navigation/types';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
interface RouteParams {
pluginId: string;
}
interface Props extends GrafanaRouteComponentProps<RouteParams> {}
interface State {
loading: boolean;
portalNode: HtmlPortalNode;
plugin?: AppPlugin | null;
nav?: NavModel;
}
export function getAppPluginPageError(meta: AppPluginMeta) {
if (!meta) {
return 'Unknown Plugin';
}
if (meta.type !== PluginType.app) {
return 'Plugin must be an app';
}
if (!meta.enabled) {
return 'Application Not Enabled';
}
return null;
}
class AppRootPage extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
loading: true,
portalNode: createHtmlPortalNode(),
};
}
shouldComponentUpdate(nextProps: Props) {
return nextProps.location.pathname.startsWith('/a/');
}
async loadPluginSettings() {
const { params } = this.props.match;
try {
const app = await getPluginSettings(params.pluginId).then((info) => {
const error = getAppPluginPageError(info);
if (error) {
appEvents.emit(AppEvents.alertError, [error]);
this.setState({ nav: getWarningNav(error) });
return null;
}
return importAppPlugin(info);
});
this.setState({ plugin: app, loading: false, nav: undefined });
} catch (err) {
this.setState({
plugin: null,
loading: false,
nav: process.env.NODE_ENV === 'development' ? getExceptionNav(err) : getNotFoundNav(),
});
}
}
componentDidMount() {
this.loadPluginSettings();
}
componentDidUpdate(prevProps: Props) {
const { params } = this.props.match;
if (prevProps.match.params.pluginId !== params.pluginId) {
this.setState({ loading: true, plugin: null });
this.loadPluginSettings();
}
}
onNavChanged = (nav: NavModel) => {
this.setState({ nav });
};
render() {
const { loading, plugin, nav, portalNode } = this.state;
if (plugin && !plugin.root) {
// TODO? redirect to plugin page?
return <div>No Root App</div>;
}
return (
<>
<InPortal node={portalNode}>
{plugin && plugin.root && (
<plugin.root
meta={plugin.meta}
basename={this.props.match.url}
onNavChanged={this.onNavChanged}
query={this.props.queryParams as KeyValue}
path={this.props.location.pathname}
/>
)}
</InPortal>
{nav ? (
<Page navModel={nav}>
<Page.Contents isLoading={loading}>
<OutPortal node={portalNode} />
</Page.Contents>
</Page>
) : (
<Page>
<OutPortal node={portalNode} />
{loading && <PageLoader />}
</Page>
)}
</>
);
}
}
export default AppRootPage;
| public/app/features/plugins/components/AppRootPage.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.9412549138069153,
0.06793639808893204,
0.00016520291683264077,
0.00017689692322164774,
0.2422184944152832
] |
{
"id": 5,
"code_window": [
" return <p>my great component</p>;\n",
" }\n",
" }\n",
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n",
"\n",
" renderUnderRouter();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 124
} | import { PanelPlugin, PanelPluginMeta } from '@grafana/data';
import config from 'app/core/config';
import { getPanelPluginLoadError } from '../panel/components/PanelPluginError';
import { importPluginModule } from './plugin_loader';
const promiseCache: Record<string, Promise<PanelPlugin>> = {};
const panelPluginCache: Record<string, PanelPlugin> = {};
export function importPanelPlugin(id: string): Promise<PanelPlugin> {
const loaded = promiseCache[id];
if (loaded) {
return loaded;
}
const meta = config.panels[id];
if (!meta) {
throw new Error(`Plugin ${id} not found`);
}
promiseCache[id] = getPanelPlugin(meta);
return promiseCache[id];
}
export function importPanelPluginFromMeta(meta: PanelPluginMeta): Promise<PanelPlugin> {
return getPanelPlugin(meta);
}
export function syncGetPanelPlugin(id: string): PanelPlugin | undefined {
return panelPluginCache[id];
}
function getPanelPlugin(meta: PanelPluginMeta): Promise<PanelPlugin> {
return importPluginModule(meta.module, meta.info?.version)
.then((pluginExports) => {
if (pluginExports.plugin) {
return pluginExports.plugin as PanelPlugin;
} else if (pluginExports.PanelCtrl) {
const plugin = new PanelPlugin(null);
plugin.angularPanelCtrl = pluginExports.PanelCtrl;
return plugin;
}
throw new Error('missing export: plugin or PanelCtrl');
})
.then((plugin) => {
plugin.meta = meta;
panelPluginCache[meta.id] = plugin;
return plugin;
})
.catch((err) => {
// TODO, maybe a different error plugin
console.warn('Error loading panel plugin: ' + meta.id, err);
return getPanelPluginLoadError(meta, err);
});
}
| public/app/features/plugins/importPanelPlugin.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.9596585035324097,
0.3060174286365509,
0.00017287129594478756,
0.0002892033662647009,
0.43312403559684753
] |
{
"id": 5,
"code_window": [
" return <p>my great component</p>;\n",
" }\n",
" }\n",
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n",
"\n",
" renderUnderRouter();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 124
} | package remotecache
import (
"context"
"time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/sqlstore"
)
var getTime = time.Now
const databaseCacheType = "database"
type databaseCache struct {
SQLStore *sqlstore.SQLStore
log log.Logger
}
func newDatabaseCache(sqlstore *sqlstore.SQLStore) *databaseCache {
dc := &databaseCache{
SQLStore: sqlstore,
log: log.New("remotecache.database"),
}
return dc
}
func (dc *databaseCache) Run(ctx context.Context) error {
ticker := time.NewTicker(time.Minute * 10)
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
dc.internalRunGC()
}
}
}
func (dc *databaseCache) internalRunGC() {
err := dc.SQLStore.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
now := getTime().Unix()
sql := `DELETE FROM cache_data WHERE (? - created_at) >= expires AND expires <> 0`
_, err := session.Exec(sql, now)
return err
})
if err != nil {
dc.log.Error("failed to run garbage collect", "error", err)
}
}
func (dc *databaseCache) Get(ctx context.Context, key string) (interface{}, error) {
cacheHit := CacheData{}
session := dc.SQLStore.NewSession(ctx)
defer session.Close()
exist, err := session.Where("cache_key= ?", key).Get(&cacheHit)
if err != nil {
return nil, err
}
if !exist {
return nil, ErrCacheItemNotFound
}
if cacheHit.Expires > 0 {
existedButExpired := getTime().Unix()-cacheHit.CreatedAt >= cacheHit.Expires
if existedButExpired {
err = dc.Delete(ctx, key) // ignore this error since we will return `ErrCacheItemNotFound` anyway
if err != nil {
dc.log.Debug("Deletion of expired key failed: %v", err)
}
return nil, ErrCacheItemNotFound
}
}
item := &cachedItem{}
if err = decodeGob(cacheHit.Data, item); err != nil {
return nil, err
}
return item.Val, nil
}
func (dc *databaseCache) Set(ctx context.Context, key string, value interface{}, expire time.Duration) error {
item := &cachedItem{Val: value}
data, err := encodeGob(item)
if err != nil {
return err
}
session := dc.SQLStore.NewSession(context.Background())
defer session.Close()
var expiresInSeconds int64
if expire != 0 {
expiresInSeconds = int64(expire) / int64(time.Second)
}
// attempt to insert the key
sql := `INSERT INTO cache_data (cache_key,data,created_at,expires) VALUES(?,?,?,?)`
_, err = session.Exec(sql, key, data, getTime().Unix(), expiresInSeconds)
if err != nil {
// attempt to update if a unique constrain violation or a deadlock (for MySQL) occurs
// if the update fails propagate the error
// which eventually will result in a key that is not finally set
// but since it's a cache does not harm a lot
if dc.SQLStore.Dialect.IsUniqueConstraintViolation(err) || dc.SQLStore.Dialect.IsDeadlock(err) {
sql := `UPDATE cache_data SET data=?, created_at=?, expires=? WHERE cache_key=?`
_, err = session.Exec(sql, data, getTime().Unix(), expiresInSeconds, key)
if err != nil && dc.SQLStore.Dialect.IsDeadlock(err) {
// most probably somebody else is upserting the key
// so it is safe enough not to propagate this error
return nil
}
}
}
return err
}
func (dc *databaseCache) Delete(ctx context.Context, key string) error {
return dc.SQLStore.WithDbSession(ctx, func(session *sqlstore.DBSession) error {
sql := "DELETE FROM cache_data WHERE cache_key=?"
_, err := session.Exec(sql, key)
return err
})
}
// CacheData is the struct representing the table in the database
type CacheData struct {
CacheKey string
Data []byte
Expires int64
CreatedAt int64
}
| pkg/infra/remotecache/database_storage.go | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.0001800398458726704,
0.0001736392150633037,
0.000164692202815786,
0.00017450838640797883,
0.000003865618509735214
] |
{
"id": 5,
"code_window": [
" return <p>my great component</p>;\n",
" }\n",
" }\n",
"\n",
" const plugin = new AppPlugin();\n",
" plugin.root = RootComponent;\n",
"\n",
" importAppPluginMock.mockResolvedValue(plugin);\n",
"\n",
" renderUnderRouter();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" plugin.meta = pluginMeta;\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "add",
"edit_start_line_idx": 124
} | import { css } from '@emotion/css';
import React, { useEffect, useMemo, useState } from 'react';
import { useFormContext, FieldErrors } from 'react-hook-form';
import { GrafanaTheme2, SelectableValue } from '@grafana/data';
import { Alert, Button, Field, InputControl, Select, useStyles2 } from '@grafana/ui';
import { NotifierDTO } from 'app/types';
import { useUnifiedAlertingSelector } from '../../../hooks/useUnifiedAlertingSelector';
import { ChannelValues, CommonSettingsComponentType } from '../../../types/receiver-form';
import { ChannelOptions } from './ChannelOptions';
import { CollapsibleSection } from './CollapsibleSection';
interface Props<R> {
defaultValues: R;
pathPrefix: string;
notifiers: NotifierDTO[];
onDuplicate: () => void;
onTest?: () => void;
commonSettingsComponent: CommonSettingsComponentType;
secureFields?: Record<string, boolean>;
errors?: FieldErrors<R>;
onDelete?: () => void;
isEditable?: boolean;
isTestable?: boolean;
}
export function ChannelSubForm<R extends ChannelValues>({
defaultValues,
pathPrefix,
onDuplicate,
onDelete,
onTest,
notifiers,
errors,
secureFields,
commonSettingsComponent: CommonSettingsComponent,
isEditable = true,
isTestable,
}: Props<R>): JSX.Element {
const styles = useStyles2(getStyles);
const name = (fieldName: string) => `${pathPrefix}${fieldName}`;
const { control, watch, register, trigger, formState, setValue } = useFormContext();
const selectedType = watch(name('type')) ?? defaultValues.type; // nope, setting "default" does not work at all.
const { loading: testingReceiver } = useUnifiedAlertingSelector((state) => state.testReceivers);
useEffect(() => {
register(`${pathPrefix}.__id`);
/* Need to manually register secureFields or else they'll
be lost when testing a contact point */
register(`${pathPrefix}.secureFields`);
}, [register, pathPrefix]);
const [_secureFields, setSecureFields] = useState(secureFields ?? {});
const onResetSecureField = (key: string) => {
if (_secureFields[key]) {
const updatedSecureFields = { ...secureFields };
delete updatedSecureFields[key];
setSecureFields(updatedSecureFields);
setValue(`${pathPrefix}.secureFields`, updatedSecureFields);
}
};
const typeOptions = useMemo(
(): SelectableValue[] =>
notifiers
.map(({ name, type }) => ({
label: name,
value: type,
}))
.sort((a, b) => a.label.localeCompare(b.label)),
[notifiers]
);
const handleTest = async () => {
await trigger();
const isValid = Object.keys(formState.errors).length === 0;
if (isValid && onTest) {
onTest();
}
};
const notifier = notifiers.find(({ type }) => type === selectedType);
// if there are mandatory options defined, optional options will be hidden by a collapse
// if there aren't mandatory options, all options will be shown without collapse
const mandatoryOptions = notifier?.options.filter((o) => o.required);
const optionalOptions = notifier?.options.filter((o) => !o.required);
const contactPointTypeInputId = `contact-point-type-${pathPrefix}`;
return (
<div className={styles.wrapper} data-testid="item-container">
<div className={styles.topRow}>
<div>
<Field label="Contact point type" htmlFor={contactPointTypeInputId} data-testid={`${pathPrefix}type`}>
<InputControl
name={name('type')}
defaultValue={defaultValues.type}
render={({ field: { ref, onChange, ...field } }) => (
<Select
disabled={!isEditable}
inputId={contactPointTypeInputId}
{...field}
width={37}
options={typeOptions}
onChange={(value) => onChange(value?.value)}
/>
)}
control={control}
rules={{ required: true }}
/>
</Field>
</div>
<div className={styles.buttons}>
{isTestable && onTest && (
<Button
disabled={testingReceiver}
size="xs"
variant="secondary"
type="button"
onClick={() => handleTest()}
icon={testingReceiver ? 'fa fa-spinner' : 'message'}
>
Test
</Button>
)}
{isEditable && (
<>
<Button size="xs" variant="secondary" type="button" onClick={() => onDuplicate()} icon="copy">
Duplicate
</Button>
{onDelete && (
<Button
data-testid={`${pathPrefix}delete-button`}
size="xs"
variant="secondary"
type="button"
onClick={() => onDelete()}
icon="trash-alt"
>
Delete
</Button>
)}
</>
)}
</div>
</div>
{notifier && (
<div className={styles.innerContent}>
<ChannelOptions<R>
defaultValues={defaultValues}
selectedChannelOptions={mandatoryOptions?.length ? mandatoryOptions! : optionalOptions!}
secureFields={_secureFields}
errors={errors}
onResetSecureField={onResetSecureField}
pathPrefix={pathPrefix}
readOnly={!isEditable}
/>
{!!(mandatoryOptions?.length && optionalOptions?.length) && (
<CollapsibleSection label={`Optional ${notifier.name} settings`}>
{notifier.info !== '' && (
<Alert title="" severity="info">
{notifier.info}
</Alert>
)}
<ChannelOptions<R>
defaultValues={defaultValues}
selectedChannelOptions={optionalOptions!}
secureFields={_secureFields}
onResetSecureField={onResetSecureField}
errors={errors}
pathPrefix={pathPrefix}
readOnly={!isEditable}
/>
</CollapsibleSection>
)}
<CollapsibleSection label="Notification settings">
<CommonSettingsComponent pathPrefix={pathPrefix} readOnly={!isEditable} />
</CollapsibleSection>
</div>
)}
</div>
);
}
const getStyles = (theme: GrafanaTheme2) => ({
buttons: css`
& > * + * {
margin-left: ${theme.spacing(1)};
}
`,
innerContent: css`
max-width: 536px;
`,
wrapper: css`
margin: ${theme.spacing(2, 0)};
padding: ${theme.spacing(1)};
border: solid 1px ${theme.colors.border.medium};
border-radius: ${theme.shape.borderRadius(1)};
max-width: ${theme.breakpoints.values.xl}${theme.breakpoints.unit};
`,
topRow: css`
display: flex;
flex-direction: row;
justify-content: space-between;
`,
channelSettingsHeader: css`
margin-top: ${theme.spacing(2)};
`,
});
| public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.tsx | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017806148389354348,
0.00017385624232701957,
0.00016762572340667248,
0.00017370391287840903,
0.000002556798335717758
] |
{
"id": 6,
"code_window": [
" expect(await screen.findByText('my great component')).toBeVisible();\n",
"\n",
" // renders the first time\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/foo');\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 133
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.994955837726593,
0.06731534749269485,
0.00016457526362501085,
0.00023588516341987997,
0.24792549014091492
] |
{
"id": 6,
"code_window": [
" expect(await screen.findByText('my great component')).toBeVisible();\n",
"\n",
" // renders the first time\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/foo');\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 133
} | import { NotificationChannelDTO } from '../../../types';
import { transformSubmitData } from './notificationChannels';
const basicFormData: NotificationChannelDTO = {
id: 1,
uid: 'pX7fbbHGk',
name: 'Pete discord',
type: {
value: 'discord',
label: 'Discord',
type: 'discord',
name: 'Discord',
heading: 'Discord settings',
description: 'Sends notifications to Discord',
info: '',
options: [
{
element: 'input',
inputType: 'text',
label: 'Message Content',
description: 'Mention a group using @ or a user using <@ID> when notifying in a channel',
placeholder: '',
propertyName: 'content',
selectOptions: null,
showWhen: { field: '', is: '' },
required: false,
validationRule: '',
secure: false,
},
{
element: 'input',
inputType: 'text',
label: 'Webhook URL',
description: '',
placeholder: 'Discord webhook URL',
propertyName: 'url',
selectOptions: null,
showWhen: { field: '', is: '' },
required: true,
validationRule: '',
secure: false,
},
],
typeName: 'discord',
},
isDefault: false,
sendReminder: false,
disableResolveMessage: false,
frequency: '',
created: '2020-08-24T10:46:43+02:00',
updated: '2020-09-02T14:08:27+02:00',
settings: {
url: 'https://discordapp.com/api/webhooks/',
uploadImage: true,
content: '',
autoResolve: true,
httpMethod: 'POST',
severity: 'critical',
},
secureFields: {},
secureSettings: {},
};
const selectFormData: NotificationChannelDTO = {
id: 23,
uid: 'BxEN9rNGk',
name: 'Webhook',
type: {
value: 'webhook',
label: 'webhook',
type: 'webhook',
name: 'webhook',
heading: 'Webhook settings',
description: 'Sends HTTP POST request to a URL',
info: '',
options: [
{
element: 'input',
inputType: 'text',
label: 'Url',
description: '',
placeholder: '',
propertyName: 'url',
selectOptions: null,
showWhen: { field: '', is: '' },
required: true,
validationRule: '',
secure: false,
},
{
element: 'select',
inputType: '',
label: 'Http Method',
description: '',
placeholder: '',
propertyName: 'httpMethod',
selectOptions: [
{ value: 'POST', label: 'POST' },
{ value: 'PUT', label: 'PUT' },
],
showWhen: { field: '', is: '' },
required: false,
validationRule: '',
secure: false,
},
{
element: 'input',
inputType: 'text',
label: 'Username',
description: '',
placeholder: '',
propertyName: 'username',
selectOptions: null,
showWhen: { field: '', is: '' },
required: false,
validationRule: '',
secure: false,
},
{
element: 'input',
inputType: 'password',
label: 'Password',
description: '',
placeholder: '',
propertyName: 'password',
selectOptions: null,
showWhen: { field: '', is: '' },
required: false,
validationRule: '',
secure: true,
},
],
typeName: 'webhook',
},
isDefault: false,
sendReminder: false,
disableResolveMessage: false,
frequency: '',
created: '2020-08-28T10:47:37+02:00',
updated: '2020-09-03T09:37:21+02:00',
settings: {
autoResolve: true,
httpMethod: 'POST',
password: '',
severity: 'critical',
uploadImage: true,
url: 'http://asdf',
username: 'asdf',
},
secureFields: { password: true },
secureSettings: {},
};
describe('Transform submit data', () => {
it('basic transform', () => {
const expected = {
id: 1,
name: 'Pete discord',
type: 'discord',
sendReminder: false,
disableResolveMessage: false,
frequency: '15m',
settings: {
uploadImage: true,
autoResolve: true,
httpMethod: 'POST',
severity: 'critical',
url: 'https://discordapp.com/api/webhooks/',
content: '',
},
secureSettings: {},
secureFields: {},
isDefault: false,
uid: 'pX7fbbHGk',
created: '2020-08-24T10:46:43+02:00',
updated: '2020-09-02T14:08:27+02:00',
};
expect(transformSubmitData(basicFormData)).toEqual(expected);
});
it('should transform form data with selects', () => {
const expected = {
created: '2020-08-28T10:47:37+02:00',
disableResolveMessage: false,
frequency: '15m',
id: 23,
isDefault: false,
name: 'Webhook',
secureFields: { password: true },
secureSettings: {},
sendReminder: false,
settings: {
autoResolve: true,
httpMethod: 'POST',
password: '',
severity: 'critical',
uploadImage: true,
url: 'http://asdf',
username: 'asdf',
},
type: 'webhook',
uid: 'BxEN9rNGk',
updated: '2020-09-03T09:37:21+02:00',
};
expect(transformSubmitData(selectFormData)).toEqual(expected);
});
});
| public/app/features/alerting/utils/notificationChannel.test.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017914509226102382,
0.00017664664483163506,
0.00016986510308925062,
0.0001773166295606643,
0.0000023779205093887867
] |
{
"id": 6,
"code_window": [
" expect(await screen.findByText('my great component')).toBeVisible();\n",
"\n",
" // renders the first time\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/foo');\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 133
} | package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/infra/kvstore"
"github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/setting"
)
// This is to ensure that the interface contract is held by the implementation
func Test_InterfaceContractValidity(t *testing.T) {
newUsageStats := func() usagestats.Service {
return &UsageStats{}
}
v, ok := newUsageStats().(*UsageStats)
assert.NotNil(t, v)
assert.True(t, ok)
}
func TestMetrics(t *testing.T) {
const metricName = "stats.test_metric.count"
sqlStore := mockstore.NewSQLStoreMock()
uss := createService(t, setting.Cfg{}, sqlStore, false)
uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) {
return map[string]interface{}{metricName: 1}, nil
})
err := uss.sendUsageStats(context.Background())
require.NoError(t, err)
t.Run("Given reporting not enabled and sending usage stats", func(t *testing.T) {
origSendUsageStats := sendUsageStats
t.Cleanup(func() {
sendUsageStats = origSendUsageStats
})
statsSent := false
sendUsageStats = func(uss *UsageStats, b *bytes.Buffer) {
statsSent = true
}
uss.Cfg.ReportingEnabled = false
err := uss.sendUsageStats(context.Background())
require.NoError(t, err)
require.False(t, statsSent)
})
t.Run("Given reporting enabled, stats should be gathered and sent to HTTP endpoint", func(t *testing.T) {
origCfg := uss.Cfg
t.Cleanup(func() {
uss.Cfg = origCfg
})
uss.Cfg = &setting.Cfg{
ReportingEnabled: true,
BuildVersion: "5.0.0",
AnonymousEnabled: true,
BasicAuthEnabled: true,
LDAPEnabled: true,
AuthProxyEnabled: true,
Packaging: "deb",
ReportingDistributor: "hosted-grafana",
}
ch := make(chan httpResp)
ticker := time.NewTicker(2 * time.Second)
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
buf, err := io.ReadAll(r.Body)
if err != nil {
t.Logf("Fake HTTP handler received an error: %s", err.Error())
ch <- httpResp{
err: err,
}
return
}
require.NoError(t, err, "Failed to read response body, err=%v", err)
t.Logf("Fake HTTP handler received a response")
ch <- httpResp{
responseBuffer: bytes.NewBuffer(buf),
req: r,
}
}))
t.Cleanup(ts.Close)
t.Cleanup(func() {
close(ch)
})
usageStatsURL = ts.URL
err := uss.sendUsageStats(context.Background())
require.NoError(t, err)
// Wait for fake HTTP server to receive a request
var resp httpResp
select {
case resp = <-ch:
require.NoError(t, resp.err, "Fake server experienced an error")
case <-ticker.C:
t.Fatalf("Timed out waiting for HTTP request")
}
t.Logf("Received response from fake HTTP server: %+v\n", resp)
assert.NotNil(t, resp.req)
assert.Equal(t, http.MethodPost, resp.req.Method)
assert.Equal(t, "application/json", resp.req.Header.Get("Content-Type"))
require.NotNil(t, resp.responseBuffer)
j := make(map[string]interface{})
err = json.Unmarshal(resp.responseBuffer.Bytes(), &j)
require.NoError(t, err)
assert.Equal(t, "5_0_0", j["version"])
assert.Equal(t, runtime.GOOS, j["os"])
assert.Equal(t, runtime.GOARCH, j["arch"])
usageId := uss.GetUsageStatsId(context.Background())
assert.NotEmpty(t, usageId)
metrics, ok := j["metrics"].(map[string]interface{})
require.True(t, ok)
assert.EqualValues(t, 1, metrics[metricName])
})
}
func TestGetUsageReport_IncludesMetrics(t *testing.T) {
sqlStore := mockstore.NewSQLStoreMock()
uss := createService(t, setting.Cfg{}, sqlStore, true)
metricName := "stats.test_metric.count"
uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) {
return map[string]interface{}{metricName: 1}, nil
})
report, err := uss.GetUsageReport(context.Background())
require.NoError(t, err, "Expected no error")
metric := report.Metrics[metricName]
assert.Equal(t, 1, metric)
}
func TestRegisterMetrics(t *testing.T) {
const goodMetricName = "stats.test_external_metric.count"
sqlStore := mockstore.NewSQLStoreMock()
uss := createService(t, setting.Cfg{}, sqlStore, false)
metrics := map[string]interface{}{"stats.test_metric.count": 1, "stats.test_metric_second.count": 2}
uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) {
return map[string]interface{}{goodMetricName: 1}, nil
})
{
extMetrics, err := uss.externalMetrics[0](context.Background())
require.NoError(t, err)
assert.Equal(t, map[string]interface{}{goodMetricName: 1}, extMetrics)
}
uss.gatherMetrics(context.Background(), metrics)
assert.Equal(t, 1, metrics[goodMetricName])
metricsCount := len(metrics)
t.Run("do not add metrics that return an error when fetched", func(t *testing.T) {
const badMetricName = "stats.test_external_metric_error.count"
uss.RegisterMetricsFunc(func(context.Context) (map[string]interface{}, error) {
return map[string]interface{}{badMetricName: 1}, errors.New("some error")
})
uss.gatherMetrics(context.Background(), metrics)
extErrorMetric := metrics[badMetricName]
extMetric := metrics[goodMetricName]
require.Nil(t, extErrorMetric, "Invalid metric should not be added")
assert.Equal(t, 1, extMetric)
assert.Len(t, metrics, metricsCount, "Expected same number of metrics before and after collecting bad metric")
assert.EqualValues(t, 1, metrics["stats.usagestats.debug.collect.error.count"])
})
}
type fakePluginStore struct {
plugins.Store
plugins map[string]plugins.PluginDTO
}
func (pr fakePluginStore) Plugin(_ context.Context, pluginID string) (plugins.PluginDTO, bool) {
p, exists := pr.plugins[pluginID]
return p, exists
}
func (pr fakePluginStore) Plugins(_ context.Context, pluginTypes ...plugins.Type) []plugins.PluginDTO {
var result []plugins.PluginDTO
for _, v := range pr.plugins {
for _, t := range pluginTypes {
if v.Type == t {
result = append(result, v)
}
}
}
return result
}
type httpResp struct {
req *http.Request
responseBuffer *bytes.Buffer
err error
}
func createService(t *testing.T, cfg setting.Cfg, sqlStore sqlstore.Store, withDB bool) *UsageStats {
t.Helper()
if withDB {
sqlStore = sqlstore.InitTestDB(t)
}
return ProvideService(
&cfg,
&fakePluginStore{},
kvstore.ProvideService(sqlStore),
routing.NewRouteRegister(),
)
}
| pkg/infra/usagestats/service/usage_stats_test.go | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00022724347945768386,
0.00017724391364026815,
0.00016782803868409246,
0.00017627456691116095,
0.000010660254702088423
] |
{
"id": 6,
"code_window": [
" expect(await screen.findByText('my great component')).toBeVisible();\n",
"\n",
" // renders the first time\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/foo');\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 133
} | package commands
import (
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/utils"
)
// listRemoteCommand prints out all plugins in the remote repo with latest version supported on current platform.
// If there are no supported versions for plugin it is skipped.
func (cmd Command) listRemoteCommand(c utils.CommandLine) error {
plugin, err := cmd.Client.ListAllPlugins(c.PluginRepoURL())
if err != nil {
return err
}
for _, p := range plugin.Plugins {
plugin := p
if len(plugin.Versions) > 0 {
ver := latestSupportedVersion(&plugin)
if ver != nil {
logger.Infof("id: %v version: %s\n", plugin.ID, ver.Version)
}
}
}
return nil
}
| pkg/cmd/grafana-cli/commands/listremote_command.go | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.0001778531150193885,
0.00017576779646333307,
0.00017198134446516633,
0.00017746891535352916,
0.0000026820127914106706
] |
{
"id": 7,
"code_window": [
" locationService.push('/foo');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 139
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.9682661890983582,
0.06694432348012924,
0.00016248862084466964,
0.0002778436173684895,
0.24096864461898804
] |
{
"id": 7,
"code_window": [
" locationService.push('/foo');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 139
} | #!/bin/bash
set -eo pipefail
source ./common.sh
#
# No longer required, but useful to keep just in case we want to deploy
# changes in toolkit directly to the docker image
#
if [ -n "$INCLUDE_TOOLKIT" ]; then
/bin/rm -rfv install/grafana-toolkit
mkdir -pv install/grafana-toolkit
cp -rv ../../bin install/grafana-toolkit
cp -rv ../../src install/grafana-toolkit
cp -v ../../package.json install/grafana-toolkit
cp -v ../../tsconfig.json install/grafana-toolkit
fi
docker build -t ${DOCKER_IMAGE_NAME} .
docker push $DOCKER_IMAGE_NAME
[ -n "$INCLUDE_TOOLKIT" ] && /bin/rm -rfv install/grafana-toolkit
| packages/grafana-toolkit/docker/grafana-plugin-ci-alpine/build.sh | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017484198906458914,
0.00017097638919949532,
0.000167828518897295,
0.0001702586596366018,
0.0000029078678380756173
] |
{
"id": 7,
"code_window": [
" locationService.push('/foo');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 139
} | import { css } from '@emotion/css';
import React from 'react';
import { PluginErrorCode, PluginSignatureStatus } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { HorizontalGroup, InfoBox, List, PluginSignatureBadge, useTheme } from '@grafana/ui';
import { useGetErrors, useFetchStatus } from '../admin/state/hooks';
export function PluginsErrorsInfo(): React.ReactElement | null {
const errors = useGetErrors();
const { isLoading } = useFetchStatus();
const theme = useTheme();
if (isLoading || errors.length === 0) {
return null;
}
return (
<InfoBox
aria-label={selectors.pages.PluginsList.signatureErrorNotice}
severity="warning"
urlTitle="Read more about plugin signing"
url="https://grafana.com/docs/grafana/latest/plugins/plugin-signatures/"
>
<div>
<p>
Unsigned plugins were found during plugin initialization. Grafana Labs cannot guarantee the integrity of these
plugins. We recommend only using signed plugins.
</p>
The following plugins are disabled and not shown in the list below:
<List
items={errors}
className={css`
list-style-type: circle;
`}
renderItem={(error) => (
<div
className={css`
margin-top: ${theme.spacing.sm};
`}
>
<HorizontalGroup spacing="sm" justify="flex-start" align="center">
<strong>{error.pluginId}</strong>
<PluginSignatureBadge
status={mapPluginErrorCodeToSignatureStatus(error.errorCode)}
className={css`
margin-top: 0;
`}
/>
</HorizontalGroup>
</div>
)}
/>
</div>
</InfoBox>
);
}
function mapPluginErrorCodeToSignatureStatus(code: PluginErrorCode) {
switch (code) {
case PluginErrorCode.invalidSignature:
return PluginSignatureStatus.invalid;
case PluginErrorCode.missingSignature:
return PluginSignatureStatus.missing;
case PluginErrorCode.modifiedSignature:
return PluginSignatureStatus.modified;
default:
return PluginSignatureStatus.missing;
}
}
| public/app/features/plugins/components/PluginsErrorsInfo.tsx | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00018052906671073288,
0.00017423805547878146,
0.0001679373817751184,
0.00017500821559224278,
0.0000047369881031045225
] |
{
"id": 7,
"code_window": [
" locationService.push('/foo');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(1);\n",
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(2);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 139
} | #!/usr/bin/env bash
./scripts/build/update_repo/publish-rpm.sh "oss" "v5.4.3" "grafana-testing-repo"
| scripts/build/update_repo/test-publish-rpm-repo.sh | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017368252156302333,
0.00017368252156302333,
0.00017368252156302333,
0.00017368252156302333,
0
] |
{
"id": 8,
"code_window": [
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(2);\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(4);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 145
} | // Libraries
import React, { Component } from 'react';
import { createHtmlPortalNode, InPortal, OutPortal, HtmlPortalNode } from 'react-reverse-portal';
import { AppEvents, AppPlugin, AppPluginMeta, KeyValue, NavModel, PluginType } from '@grafana/data';
import { getNotFoundNav, getWarningNav, getExceptionNav } from 'app/angular/services/nav_model_srv';
import { Page } from 'app/core/components/Page/Page';
import PageLoader from 'app/core/components/PageLoader/PageLoader';
import { appEvents } from 'app/core/core';
import { GrafanaRouteComponentProps } from 'app/core/navigation/types';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
interface RouteParams {
pluginId: string;
}
interface Props extends GrafanaRouteComponentProps<RouteParams> {}
interface State {
loading: boolean;
portalNode: HtmlPortalNode;
plugin?: AppPlugin | null;
nav?: NavModel;
}
export function getAppPluginPageError(meta: AppPluginMeta) {
if (!meta) {
return 'Unknown Plugin';
}
if (meta.type !== PluginType.app) {
return 'Plugin must be an app';
}
if (!meta.enabled) {
return 'Application Not Enabled';
}
return null;
}
class AppRootPage extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
loading: true,
portalNode: createHtmlPortalNode(),
};
}
shouldComponentUpdate(nextProps: Props) {
return nextProps.location.pathname.startsWith('/a/');
}
async loadPluginSettings() {
const { params } = this.props.match;
try {
const app = await getPluginSettings(params.pluginId).then((info) => {
const error = getAppPluginPageError(info);
if (error) {
appEvents.emit(AppEvents.alertError, [error]);
this.setState({ nav: getWarningNav(error) });
return null;
}
return importAppPlugin(info);
});
this.setState({ plugin: app, loading: false, nav: undefined });
} catch (err) {
this.setState({
plugin: null,
loading: false,
nav: process.env.NODE_ENV === 'development' ? getExceptionNav(err) : getNotFoundNav(),
});
}
}
componentDidMount() {
this.loadPluginSettings();
}
componentDidUpdate(prevProps: Props) {
const { params } = this.props.match;
if (prevProps.match.params.pluginId !== params.pluginId) {
this.setState({ loading: true, plugin: null });
this.loadPluginSettings();
}
}
onNavChanged = (nav: NavModel) => {
this.setState({ nav });
};
render() {
const { loading, plugin, nav, portalNode } = this.state;
if (plugin && !plugin.root) {
// TODO? redirect to plugin page?
return <div>No Root App</div>;
}
return (
<>
<InPortal node={portalNode}>
{plugin && plugin.root && (
<plugin.root
meta={plugin.meta}
basename={this.props.match.url}
onNavChanged={this.onNavChanged}
query={this.props.queryParams as KeyValue}
path={this.props.location.pathname}
/>
)}
</InPortal>
{nav ? (
<Page navModel={nav}>
<Page.Contents isLoading={loading}>
<OutPortal node={portalNode} />
</Page.Contents>
</Page>
) : (
<Page>
<OutPortal node={portalNode} />
{loading && <PageLoader />}
</Page>
)}
</>
);
}
}
export default AppRootPage;
| public/app/features/plugins/components/AppRootPage.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.001073604915291071,
0.0002354637545067817,
0.00016348884673789144,
0.00017201485752593726,
0.0002324832894373685
] |
{
"id": 8,
"code_window": [
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(2);\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(4);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 145
} | package api
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/sqlstore/mockstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
)
type getSettingsTestCase struct {
desc string
expectedCode int
expectedBody string
permissions []accesscontrol.Permission
}
func TestAPI_AdminGetSettings(t *testing.T) {
tests := []getSettingsTestCase{
{
desc: "should return all settings",
expectedCode: http.StatusOK,
expectedBody: `{"auth.proxy":{"enable_login_token":"false","enabled":"false"},"auth.saml":{"allow_idp_initiated":"false","enabled":"true"}}`,
permissions: []accesscontrol.Permission{
{
Action: accesscontrol.ActionSettingsRead,
Scope: accesscontrol.ScopeSettingsAll,
},
},
},
{
desc: "should only return auth.saml settings",
expectedCode: http.StatusOK,
expectedBody: `{"auth.saml":{"allow_idp_initiated":"false","enabled":"true"}}`,
permissions: []accesscontrol.Permission{
{
Action: accesscontrol.ActionSettingsRead,
Scope: "settings:auth.saml:*",
},
},
},
{
desc: "should only partial properties from auth.saml and auth.proxy settings",
expectedCode: http.StatusOK,
expectedBody: `{"auth.proxy":{"enable_login_token":"false"},"auth.saml":{"enabled":"true"}}`,
permissions: []accesscontrol.Permission{
{
Action: accesscontrol.ActionSettingsRead,
Scope: "settings:auth.saml:enabled",
},
{
Action: accesscontrol.ActionSettingsRead,
Scope: "settings:auth.proxy:enable_login_token",
},
},
},
}
cfg := setting.NewCfg()
//seed sections and keys
cfg.Raw.DeleteSection("DEFAULT")
saml, err := cfg.Raw.NewSection("auth.saml")
assert.NoError(t, err)
_, err = saml.NewKey("enabled", "true")
assert.NoError(t, err)
_, err = saml.NewKey("allow_idp_initiated", "false")
assert.NoError(t, err)
proxy, err := cfg.Raw.NewSection("auth.proxy")
assert.NoError(t, err)
_, err = proxy.NewKey("enabled", "false")
assert.NoError(t, err)
_, err = proxy.NewKey("enable_login_token", "false")
assert.NoError(t, err)
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
sc, hs := setupAccessControlScenarioContext(t, cfg, "/api/admin/settings", test.permissions)
hs.SettingsProvider = &setting.OSSImpl{Cfg: cfg}
sc.resp = httptest.NewRecorder()
var err error
sc.req, err = http.NewRequest(http.MethodGet, "/api/admin/settings", nil)
assert.NoError(t, err)
sc.exec()
assert.Equal(t, test.expectedCode, sc.resp.Code)
assert.Equal(t, test.expectedBody, sc.resp.Body.String())
})
}
}
func TestAdmin_AccessControl(t *testing.T) {
tests := []accessControlTestCase{
{
expectedCode: http.StatusOK,
desc: "AdminGetStats should return 200 for user with correct permissions",
url: "/api/admin/stats",
method: http.MethodGet,
permissions: []accesscontrol.Permission{
{
Action: accesscontrol.ActionServerStatsRead,
},
},
},
{
expectedCode: http.StatusForbidden,
desc: "AdminGetStats should return 403 for user without required permissions",
url: "/api/admin/stats",
method: http.MethodGet,
permissions: []accesscontrol.Permission{
{
Action: "wrong",
},
},
},
{
expectedCode: http.StatusOK,
desc: "AdminGetSettings should return 200 for user with correct permissions",
url: "/api/admin/settings",
method: http.MethodGet,
permissions: []accesscontrol.Permission{
{
Action: accesscontrol.ActionSettingsRead,
},
},
},
{
expectedCode: http.StatusForbidden,
desc: "AdminGetSettings should return 403 for user without required permissions",
url: "/api/admin/settings",
method: http.MethodGet,
permissions: []accesscontrol.Permission{
{
Action: "wrong",
},
},
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
cfg := setting.NewCfg()
sc, hs := setupAccessControlScenarioContext(t, cfg, test.url, test.permissions)
sc.resp = httptest.NewRecorder()
hs.SettingsProvider = &setting.OSSImpl{Cfg: cfg}
hs.SQLStore = mockstore.NewSQLStoreMock()
var err error
sc.req, err = http.NewRequest(test.method, test.url, nil)
assert.NoError(t, err)
sc.exec()
assert.Equal(t, test.expectedCode, sc.resp.Code)
})
}
}
| pkg/api/admin_test.go | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017671851674094796,
0.0001723581226542592,
0.0001639306137803942,
0.00017347960965707898,
0.000003260601715737721
] |
{
"id": 8,
"code_window": [
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(2);\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(4);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 145
} | import { useEffect } from 'react';
import { NavModel, NavModelItem } from '@grafana/data';
import { Branding } from '../Branding/Branding';
export function usePageTitle(navModel?: NavModel, pageNav?: NavModelItem) {
useEffect(() => {
const parts: string[] = [];
if (pageNav) {
if (pageNav.children) {
const activePage = pageNav.children.find((x) => x.active);
if (activePage) {
parts.push(activePage.text);
}
}
parts.push(pageNav.text);
}
if (navModel) {
if (navModel.node !== navModel.main) {
parts.push(navModel.node.text);
}
parts.push(navModel.main.text);
}
parts.push(Branding.AppTitle);
document.title = parts.join(' - ');
}, [navModel, pageNav]);
}
| public/app/core/components/Page/usePageTitle.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017669526278041303,
0.00017602906154934317,
0.00017527129966765642,
0.00017607482732273638,
5.055240990259335e-7
] |
{
"id": 8,
"code_window": [
"\n",
" await act(async () => {\n",
" locationService.push('/a/my-awesome-plugin');\n",
" });\n",
"\n",
" expect(RootComponent.timesRendered).toEqual(2);\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" expect(RootComponent.timesRendered).toEqual(4);\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.test.tsx",
"type": "replace",
"edit_start_line_idx": 145
} | import { useMemo, useState } from 'react';
import { filterSpans, TraceSpan } from '@jaegertracing/jaeger-ui-components';
/**
* Controls the state of search input that highlights spans if they match the search string.
* @param spans
*/
export function useSearch(spans?: TraceSpan[]) {
const [search, setSearch] = useState('');
const spanFindMatches: Set<string> | undefined = useMemo(() => {
return search && spans ? filterSpans(search, spans) : undefined;
}, [search, spans]);
return { search, setSearch, spanFindMatches };
}
| public/app/features/explore/TraceView/useSearch.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017358486365992576,
0.0001702236186247319,
0.0001668623590376228,
0.0001702236186247319,
0.0000033612523111514747
] |
{
"id": 9,
"code_window": [
"\n",
" render() {\n",
" const { loading, plugin, nav, portalNode } = this.state;\n",
"\n",
" if (plugin && !plugin.root) {\n",
" // TODO? redirect to plugin page?\n",
" return <div>No Root App</div>;\n",
" }\n",
"\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!plugin || this.props.match.params.pluginId !== plugin.meta.id) {\n",
" return (\n",
" <Page>\n",
" <PageLoader />\n",
" </Page>\n",
" );\n",
" }\n",
"\n",
" if (!plugin.root) {\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 94
} | import { act, render, screen } from '@testing-library/react';
import React, { Component } from 'react';
import { Route, Router } from 'react-router-dom';
import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock';
import { AppPlugin, PluginType, AppRootProps, NavModelItem } from '@grafana/data';
import { locationService, setEchoSrv } from '@grafana/runtime';
import { GrafanaContext } from 'app/core/context/GrafanaContext';
import { GrafanaRoute } from 'app/core/navigation/GrafanaRoute';
import { Echo } from 'app/core/services/echo/Echo';
import { getMockPlugin } from '../__mocks__/pluginMocks';
import { getPluginSettings } from '../pluginSettings';
import { importAppPlugin } from '../plugin_loader';
import AppRootPage from './AppRootPage';
jest.mock('../pluginSettings', () => ({
getPluginSettings: jest.fn(),
}));
jest.mock('../plugin_loader', () => ({
importAppPlugin: jest.fn(),
}));
const importAppPluginMock = importAppPlugin as jest.Mock<
ReturnType<typeof importAppPlugin>,
Parameters<typeof importAppPlugin>
>;
const getPluginSettingsMock = getPluginSettings as jest.Mock<
ReturnType<typeof getPluginSettings>,
Parameters<typeof getPluginSettings>
>;
class RootComponent extends Component<AppRootProps> {
static timesMounted = 0;
componentDidMount() {
RootComponent.timesMounted += 1;
const node: NavModelItem = {
text: 'My Great plugin',
children: [
{
text: 'A page',
url: '/apage',
id: 'a',
},
{
text: 'Another page',
url: '/anotherpage',
id: 'b',
},
],
};
this.props.onNavChanged({
main: node,
node,
});
}
render() {
return <p>my great plugin</p>;
}
}
function renderUnderRouter() {
const route = { component: AppRootPage };
locationService.push('/a/my-awesome-plugin');
render(
<Router history={locationService.getHistory()}>
<GrafanaContext.Provider value={getGrafanaContextMock()}>
<Route path="/a/:pluginId" exact render={(props) => <GrafanaRoute {...props} route={route as any} />} />
</GrafanaContext.Provider>
</Router>
);
}
describe('AppRootPage', () => {
beforeEach(() => {
jest.resetAllMocks();
setEchoSrv(new Echo());
});
it('should not mount plugin twice if nav is changed', async () => {
// reproduces https://github.com/grafana/grafana/pull/28105
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
// check that plugin and nav links were rendered, and plugin is mounted only once
expect(await screen.findByText('my great plugin')).toBeVisible();
expect(await screen.findByLabelText('Tab A page')).toBeVisible();
expect(await screen.findByLabelText('Tab Another page')).toBeVisible();
expect(RootComponent.timesMounted).toEqual(1);
});
it('should not render component if not at plugin path', async () => {
getPluginSettingsMock.mockResolvedValue(
getMockPlugin({
type: PluginType.app,
enabled: true,
})
);
class RootComponent extends Component<AppRootProps> {
static timesRendered = 0;
render() {
RootComponent.timesRendered += 1;
return <p>my great component</p>;
}
}
const plugin = new AppPlugin();
plugin.root = RootComponent;
importAppPluginMock.mockResolvedValue(plugin);
renderUnderRouter();
expect(await screen.findByText('my great component')).toBeVisible();
// renders the first time
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/foo');
});
expect(RootComponent.timesRendered).toEqual(1);
await act(async () => {
locationService.push('/a/my-awesome-plugin');
});
expect(RootComponent.timesRendered).toEqual(2);
});
});
| public/app/features/plugins/components/AppRootPage.test.tsx | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.9965920448303223,
0.1349269300699234,
0.00016540307842660695,
0.00027708173729479313,
0.33278772234916687
] |
{
"id": 9,
"code_window": [
"\n",
" render() {\n",
" const { loading, plugin, nav, portalNode } = this.state;\n",
"\n",
" if (plugin && !plugin.root) {\n",
" // TODO? redirect to plugin page?\n",
" return <div>No Root App</div>;\n",
" }\n",
"\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!plugin || this.props.match.params.pluginId !== plugin.meta.id) {\n",
" return (\n",
" <Page>\n",
" <PageLoader />\n",
" </Page>\n",
" );\n",
" }\n",
"\n",
" if (!plugin.root) {\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 94
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21.32,9.55l-1.89-.63.89-1.78A1,1,0,0,0,20.13,6L18,3.87a1,1,0,0,0-1.15-.19l-1.78.89-.63-1.89A1,1,0,0,0,13.5,2h-3a1,1,0,0,0-.95.68L8.92,4.57,7.14,3.68A1,1,0,0,0,6,3.87L3.87,6a1,1,0,0,0-.19,1.15l.89,1.78-1.89.63A1,1,0,0,0,2,10.5v3a1,1,0,0,0,.68.95l1.89.63-.89,1.78A1,1,0,0,0,3.87,18L6,20.13a1,1,0,0,0,1.15.19l1.78-.89.63,1.89a1,1,0,0,0,.95.68h3a1,1,0,0,0,.95-.68l.63-1.89,1.78.89A1,1,0,0,0,18,20.13L20.13,18a1,1,0,0,0,.19-1.15l-.89-1.78,1.89-.63A1,1,0,0,0,22,13.5v-3A1,1,0,0,0,21.32,9.55ZM20,12.78l-1.2.4A2,2,0,0,0,17.64,16l.57,1.14-1.1,1.1L16,17.64a2,2,0,0,0-2.79,1.16l-.4,1.2H11.22l-.4-1.2A2,2,0,0,0,8,17.64l-1.14.57-1.1-1.1L6.36,16A2,2,0,0,0,5.2,13.18L4,12.78V11.22l1.2-.4A2,2,0,0,0,6.36,8L5.79,6.89l1.1-1.1L8,6.36A2,2,0,0,0,10.82,5.2l.4-1.2h1.56l.4,1.2A2,2,0,0,0,16,6.36l1.14-.57,1.1,1.1L17.64,8a2,2,0,0,0,1.16,2.79l1.2.4ZM12,8a4,4,0,1,0,4,4A4,4,0,0,0,12,8Zm0,6a2,2,0,1,1,2-2A2,2,0,0,1,12,14Z"/></svg> | public/img/icons/unicons/cog.svg | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00018481328152120113,
0.00018481328152120113,
0.00018481328152120113,
0.00018481328152120113,
0
] |
{
"id": 9,
"code_window": [
"\n",
" render() {\n",
" const { loading, plugin, nav, portalNode } = this.state;\n",
"\n",
" if (plugin && !plugin.root) {\n",
" // TODO? redirect to plugin page?\n",
" return <div>No Root App</div>;\n",
" }\n",
"\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!plugin || this.props.match.params.pluginId !== plugin.meta.id) {\n",
" return (\n",
" <Page>\n",
" <PageLoader />\n",
" </Page>\n",
" );\n",
" }\n",
"\n",
" if (!plugin.root) {\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 94
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12,10a1,1,0,0,0-1,1v4a1,1,0,0,0,2,0V11A1,1,0,0,0,12,10ZM8,13a1,1,0,0,0-1,1v1a1,1,0,0,0,2,0V14A1,1,0,0,0,8,13ZM12,2A10,10,0,0,0,2,12a9.89,9.89,0,0,0,2.26,6.33l-2,2a1,1,0,0,0-.21,1.09A1,1,0,0,0,3,22h9A10,10,0,0,0,12,2Zm0,18H5.41l.93-.93a1,1,0,0,0,.3-.71,1,1,0,0,0-.3-.7A8,8,0,1,1,12,20ZM16,8a1,1,0,0,0-1,1v6a1,1,0,0,0,2,0V9A1,1,0,0,0,16,8Z"/></svg> | public/img/icons/unicons/comment-chart-line.svg | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017039004887919873,
0.00017039004887919873,
0.00017039004887919873,
0.00017039004887919873,
0
] |
{
"id": 9,
"code_window": [
"\n",
" render() {\n",
" const { loading, plugin, nav, portalNode } = this.state;\n",
"\n",
" if (plugin && !plugin.root) {\n",
" // TODO? redirect to plugin page?\n",
" return <div>No Root App</div>;\n",
" }\n",
"\n",
" return (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!plugin || this.props.match.params.pluginId !== plugin.meta.id) {\n",
" return (\n",
" <Page>\n",
" <PageLoader />\n",
" </Page>\n",
" );\n",
" }\n",
"\n",
" if (!plugin.root) {\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 94
} | import angular from 'angular';
const coreModule = angular.module('grafana.core', ['ngRoute']);
// legacy modules
const angularModules = [
coreModule,
angular.module('grafana.controllers', []),
angular.module('grafana.directives', []),
angular.module('grafana.factories', []),
angular.module('grafana.services', []),
angular.module('grafana.filters', []),
angular.module('grafana.routes', []),
];
export { angularModules, coreModule };
export default coreModule;
| public/app/angular/core_module.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017423721146769822,
0.0001723522145766765,
0.00017046723223757,
0.0001723522145766765,
0.0000018849896150641143
] |
{
"id": 10,
"code_window": [
"\n",
" return (\n",
" <>\n",
" <InPortal node={portalNode}>\n",
" {plugin && plugin.root && (\n",
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n",
" )}\n",
" </InPortal>\n",
" {nav ? (\n",
" <Page navModel={nav}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 102
} | import * as webpack from 'webpack';
import { getStyleLoaders, getStylesheetEntries, getFileLoaders } from './webpack/loaders';
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const ReplaceInFileWebpackPlugin = require('replace-in-file-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const util = require('util');
const readdirPromise = util.promisify(fs.readdir);
const accessPromise = util.promisify(fs.access);
export interface WebpackConfigurationOptions {
watch?: boolean;
production?: boolean;
preserveConsole?: boolean;
}
type WebpackConfigurationGetter = (options: WebpackConfigurationOptions) => Promise<webpack.Configuration>;
export type CustomWebpackConfigurationGetter = (
originalConfig: webpack.Configuration,
options: WebpackConfigurationOptions
) => webpack.Configuration;
export const findModuleFiles = async (base: string, files?: string[], result?: string[]) => {
files = files || (await readdirPromise(base));
result = result || [];
if (files) {
await Promise.all(
files.map(async (file) => {
const newbase = path.join(base, file);
if (fs.statSync(newbase).isDirectory()) {
result = await findModuleFiles(newbase, await readdirPromise(newbase), result);
} else {
const filename = path.basename(file);
if (/^module.(t|j)sx?$/.exec(filename)) {
// @ts-ignore
result.push(newbase);
}
}
})
);
}
return result;
};
const getModuleFiles = () => {
return findModuleFiles(path.resolve(process.cwd(), 'src'));
};
const getManualChunk = (id: string) => {
if (id.endsWith('module.ts') || id.endsWith('module.js') || id.endsWith('module.tsx')) {
const idx = id.lastIndexOf(path.sep + 'src' + path.sep);
if (idx > 0) {
const name = id.substring(idx + 5, id.lastIndexOf('.'));
return {
name,
module: id,
};
}
}
return null;
};
const getEntries = async () => {
const entries: { [key: string]: string } = {};
const modules = await getModuleFiles();
modules.forEach((modFile) => {
const mod = getManualChunk(modFile);
// @ts-ignore
entries[mod.name] = mod.module;
});
return {
...entries,
...getStylesheetEntries(),
};
};
const getCommonPlugins = (options: WebpackConfigurationOptions) => {
const hasREADME = fs.existsSync(path.resolve(process.cwd(), 'src', 'README.md'));
const packageJson = require(path.resolve(process.cwd(), 'package.json'));
return [
new MiniCssExtractPlugin({
// both options are optional
filename: 'styles/[name].css',
}),
new CopyWebpackPlugin({
patterns: [
// If src/README.md exists use it; otherwise the root README
{ from: hasREADME ? 'README.md' : '../README.md', to: '.', force: true, priority: 1, noErrorOnMissing: true },
{ from: 'plugin.json', to: '.', noErrorOnMissing: true },
{ from: '**/README.md', to: '[path]README.md', priority: 0, noErrorOnMissing: true },
{ from: '../LICENSE', to: '.', noErrorOnMissing: true },
{ from: '../CHANGELOG.md', to: '.', force: true, noErrorOnMissing: true },
{ from: '**/*.{json,svg,png,html}', to: '.', noErrorOnMissing: true },
{ from: 'img/**/*', to: '.', noErrorOnMissing: true },
{ from: 'libs/**/*', to: '.', noErrorOnMissing: true },
{ from: 'static/**/*', to: '.', noErrorOnMissing: true },
],
}),
new ReplaceInFileWebpackPlugin([
{
dir: 'dist',
files: ['plugin.json', 'README.md'],
rules: [
{
search: '%VERSION%',
replace: packageJson.version,
},
{
search: '%TODAY%',
replace: new Date().toISOString().substring(0, 10),
},
],
},
]),
new ForkTsCheckerWebpackPlugin({
typescript: { configFile: path.join(process.cwd(), 'tsconfig.json') },
issue: {
include: [{ file: '**/*.{ts,tsx}' }],
},
}),
];
};
const getBaseWebpackConfig: WebpackConfigurationGetter = async (options) => {
const plugins = getCommonPlugins(options);
const optimization: { [key: string]: any } = {};
if (options.production) {
const compressOptions = { drop_console: !options.preserveConsole, drop_debugger: true };
optimization.minimizer = [
new TerserPlugin({ terserOptions: { compress: compressOptions } }),
new CssMinimizerPlugin(),
];
optimization.chunkIds = 'total-size';
optimization.moduleIds = 'size';
} else if (options.watch) {
plugins.push(new HtmlWebpackPlugin());
}
return {
mode: options.production ? 'production' : 'development',
target: 'web',
context: path.join(process.cwd(), 'src'),
devtool: 'source-map',
entry: await getEntries(),
output: {
filename: '[name].js',
path: path.join(process.cwd(), 'dist'),
libraryTarget: 'amd',
publicPath: '/',
},
performance: { hints: false },
externals: [
'lodash',
'jquery',
'moment',
'slate',
'emotion',
'@emotion/react',
'@emotion/css',
'prismjs',
'slate-plain-serializer',
'@grafana/slate-react',
'react',
'react-dom',
'react-redux',
'redux',
'rxjs',
'react-router-dom',
'd3',
'angular',
'@grafana/ui',
'@grafana/runtime',
'@grafana/data',
({ request }, callback) => {
const prefix = 'grafana/';
if (request?.indexOf(prefix) === 0) {
return callback(undefined, request.slice(prefix.length));
}
callback();
},
],
plugins,
resolve: {
extensions: ['.ts', '.tsx', '.js'],
modules: [path.resolve(process.cwd(), 'src'), 'node_modules'],
fallback: {
buffer: false,
fs: false,
stream: false,
http: false,
https: false,
string_decoder: false,
os: false,
timers: false,
},
},
module: {
rules: [
{
test: /\.[tj]sx?$/,
use: {
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
cacheCompression: false,
presets: [
[require.resolve('@babel/preset-env'), { modules: false }],
[
require.resolve('@babel/preset-typescript'),
{
allowNamespaces: true,
allowDeclareFields: true,
},
],
[require.resolve('@babel/preset-react')],
],
plugins: [
[
require.resolve('@babel/plugin-transform-typescript'),
{
allowNamespaces: true,
allowDeclareFields: true,
},
],
require.resolve('@babel/plugin-proposal-class-properties'),
[require.resolve('@babel/plugin-proposal-object-rest-spread'), { loose: true }],
require.resolve('@babel/plugin-transform-react-constant-elements'),
require.resolve('@babel/plugin-proposal-nullish-coalescing-operator'),
require.resolve('@babel/plugin-proposal-optional-chaining'),
require.resolve('@babel/plugin-syntax-dynamic-import'),
require.resolve('babel-plugin-angularjs-annotate'),
],
},
},
exclude: /node_modules/,
},
...getStyleLoaders(),
{
test: /\.html$/,
exclude: [/node_modules/],
use: {
loader: require.resolve('html-loader'),
},
},
...getFileLoaders(),
],
},
optimization,
};
};
export const loadWebpackConfig: WebpackConfigurationGetter = async (options) => {
const baseConfig = await getBaseWebpackConfig(options);
const customWebpackPath = path.resolve(process.cwd(), 'webpack.config.js');
try {
await accessPromise(customWebpackPath);
const customConfig = require(customWebpackPath);
const configGetter = customConfig.getWebpackConfig || customConfig;
if (typeof configGetter !== 'function') {
throw Error(
'Custom webpack config needs to export a function implementing CustomWebpackConfigurationGetter. Function needs to be ' +
'module export or named "getWebpackConfig"'
);
}
return (configGetter as CustomWebpackConfigurationGetter)(baseConfig, options);
} catch (err: any) {
if (err.code === 'ENOENT') {
return baseConfig;
}
throw err;
}
};
| packages/grafana-toolkit/src/config/webpack.plugin.config.ts | 1 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017589562048669904,
0.00016971412696875632,
0.00016318469715770334,
0.00017041247338056564,
0.0000033755425192794064
] |
{
"id": 10,
"code_window": [
"\n",
" return (\n",
" <>\n",
" <InPortal node={portalNode}>\n",
" {plugin && plugin.root && (\n",
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n",
" )}\n",
" </InPortal>\n",
" {nav ? (\n",
" <Page navModel={nav}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 102
} | package plugins
import (
"archive/zip"
"io"
"log"
"os"
"path/filepath"
)
// Unzip unzips a plugin.
func Unzip(fpath, tgtDir string) error {
log.Printf("Unzipping plugin %q into %q...", fpath, tgtDir)
r, err := zip.OpenReader(fpath)
if err != nil {
return err
}
defer logCloseError(r.Close)
// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
log.Printf("Extracting zip member %q...", f.Name)
rc, err := f.Open()
if err != nil {
return err
}
defer logCloseError(rc.Close)
//nolint:gosec
dstPath := filepath.Join(tgtDir, f.Name)
if f.FileInfo().IsDir() {
return os.MkdirAll(dstPath, f.Mode())
}
if err := os.MkdirAll(filepath.Dir(dstPath), f.Mode()); err != nil {
return err
}
//nolint:gosec
fd, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer logCloseError(fd.Close)
// nolint:gosec
if _, err := io.Copy(fd, rc); err != nil {
return err
}
return fd.Close()
}
for _, f := range r.File {
if err := extractAndWriteFile(f); err != nil {
return err
}
}
return nil
}
| pkg/build/plugins/zip.go | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00017646071501076221,
0.00017009589646477252,
0.0001625947916181758,
0.00017014748300425708,
0.0000049968853090831544
] |
{
"id": 10,
"code_window": [
"\n",
" return (\n",
" <>\n",
" <InPortal node={portalNode}>\n",
" {plugin && plugin.root && (\n",
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n",
" )}\n",
" </InPortal>\n",
" {nav ? (\n",
" <Page navModel={nav}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 102
} | import { e2e } from '../';
export interface ScenarioArguments {
describeName: string;
itName: string;
scenario: Function;
skipScenario?: boolean;
addScenarioDataSource?: boolean;
addScenarioDashBoard?: boolean;
loginViaApi?: boolean;
}
export const e2eScenario = ({
describeName,
itName,
scenario,
skipScenario = false,
addScenarioDataSource = false,
addScenarioDashBoard = false,
loginViaApi = true,
}: ScenarioArguments) => {
describe(describeName, () => {
if (skipScenario) {
it.skip(itName, () => scenario());
} else {
before(() => e2e.flows.login(e2e.env('USERNAME'), e2e.env('PASSWORD'), loginViaApi));
beforeEach(() => {
Cypress.Cookies.preserveOnce('grafana_session');
if (addScenarioDataSource) {
e2e.flows.addDataSource();
}
if (addScenarioDashBoard) {
e2e.flows.addDashboard();
}
});
afterEach(() => e2e.flows.revertAllChanges());
after(() => e2e().clearCookies());
it(itName, () => scenario());
// @todo remove when possible: https://github.com/cypress-io/cypress/issues/2831
it('temporary', () => {});
}
});
};
| packages/grafana-e2e/src/support/scenario.ts | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.0001756569545250386,
0.00017340311023872346,
0.00017027197463903576,
0.00017335741722490638,
0.00000178299728759157
] |
{
"id": 10,
"code_window": [
"\n",
" return (\n",
" <>\n",
" <InPortal node={portalNode}>\n",
" {plugin && plugin.root && (\n",
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n",
" )}\n",
" </InPortal>\n",
" {nav ? (\n",
" <Page navModel={nav}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <plugin.root\n",
" meta={plugin.meta}\n",
" basename={this.props.match.url}\n",
" onNavChanged={this.onNavChanged}\n",
" query={this.props.queryParams as KeyValue}\n",
" path={this.props.location.pathname}\n",
" />\n"
],
"file_path": "public/app/features/plugins/components/AppRootPage.tsx",
"type": "replace",
"edit_start_line_idx": 102
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M18.85,15.69a1,1,0,0,0-1.41,0l-2.06,2.06a1,1,0,0,0,.45,1.67l.26.07-.8.8a1,1,0,0,0,0,1.42,1,1,0,0,0,1.42,0l2-2a1,1,0,0,0,.26-1,1,1,0,0,0-.71-.71L18,17.94l.83-.84A1,1,0,0,0,18.85,15.69ZM7.91,19.49l.26-.07a1,1,0,0,0,.45-1.67L6.56,15.69A1,1,0,0,0,5.15,17.1l.83.84L5.72,18a1,1,0,0,0-.71.71,1,1,0,0,0,.26,1l2,2a1,1,0,0,0,1.42,0,1,1,0,0,0,0-1.42ZM21,4a1,1,0,0,0-1,1H17a3,3,0,0,0-3-3H10A3,3,0,0,0,7,5H4A1,1,0,0,0,2,5V7A1,1,0,0,0,4,7H7V9a3,3,0,0,0,2,2.83V13a2,2,0,0,0,2,2v6a1,1,0,0,0,2,0V15a2,2,0,0,0,2-2V11.83A3,3,0,0,0,17,9V7h3a1,1,0,0,0,2,0V5A1,1,0,0,0,21,4ZM15,9a1,1,0,0,1-1,1,1,1,0,0,0-1,1v2H11V11a1,1,0,0,0-1-1A1,1,0,0,1,9,9V5a1,1,0,0,1,1-1h4a1,1,0,0,1,1,1ZM12,6a1,1,0,0,0-1,1V8a1,1,0,0,0,2,0V7A1,1,0,0,0,12,6Z"/></svg> | public/img/icons/unicons/jackhammer.svg | 0 | https://github.com/grafana/grafana/commit/e5fba788d6ac3de087f030a43a2bee39366981c6 | [
0.00016944466915447265,
0.00016944466915447265,
0.00016944466915447265,
0.00016944466915447265,
0
] |
{
"id": 0,
"code_window": [
" --padding-start: #{$button-md-padding-start};\n",
" --padding-end: #{$button-md-padding-end};\n",
" --height: #{$button-md-height};\n",
" --transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,\n",
" background-color $button-md-transition-duration $button-md-transition-timing-function,\n",
" color $button-md-transition-duration $button-md-transition-timing-function};\n",
"\n",
" font-size: #{$button-md-font-size};\n",
" font-weight: #{$button-md-font-weight};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1),\n",
" background-color 15ms linear,\n",
" color 15ms linear;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 17
} | @import "./button";
@import "./button.md.vars";
// Material Design Button
// --------------------------------------------------
:host {
--border-radius: #{$button-md-border-radius};
--margin-top: #{$button-md-margin-top};
--margin-bottom: #{$button-md-margin-bottom};
--margin-start: #{$button-md-margin-start};
--margin-end: #{$button-md-margin-end};
--padding-top: #{$button-md-padding-top};
--padding-bottom: #{$button-md-padding-bottom};
--padding-start: #{$button-md-padding-start};
--padding-end: #{$button-md-padding-end};
--height: #{$button-md-height};
--transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,
background-color $button-md-transition-duration $button-md-transition-timing-function,
color $button-md-transition-duration $button-md-transition-timing-function};
font-size: #{$button-md-font-size};
font-weight: #{$button-md-font-weight};
letter-spacing: #{$button-md-letter-spacing};
text-transform: #{$button-md-text-transform};
}
// Material Design Solid Button
// --------------------------------------------------
:host(.button-solid) {
--box-shadow: #{$button-md-box-shadow};
}
:host(.button-solid.activated) {
--box-shadow: #{$button-md-box-shadow-activated};
}
// Material Design Outline Button
// --------------------------------------------------
:host(.button-outline) {
--border-width: 1px;
--border-style: solid;
--box-shadow: none;
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
}
:host(.button-outline.activated.ion-color) .button-native {
background: transparent;
}
// Material Design Clear Button
// --------------------------------------------------
:host(.button-clear) {
--opacity: #{$button-md-clear-opacity};
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
--color-focused: #{ion-color(primary, base)};
}
// Material Design Round Button
// --------------------------------------------------
:host(.button-round) {
--border-radius: #{$button-md-round-border-radius};
--padding-top: #{$button-md-round-padding-top};
--padding-start: #{$button-md-round-padding-start};
--padding-end: #{$button-md-round-padding-end};
--padding-bottom: #{$button-md-round-padding-bottom};
}
// Material Design Button Sizes
// --------------------------------------------------
:host(.button-large) {
--padding-top: #{$button-md-large-padding-top};
--padding-start: #{$button-md-large-padding-start};
--padding-end: #{$button-md-large-padding-end};
--padding-bottom: #{$button-md-large-padding-bottom};
--height: #{$button-md-large-height};
font-size: #{$button-md-large-font-size};
}
:host(.button-small) {
--padding-top: #{$button-md-small-padding-top};
--padding-start: #{$button-md-small-padding-start};
--padding-end: #{$button-md-small-padding-end};
--padding-bottom: #{$button-md-small-padding-bottom};
--height: #{$button-md-small-height};
font-size: #{$button-md-small-font-size};
}
// MD strong Button
// --------------------------------------------------
:host(.button-strong) {
font-weight: #{$button-md-strong-font-weight};
}
::slotted(ion-icon[slot="icon-only"]) {
@include padding(0);
}
| core/src/components/button/button.md.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.8982950448989868,
0.07922425121068954,
0.00016940767818596214,
0.0006284443661570549,
0.2470979392528534
] |
{
"id": 0,
"code_window": [
" --padding-start: #{$button-md-padding-start};\n",
" --padding-end: #{$button-md-padding-end};\n",
" --height: #{$button-md-height};\n",
" --transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,\n",
" background-color $button-md-transition-duration $button-md-transition-timing-function,\n",
" color $button-md-transition-duration $button-md-transition-timing-function};\n",
"\n",
" font-size: #{$button-md-font-size};\n",
" font-weight: #{$button-md-font-weight};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1),\n",
" background-color 15ms linear,\n",
" color 15ms linear;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 17
} |
<router-outlet></router-outlet>
| angular/test/testapp/src/app/app.component.html | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0001672870566835627,
0.0001672870566835627,
0.0001672870566835627,
0.0001672870566835627,
0
] |
{
"id": 0,
"code_window": [
" --padding-start: #{$button-md-padding-start};\n",
" --padding-end: #{$button-md-padding-end};\n",
" --height: #{$button-md-height};\n",
" --transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,\n",
" background-color $button-md-transition-duration $button-md-transition-timing-function,\n",
" color $button-md-transition-duration $button-md-transition-timing-function};\n",
"\n",
" font-size: #{$button-md-font-size};\n",
" font-weight: #{$button-md-font-weight};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1),\n",
" background-color 15ms linear,\n",
" color 15ms linear;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 17
} | ```html
<!-- Default Checkbox -->
<ion-checkbox></ion-checkbox>
<!-- Disabled Checkbox -->
<ion-checkbox disabled></ion-checkbox>
<!-- Checked Checkbox -->
<ion-checkbox checked></ion-checkbox>
<!-- Checkbox Colors -->
<ion-checkbox color="primary"></ion-checkbox>
<ion-checkbox color="secondary"></ion-checkbox>
<ion-checkbox color="danger"></ion-checkbox>
<ion-checkbox color="light"></ion-checkbox>
<ion-checkbox color="dark"></ion-checkbox>
<!-- Checkboxes in a List -->
<ion-list>
<ion-item>
<ion-label>Pepperoni</ion-label>
<ion-checkbox slot="end" value="pepperoni" checked></ion-checkbox>
</ion-item>
<ion-item>
<ion-label>Sausage</ion-label>
<ion-checkbox slot="end" value="sausage" disabled></ion-checkbox>
</ion-item>
<ion-item>
<ion-label>Mushrooms</ion-label>
<ion-checkbox slot="end" value="mushrooms"></ion-checkbox>
</ion-item>
</ion-list>
```
| core/src/components/checkbox/usage/javascript.md | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.00017279418534599245,
0.00017009391740430146,
0.00016780626901891083,
0.00016988760035019368,
0.0000017899915292218793
] |
{
"id": 0,
"code_window": [
" --padding-start: #{$button-md-padding-start};\n",
" --padding-end: #{$button-md-padding-end};\n",
" --height: #{$button-md-height};\n",
" --transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,\n",
" background-color $button-md-transition-duration $button-md-transition-timing-function,\n",
" color $button-md-transition-duration $button-md-transition-timing-function};\n",
"\n",
" font-size: #{$button-md-font-size};\n",
" font-weight: #{$button-md-font-weight};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1),\n",
" background-color 15ms linear,\n",
" color 15ms linear;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 17
} | @import "../themes/ionic.globals";
// Ionic Font Family
// --------------------------------------------------
html.ios {
--ion-default-font: -apple-system, BlinkMacSystemFont, "Helvetica Neue", "Roboto", sans-serif;
}
html.md {
--ion-default-font: "Roboto", "Helvetica Neue", sans-serif;
}
html {
--ion-font-family: var(--ion-default-font);
}
body.backdrop-no-scroll {
overflow: hidden;
}
// TODO: Block scrolling in ion-content, breaks inside ion-modal
// body.backdrop-no-scroll .ion-page > ion-content {
// --overflow: hidden;
// }
// Ionic Colors
// --------------------------------------------------
// Generates the color classes and variables based on the
// colors map
@mixin generate-color($color-name) {
$value: map-get($colors, $color-name);
$base: map-get($value, base);
$contrast: map-get($value, contrast);
$shade: map-get($value, shade);
$tint: map-get($value, tint);
--ion-color-base: var(--ion-color-#{$color-name}, #{$base}) !important;
--ion-color-base-rgb: var(--ion-color-#{$color-name}-rgb, #{color-to-rgb-list($base)}) !important;
--ion-color-contrast: var(--ion-color-#{$color-name}-contrast, #{$contrast}) !important;
--ion-color-contrast-rgb: var(--ion-color-#{$color-name}-contrast-rgb, #{color-to-rgb-list($contrast)}) !important;
--ion-color-shade: var(--ion-color-#{$color-name}-shade, #{$shade}) !important;
--ion-color-tint: var(--ion-color-#{$color-name}-tint, #{$tint}) !important;
}
@each $color-name, $value in $colors {
.ion-color-#{$color-name} {
@include generate-color($color-name);
}
}
// Page Container Structure
// --------------------------------------------------
.ion-page {
@include position(0, 0, 0, 0);
display: flex;
position: absolute;
flex-direction: column;
justify-content: space-between;
contain: layout size style;
overflow: hidden;
z-index: $z-index-page-container;
}
ion-route,
ion-route-redirect,
ion-router,
ion-animation-controller,
ion-nav-controller,
ion-menu-controller,
ion-action-sheet-controller,
ion-alert-controller,
ion-loading-controller,
ion-modal-controller,
ion-picker-controller,
ion-popover-controller,
ion-toast-controller,
.ion-page-hidden,
[hidden] {
/* stylelint-disable-next-line declaration-no-important */
display: none !important;
}
.ion-page-invisible {
opacity: 0;
}
// Ionic Safe Margins
// --------------------------------------------------
html.plt-ios.plt-hybrid, html.plt-ios.plt-pwa {
--ion-statusbar-padding: 20px;
}
@supports (padding-top: 20px) {
html {
--ion-safe-area-top: var(--ion-statusbar-padding);
}
}
// TODO: remove once Safari 11.2 dies
@supports (padding-top: constant(safe-area-inset-top)) {
html {
--ion-safe-area-top: constant(safe-area-inset-top);
--ion-safe-area-bottom: constant(safe-area-inset-bottom);
--ion-safe-area-left: constant(safe-area-inset-left);
--ion-safe-area-right: constant(safe-area-inset-right);
}
}
@supports (padding-top: env(safe-area-inset-top)) {
html {
--ion-safe-area-top: env(safe-area-inset-top);
--ion-safe-area-bottom: env(safe-area-inset-bottom);
--ion-safe-area-left: env(safe-area-inset-left);
--ion-safe-area-right: env(safe-area-inset-right);
}
}
| core/src/css/core.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.00017191068036481738,
0.00016750459326431155,
0.00016370553930755705,
0.0001675688399700448,
0.000002068588173642638
] |
{
"id": 1,
"code_window": [
"// Material Design Outline Button\n",
"// --------------------------------------------------\n",
"\n",
":host(.button-outline) {\n",
" --border-width: 1px;\n",
" --border-style: solid;\n",
" --box-shadow: none;\n",
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --border-width: 2px;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 44
} | @import "./button";
@import "./button.md.vars";
// Material Design Button
// --------------------------------------------------
:host {
--border-radius: #{$button-md-border-radius};
--margin-top: #{$button-md-margin-top};
--margin-bottom: #{$button-md-margin-bottom};
--margin-start: #{$button-md-margin-start};
--margin-end: #{$button-md-margin-end};
--padding-top: #{$button-md-padding-top};
--padding-bottom: #{$button-md-padding-bottom};
--padding-start: #{$button-md-padding-start};
--padding-end: #{$button-md-padding-end};
--height: #{$button-md-height};
--transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,
background-color $button-md-transition-duration $button-md-transition-timing-function,
color $button-md-transition-duration $button-md-transition-timing-function};
font-size: #{$button-md-font-size};
font-weight: #{$button-md-font-weight};
letter-spacing: #{$button-md-letter-spacing};
text-transform: #{$button-md-text-transform};
}
// Material Design Solid Button
// --------------------------------------------------
:host(.button-solid) {
--box-shadow: #{$button-md-box-shadow};
}
:host(.button-solid.activated) {
--box-shadow: #{$button-md-box-shadow-activated};
}
// Material Design Outline Button
// --------------------------------------------------
:host(.button-outline) {
--border-width: 1px;
--border-style: solid;
--box-shadow: none;
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
}
:host(.button-outline.activated.ion-color) .button-native {
background: transparent;
}
// Material Design Clear Button
// --------------------------------------------------
:host(.button-clear) {
--opacity: #{$button-md-clear-opacity};
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
--color-focused: #{ion-color(primary, base)};
}
// Material Design Round Button
// --------------------------------------------------
:host(.button-round) {
--border-radius: #{$button-md-round-border-radius};
--padding-top: #{$button-md-round-padding-top};
--padding-start: #{$button-md-round-padding-start};
--padding-end: #{$button-md-round-padding-end};
--padding-bottom: #{$button-md-round-padding-bottom};
}
// Material Design Button Sizes
// --------------------------------------------------
:host(.button-large) {
--padding-top: #{$button-md-large-padding-top};
--padding-start: #{$button-md-large-padding-start};
--padding-end: #{$button-md-large-padding-end};
--padding-bottom: #{$button-md-large-padding-bottom};
--height: #{$button-md-large-height};
font-size: #{$button-md-large-font-size};
}
:host(.button-small) {
--padding-top: #{$button-md-small-padding-top};
--padding-start: #{$button-md-small-padding-start};
--padding-end: #{$button-md-small-padding-end};
--padding-bottom: #{$button-md-small-padding-bottom};
--height: #{$button-md-small-height};
font-size: #{$button-md-small-font-size};
}
// MD strong Button
// --------------------------------------------------
:host(.button-strong) {
font-weight: #{$button-md-strong-font-weight};
}
::slotted(ion-icon[slot="icon-only"]) {
@include padding(0);
}
| core/src/components/button/button.md.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.9868013858795166,
0.0880255475640297,
0.00016634365601930767,
0.003170149866491556,
0.27114740014076233
] |
{
"id": 1,
"code_window": [
"// Material Design Outline Button\n",
"// --------------------------------------------------\n",
"\n",
":host(.button-outline) {\n",
" --border-width: 1px;\n",
" --border-style: solid;\n",
" --box-shadow: none;\n",
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --border-width: 2px;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 44
} | @import "./alert.vars";
// Alert
// --------------------------------------------------
:host {
--min-width: #{$alert-min-width};
--max-height: #{$alert-max-height};
@include font-smoothing();
@include position(0, 0, 0, 0);
display: flex;
position: fixed;
align-items: center;
justify-content: center;
font-family: $font-family-base;
contain: strict;
touch-action: none;
user-select: none;
z-index: $z-index-overlay;
}
:host(.alert-top) {
@include padding(50px, null, null, null);
align-items: flex-start;
}
.alert-wrapper {
display: flex;
flex-direction: column;
min-width: var(--min-width);
max-width: var(--max-width);
max-height: var(--max-height);
background: var(--background);
contain: content;
opacity: 0;
z-index: $z-index-overlay-wrapper;
}
.alert-title {
@include margin(0);
@include padding(0);
}
.alert-sub-title {
@include margin(5px, 0, 0);
@include padding(0);
font-weight: normal;
}
.alert-message {
box-sizing: border-box;
-webkit-overflow-scrolling: touch;
overflow-y: scroll;
overscroll-behavior-y: contain;
}
.alert-message::-webkit-scrollbar {
display: none;
}
.alert-input {
@include padding(10px, 0);
width: 100%;
border: 0;
background: inherit;
font: inherit;
box-sizing: border-box;
}
.alert-button-group {
display: flex;
flex-direction: row;
width: 100%;
}
.alert-button-group-vertical {
flex-direction: column;
flex-wrap: nowrap;
}
.alert-button {
@include margin(0);
display: block;
border: 0;
font-size: $alert-button-font-size;
line-height: $alert-button-line-height;
z-index: 0;
}
.alert-button-inner {
display: flex;
flex-flow: row nowrap;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.alert-tappable {
@include margin(0);
@include padding(0);
width: 100%;
border: 0;
background: transparent;
font-size: inherit;
line-height: initial;
text-align: start;
appearance: none;
}
.alert-button,
.alert-checkbox,
.alert-input,
.alert-radio {
&:active,
&:focus {
outline: none;
}
}
.alert-radio-icon,
.alert-checkbox-icon,
.alert-checkbox-inner {
box-sizing: border-box;
}
| core/src/components/alert/alert.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.002280906541272998,
0.0003685408737510443,
0.00016615676577202976,
0.00017959345132112503,
0.0005133380764164031
] |
{
"id": 1,
"code_window": [
"// Material Design Outline Button\n",
"// --------------------------------------------------\n",
"\n",
":host(.button-outline) {\n",
" --border-width: 1px;\n",
" --border-style: solid;\n",
" --box-shadow: none;\n",
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --border-width: 2px;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 44
} | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule, DomController } from '@ionic/angular';
import { CardPageComponent } from './card-page.component';
import { CardRoutingModule } from './card-routing.module';
@NgModule({
imports: [
CommonModule,
IonicModule,
CardRoutingModule
],
declarations: [
CardPageComponent
],
providers: [
DomController
]
})
export class CardModule { }
| angular/test/testapp/src/app/card/card.module.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.00017243601905647665,
0.00016886176308616996,
0.00016653427155688405,
0.00016761502774897963,
0.000002565597469583736
] |
{
"id": 1,
"code_window": [
"// Material Design Outline Button\n",
"// --------------------------------------------------\n",
"\n",
":host(.button-outline) {\n",
" --border-width: 1px;\n",
" --border-style: solid;\n",
" --box-shadow: none;\n",
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" --border-width: 2px;\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "replace",
"edit_start_line_idx": 44
} | ```typescript
import { Component } from '@angular/core';
import { ToastController } from '@ionic/angular';
@Component({
selector: 'toast-example',
templateUrl: 'toast-example.html',
styleUrls: ['./toast-example.css'],
})
export class ToastExample {
constructor(public toastController: ToastController) {}
async presentToast() {
const toast = await this.toastController.create({
message: 'Your settings have been saved.',
duration: 2000
});
toast.present();
}
async presentToastWithOptions() {
const toast = await this.toastController.create({
message: 'Click to Close',
showCloseButton: true,
position: 'top',
closeButtonText: 'Done'
});
toast.present();
}
}
```
| core/src/components/toast/usage/angular.md | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0001758511789375916,
0.00017121300334110856,
0.00016679569671396166,
0.0001711025834083557,
0.0000034616161883604946
] |
{
"id": 2,
"code_window": [
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
"}\n",
"\n",
":host(.button-outline.activated.ion-color) .button-native {\n",
" background: transparent;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-outline:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-outline.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 52
} | @import "./button";
@import "./button.md.vars";
// Material Design Button
// --------------------------------------------------
:host {
--border-radius: #{$button-md-border-radius};
--margin-top: #{$button-md-margin-top};
--margin-bottom: #{$button-md-margin-bottom};
--margin-start: #{$button-md-margin-start};
--margin-end: #{$button-md-margin-end};
--padding-top: #{$button-md-padding-top};
--padding-bottom: #{$button-md-padding-bottom};
--padding-start: #{$button-md-padding-start};
--padding-end: #{$button-md-padding-end};
--height: #{$button-md-height};
--transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,
background-color $button-md-transition-duration $button-md-transition-timing-function,
color $button-md-transition-duration $button-md-transition-timing-function};
font-size: #{$button-md-font-size};
font-weight: #{$button-md-font-weight};
letter-spacing: #{$button-md-letter-spacing};
text-transform: #{$button-md-text-transform};
}
// Material Design Solid Button
// --------------------------------------------------
:host(.button-solid) {
--box-shadow: #{$button-md-box-shadow};
}
:host(.button-solid.activated) {
--box-shadow: #{$button-md-box-shadow-activated};
}
// Material Design Outline Button
// --------------------------------------------------
:host(.button-outline) {
--border-width: 1px;
--border-style: solid;
--box-shadow: none;
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
}
:host(.button-outline.activated.ion-color) .button-native {
background: transparent;
}
// Material Design Clear Button
// --------------------------------------------------
:host(.button-clear) {
--opacity: #{$button-md-clear-opacity};
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
--color-focused: #{ion-color(primary, base)};
}
// Material Design Round Button
// --------------------------------------------------
:host(.button-round) {
--border-radius: #{$button-md-round-border-radius};
--padding-top: #{$button-md-round-padding-top};
--padding-start: #{$button-md-round-padding-start};
--padding-end: #{$button-md-round-padding-end};
--padding-bottom: #{$button-md-round-padding-bottom};
}
// Material Design Button Sizes
// --------------------------------------------------
:host(.button-large) {
--padding-top: #{$button-md-large-padding-top};
--padding-start: #{$button-md-large-padding-start};
--padding-end: #{$button-md-large-padding-end};
--padding-bottom: #{$button-md-large-padding-bottom};
--height: #{$button-md-large-height};
font-size: #{$button-md-large-font-size};
}
:host(.button-small) {
--padding-top: #{$button-md-small-padding-top};
--padding-start: #{$button-md-small-padding-start};
--padding-end: #{$button-md-small-padding-end};
--padding-bottom: #{$button-md-small-padding-bottom};
--height: #{$button-md-small-height};
font-size: #{$button-md-small-font-size};
}
// MD strong Button
// --------------------------------------------------
:host(.button-strong) {
font-weight: #{$button-md-strong-font-weight};
}
::slotted(ion-icon[slot="icon-only"]) {
@include padding(0);
}
| core/src/components/button/button.md.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.9971479773521423,
0.16908566653728485,
0.00016731898358557373,
0.0002419653465040028,
0.37021902203559875
] |
{
"id": 2,
"code_window": [
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
"}\n",
"\n",
":host(.button-outline.activated.ion-color) .button-native {\n",
" background: transparent;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-outline:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-outline.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 52
} | ```html
<ion-menu>
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
</ion-menu>
<ion-router-outlet main></ion-router-outlet>
```
| core/src/components/menu/usage/angular.md | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0002357446210226044,
0.00020654832769650966,
0.0001773520343704149,
0.00020654832769650966,
0.000029196293326094747
] |
{
"id": 2,
"code_window": [
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
"}\n",
"\n",
":host(.button-outline.activated.ion-color) .button-native {\n",
" background: transparent;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-outline:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-outline.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 52
} | import { Animation } from '../../../interface';
/**
* MD Toast Enter Animation
*/
export function mdEnterAnimation(AnimationC: Animation, baseEl: HTMLElement, position: string): Promise<Animation> {
const baseAnimation = new AnimationC();
const wrapperAnimation = new AnimationC();
const wrapperEle = baseEl.querySelector('.toast-wrapper') as HTMLElement;
wrapperAnimation.addElement(wrapperEle);
switch (position) {
case 'top':
wrapperAnimation.fromTo('translateY', '-100%', '0%');
break;
case 'middle':
const topPosition = Math.floor(
baseEl.clientHeight / 2 - wrapperEle.clientHeight / 2
);
wrapperEle.style.top = `${topPosition}px`;
wrapperAnimation.fromTo('opacity', 0.01, 1);
break;
default:
wrapperAnimation.fromTo('translateY', '100%', '0%');
break;
}
return Promise.resolve(baseAnimation
.addElement(baseEl)
.easing('cubic-bezier(.36,.66,.04,1)')
.duration(400)
.add(wrapperAnimation));
}
| core/src/components/toast/animations/md.enter.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.00017853853933047503,
0.00017580631538294256,
0.0001717986015137285,
0.00017644406761974096,
0.0000025322094643343007
] |
{
"id": 2,
"code_window": [
" --background-activated: transparent;\n",
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
"}\n",
"\n",
":host(.button-outline.activated.ion-color) .button-native {\n",
" background: transparent;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-outline:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-outline.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 52
} | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { BadgePageComponent } from './badge-page.component';
import { BadgeRoutingModule } from './badge-routing.module';
@NgModule({
imports: [
CommonModule,
BadgeRoutingModule,
IonicModule
],
declarations: [BadgePageComponent]
})
export class BadgeModule { }
| angular/test/testapp/src/app/badge/badge.module.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0001769545633578673,
0.00017506966833025217,
0.0001731847587507218,
0.00017506966833025217,
0.0000018849023035727441
] |
{
"id": 3,
"code_window": [
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
" --color-focused: #{ion-color(primary, base)};\n",
"}\n",
"\n",
"\n",
"// Material Design Round Button\n",
"// --------------------------------------------------\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-clear:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-clear.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 68
} | @import "./button";
@import "./button.md.vars";
// Material Design Button
// --------------------------------------------------
:host {
--border-radius: #{$button-md-border-radius};
--margin-top: #{$button-md-margin-top};
--margin-bottom: #{$button-md-margin-bottom};
--margin-start: #{$button-md-margin-start};
--margin-end: #{$button-md-margin-end};
--padding-top: #{$button-md-padding-top};
--padding-bottom: #{$button-md-padding-bottom};
--padding-start: #{$button-md-padding-start};
--padding-end: #{$button-md-padding-end};
--height: #{$button-md-height};
--transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,
background-color $button-md-transition-duration $button-md-transition-timing-function,
color $button-md-transition-duration $button-md-transition-timing-function};
font-size: #{$button-md-font-size};
font-weight: #{$button-md-font-weight};
letter-spacing: #{$button-md-letter-spacing};
text-transform: #{$button-md-text-transform};
}
// Material Design Solid Button
// --------------------------------------------------
:host(.button-solid) {
--box-shadow: #{$button-md-box-shadow};
}
:host(.button-solid.activated) {
--box-shadow: #{$button-md-box-shadow-activated};
}
// Material Design Outline Button
// --------------------------------------------------
:host(.button-outline) {
--border-width: 1px;
--border-style: solid;
--box-shadow: none;
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
}
:host(.button-outline.activated.ion-color) .button-native {
background: transparent;
}
// Material Design Clear Button
// --------------------------------------------------
:host(.button-clear) {
--opacity: #{$button-md-clear-opacity};
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
--color-focused: #{ion-color(primary, base)};
}
// Material Design Round Button
// --------------------------------------------------
:host(.button-round) {
--border-radius: #{$button-md-round-border-radius};
--padding-top: #{$button-md-round-padding-top};
--padding-start: #{$button-md-round-padding-start};
--padding-end: #{$button-md-round-padding-end};
--padding-bottom: #{$button-md-round-padding-bottom};
}
// Material Design Button Sizes
// --------------------------------------------------
:host(.button-large) {
--padding-top: #{$button-md-large-padding-top};
--padding-start: #{$button-md-large-padding-start};
--padding-end: #{$button-md-large-padding-end};
--padding-bottom: #{$button-md-large-padding-bottom};
--height: #{$button-md-large-height};
font-size: #{$button-md-large-font-size};
}
:host(.button-small) {
--padding-top: #{$button-md-small-padding-top};
--padding-start: #{$button-md-small-padding-start};
--padding-end: #{$button-md-small-padding-end};
--padding-bottom: #{$button-md-small-padding-bottom};
--height: #{$button-md-small-height};
font-size: #{$button-md-small-font-size};
}
// MD strong Button
// --------------------------------------------------
:host(.button-strong) {
font-weight: #{$button-md-strong-font-weight};
}
::slotted(ion-icon[slot="icon-only"]) {
@include padding(0);
}
| core/src/components/button/button.md.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.98249751329422,
0.09085244685411453,
0.0001632005732972175,
0.0002978301199618727,
0.2702019214630127
] |
{
"id": 3,
"code_window": [
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
" --color-focused: #{ion-color(primary, base)};\n",
"}\n",
"\n",
"\n",
"// Material Design Round Button\n",
"// --------------------------------------------------\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-clear:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-clear.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 68
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Button - Outline</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="../../../../../dist/ionic.js"></script>
</head>
<body>
<ion-app>
<ion-header>
<ion-toolbar>
<ion-title>Button - Outline</ion-title>
</ion-toolbar>
</ion-header>
<ion-content id="content" padding no-bounce>
<p>
<ion-button fill="outline">Default</ion-button>
<ion-button fill="outline" class="activated">Default.activated</ion-button>
<ion-button fill="outline" class="focused">Default.focused</ion-button>
<ion-button fill="outline" class="activated focused">Default.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="primary">Primary</ion-button>
<ion-button fill="outline" class="activated" color="primary">Primary.activated</ion-button>
<ion-button fill="outline" class="focused" color="primary">Primary.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="primary">Primary.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="secondary">Secondary</ion-button>
<ion-button fill="outline" class="activated" color="secondary">Secondary.activated</ion-button>
<ion-button fill="outline" class="focused" color="secondary">Secondary.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="secondary">Secondary.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="tertiary">Tertiary</ion-button>
<ion-button fill="outline" class="activated" color="tertiary">Tertiary.activated</ion-button>
<ion-button fill="outline" class="focused" color="tertiary">Tertiary.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="tertiary">Tertiary.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="success">Success</ion-button>
<ion-button fill="outline" class="activated" color="success">Success.activated</ion-button>
<ion-button fill="outline" class="focused" color="success">Success.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="success">Success.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="warning">Warning</ion-button>
<ion-button fill="outline" class="activated" color="warning">Warning.activated</ion-button>
<ion-button fill="outline" class="focused" color="warning">Warning.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="warning">Warning.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="danger">Danger</ion-button>
<ion-button fill="outline" class="activated" color="danger">Danger.activated</ion-button>
<ion-button fill="outline" class="focused" color="danger">Danger.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="danger">Danger.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="light">Light</ion-button>
<ion-button fill="outline" class="activated" color="light">Light.activated</ion-button>
<ion-button fill="outline" class="focused" color="light">Light.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="light">Light.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="medium">Medium</ion-button>
<ion-button fill="outline" class="activated" color="medium">Medium.activated</ion-button>
<ion-button fill="outline" class="focused" color="medium">Medium.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="medium">Medium.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" color="dark">Dark</ion-button>
<ion-button fill="outline" class="activated" color="dark">Dark.activated</ion-button>
<ion-button fill="outline" class="focused" color="dark">Dark.focused</ion-button>
<ion-button fill="outline" class="activated focused" color="dark">Dark.activated.focused</ion-button>
</p>
<p>
<ion-button fill="outline" disabled>Disabled</ion-button>
<ion-button fill="outline" color="secondary" disabled>Secondary Disabled</ion-button>
</p>
</ion-content>
</ion-app>
</body>
</html>
| core/src/components/button/test/outline/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0002760194183792919,
0.00020215995027683675,
0.0001658862311160192,
0.00019537920888978988,
0.00003552853377186693
] |
{
"id": 3,
"code_window": [
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
" --color-focused: #{ion-color(primary, base)};\n",
"}\n",
"\n",
"\n",
"// Material Design Round Button\n",
"// --------------------------------------------------\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-clear:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-clear.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 68
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Slides</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="../../../../../dist/ionic.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: red; color: white;">
<h1>Slide 1</h1>
</ion-slide>
<ion-slide style="background: white; color: blue;">
<h1>Slide 2</h1>
</ion-slide>
<ion-slide style="background: blue; color: white;">
<h1>Slide 3</h1>
</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 = {}
function slideNext() {
slides.slideNext(500)
};
function slidePrev() {
slides.slidePrev(500);
};
function slideTo() {
slides.slideTo(2);
}
function slideAutoPlay() {
slides.options = Object.assign({}, slides.options, { autoplay: 300 });
slides.startAutoplay();
}
function slideStopAutoPlay() {
slides.stopAutoplay();
}
function setOptions() {
slides.options = Object.assign({}, slides.options, {
slidesPerView: 2,
});
}
function slideLength() {
console.log(slides.length());
}
function getActiveIndex() {
console.log(slides.getActiveIndex());
};
function getPreviousIndex() {
console.log(slides.getPreviousIndex());
};
function isEnd() {
console.log(slides.isEnd());
}
function isBeginning() {
console.log(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 transistion 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)
});
</script>
</body>
</html>
| core/src/components/slides/test/preview/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.00023430709552485496,
0.0001784637861419469,
0.00016799182048998773,
0.00017236189160030335,
0.000016673879144946113
] |
{
"id": 3,
"code_window": [
" --background-focused: #{ion-color(primary, base, .1)};\n",
" --color-activated: #{ion-color(primary, base)};\n",
" --color-focused: #{ion-color(primary, base)};\n",
"}\n",
"\n",
"\n",
"// Material Design Round Button\n",
"// --------------------------------------------------\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
":host(.button-clear:hover) .button-native {\n",
" background: ion-color(primary, base, .04);\n",
"}\n",
"\n",
":host(.button-clear.ion-color:hover) .button-native {\n",
" background: current-color(base, .04);\n",
"}\n",
"\n"
],
"file_path": "core/src/components/button/button.md.scss",
"type": "add",
"edit_start_line_idx": 68
} | @import "../../themes/ionic.globals";
@import "../fab-button/fab-button.vars";
// Floating Action Button Container
// --------------------------------------------------
/// @prop - Margin of the FAB Container
$fab-content-margin: 10px !default;
| core/src/components/fab/fab.vars.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0002163211756851524,
0.0002163211756851524,
0.0002163211756851524,
0.0002163211756851524,
0
] |
{
"id": 4,
"code_window": [
"\n",
"/// @prop - Box shadow of the button\n",
"$button-md-box-shadow: 0 3px 1px -2px rgba(0, 0, 0, .2), 0 2px 2px 0 rgba(0, 0, 0, .14), 0 1px 5px 0 rgba(0, 0, 0, .12) !default;\n",
"\n",
"/// @prop - Duration of the transition of the button\n",
"$button-md-transition-duration: 300ms !default;\n",
"\n",
"/// @prop - Speed curve of the transition of the button\n",
"$button-md-transition-timing-function: cubic-bezier(.4, 0, .2, 1) !default;\n",
"\n",
"/// @prop - Opacity of the activated button\n",
"$button-md-opacity-activated: 1 !default;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "core/src/components/button/button.md.vars.scss",
"type": "replace",
"edit_start_line_idx": 49
} | @import "./button";
@import "./button.md.vars";
// Material Design Button
// --------------------------------------------------
:host {
--border-radius: #{$button-md-border-radius};
--margin-top: #{$button-md-margin-top};
--margin-bottom: #{$button-md-margin-bottom};
--margin-start: #{$button-md-margin-start};
--margin-end: #{$button-md-margin-end};
--padding-top: #{$button-md-padding-top};
--padding-bottom: #{$button-md-padding-bottom};
--padding-start: #{$button-md-padding-start};
--padding-end: #{$button-md-padding-end};
--height: #{$button-md-height};
--transition: #{box-shadow $button-md-transition-duration $button-md-transition-timing-function,
background-color $button-md-transition-duration $button-md-transition-timing-function,
color $button-md-transition-duration $button-md-transition-timing-function};
font-size: #{$button-md-font-size};
font-weight: #{$button-md-font-weight};
letter-spacing: #{$button-md-letter-spacing};
text-transform: #{$button-md-text-transform};
}
// Material Design Solid Button
// --------------------------------------------------
:host(.button-solid) {
--box-shadow: #{$button-md-box-shadow};
}
:host(.button-solid.activated) {
--box-shadow: #{$button-md-box-shadow-activated};
}
// Material Design Outline Button
// --------------------------------------------------
:host(.button-outline) {
--border-width: 1px;
--border-style: solid;
--box-shadow: none;
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
}
:host(.button-outline.activated.ion-color) .button-native {
background: transparent;
}
// Material Design Clear Button
// --------------------------------------------------
:host(.button-clear) {
--opacity: #{$button-md-clear-opacity};
--background-activated: transparent;
--background-focused: #{ion-color(primary, base, .1)};
--color-activated: #{ion-color(primary, base)};
--color-focused: #{ion-color(primary, base)};
}
// Material Design Round Button
// --------------------------------------------------
:host(.button-round) {
--border-radius: #{$button-md-round-border-radius};
--padding-top: #{$button-md-round-padding-top};
--padding-start: #{$button-md-round-padding-start};
--padding-end: #{$button-md-round-padding-end};
--padding-bottom: #{$button-md-round-padding-bottom};
}
// Material Design Button Sizes
// --------------------------------------------------
:host(.button-large) {
--padding-top: #{$button-md-large-padding-top};
--padding-start: #{$button-md-large-padding-start};
--padding-end: #{$button-md-large-padding-end};
--padding-bottom: #{$button-md-large-padding-bottom};
--height: #{$button-md-large-height};
font-size: #{$button-md-large-font-size};
}
:host(.button-small) {
--padding-top: #{$button-md-small-padding-top};
--padding-start: #{$button-md-small-padding-start};
--padding-end: #{$button-md-small-padding-end};
--padding-bottom: #{$button-md-small-padding-bottom};
--height: #{$button-md-small-height};
font-size: #{$button-md-small-font-size};
}
// MD strong Button
// --------------------------------------------------
:host(.button-strong) {
font-weight: #{$button-md-strong-font-weight};
}
::slotted(ion-icon[slot="icon-only"]) {
@include padding(0);
}
| core/src/components/button/button.md.scss | 1 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.040738850831985474,
0.003641594434157014,
0.0001641471026232466,
0.00020059267990291119,
0.011187048628926277
] |
{
"id": 4,
"code_window": [
"\n",
"/// @prop - Box shadow of the button\n",
"$button-md-box-shadow: 0 3px 1px -2px rgba(0, 0, 0, .2), 0 2px 2px 0 rgba(0, 0, 0, .14), 0 1px 5px 0 rgba(0, 0, 0, .12) !default;\n",
"\n",
"/// @prop - Duration of the transition of the button\n",
"$button-md-transition-duration: 300ms !default;\n",
"\n",
"/// @prop - Speed curve of the transition of the button\n",
"$button-md-transition-timing-function: cubic-bezier(.4, 0, .2, 1) !default;\n",
"\n",
"/// @prop - Opacity of the activated button\n",
"$button-md-opacity-activated: 1 !default;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "core/src/components/button/button.md.vars.scss",
"type": "replace",
"edit_start_line_idx": 49
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Item Sliding - Standalone</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/core.css" rel="stylesheet">
<link href="../../../../../scripts/testing/styles.css" rel="stylesheet">
<script src="../../../../../dist/ionic.js"></script>
</head>
<body>
<ion-item-sliding>
<ion-item>
<ion-label>
One Line, icon only
</ion-label>
</ion-item>
<ion-item-options>
<ion-item-option color="secondary">
<ion-icon slot="icon-only" name="heart"></ion-icon>
</ion-item-option>
<ion-item-option color="danger">
<ion-icon slot="icon-only" name="close"></ion-icon>
</ion-item-option>
</ion-item-options>
</ion-item-sliding>
<ion-item-sliding>
<ion-item>
<ion-label>
One Line, icon and text
</ion-label>
</ion-item>
<ion-item-options>
<ion-item-option color="primary">
<ion-icon name="more"></ion-icon>
<span class="more-text">More</span>
</ion-item-option>
<ion-item-option color="secondary">
<ion-icon name="archive"></ion-icon>
<span class="archive-text">Archive</span>
</ion-item-option>
</ion-item-options>
</ion-item-sliding>
</body>
</html>
| core/src/components/item-sliding/test/standalone/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0001728132920106873,
0.00017171823128592223,
0.00016951965517364442,
0.00017234431288670748,
0.0000012221628367115045
] |
{
"id": 4,
"code_window": [
"\n",
"/// @prop - Box shadow of the button\n",
"$button-md-box-shadow: 0 3px 1px -2px rgba(0, 0, 0, .2), 0 2px 2px 0 rgba(0, 0, 0, .14), 0 1px 5px 0 rgba(0, 0, 0, .12) !default;\n",
"\n",
"/// @prop - Duration of the transition of the button\n",
"$button-md-transition-duration: 300ms !default;\n",
"\n",
"/// @prop - Speed curve of the transition of the button\n",
"$button-md-transition-timing-function: cubic-bezier(.4, 0, .2, 1) !default;\n",
"\n",
"/// @prop - Opacity of the activated button\n",
"$button-md-opacity-activated: 1 !default;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "core/src/components/button/button.md.vars.scss",
"type": "replace",
"edit_start_line_idx": 49
} | // Roboto Font
// Google
// Apache License, version 2.0
// http://www.apache.org/licenses/LICENSE-2.0.html
$roboto-font-path: $font-path !default;
@font-face {
font-family: "Roboto";
font-style: normal;
font-weight: 300;
src: local("Roboto Light"), local("Roboto-Light"), url("#{$roboto-font-path}/roboto-light.woff2") format("woff2"), url("#{$roboto-font-path}/roboto-light.woff") format("woff"), url("#{$roboto-font-path}/roboto-light.ttf") format("truetype");
}
@font-face {
font-family: "Roboto";
font-style: normal;
font-weight: 400;
src: local("Roboto"), local("Roboto-Regular"), url("#{$roboto-font-path}/roboto-regular.woff2") format("woff2"), url("#{$roboto-font-path}/roboto-regular.woff") format("woff"), url("#{$roboto-font-path}/roboto-regular.ttf") format("truetype");
}
@font-face {
font-family: "Roboto";
font-style: normal;
font-weight: 500;
src: local("Roboto Medium"), local("Roboto-Medium"), url("#{$roboto-font-path}/roboto-medium.woff2") format("woff2"), url("#{$roboto-font-path}/roboto-medium.woff") format("woff"), url("#{$roboto-font-path}/roboto-medium.ttf") format("truetype");
}
@font-face {
font-family: "Roboto";
font-style: normal;
font-weight: 700;
src: local("Roboto Bold"), local("Roboto-Bold"), url("#{$roboto-font-path}/roboto-bold.woff2") format("woff2"), url("#{$roboto-font-path}/roboto-bold.woff") format("woff"), url("#{$roboto-font-path}/roboto-bold.ttf") format("truetype");
}
| core/src/components/app/fonts/roboto.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.00017318410391453654,
0.0001722367014735937,
0.00017115013906732202,
0.00017230628873221576,
7.713972536294023e-7
] |
{
"id": 4,
"code_window": [
"\n",
"/// @prop - Box shadow of the button\n",
"$button-md-box-shadow: 0 3px 1px -2px rgba(0, 0, 0, .2), 0 2px 2px 0 rgba(0, 0, 0, .14), 0 1px 5px 0 rgba(0, 0, 0, .12) !default;\n",
"\n",
"/// @prop - Duration of the transition of the button\n",
"$button-md-transition-duration: 300ms !default;\n",
"\n",
"/// @prop - Speed curve of the transition of the button\n",
"$button-md-transition-timing-function: cubic-bezier(.4, 0, .2, 1) !default;\n",
"\n",
"/// @prop - Opacity of the activated button\n",
"$button-md-opacity-activated: 1 !default;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "core/src/components/button/button.md.vars.scss",
"type": "replace",
"edit_start_line_idx": 49
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Button - Strong</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="../../../../../dist/ionic.js"></script>
</head>
<body>
<ion-app>
<ion-header>
<ion-toolbar>
<ion-title>Button - Strong</ion-title>
</ion-toolbar>
</ion-header>
<ion-content id="content" padding no-bounce>
<p>
<ion-button strong>Default</ion-button>
</p>
<p>
<ion-button strong fill="outline" color="secondary">Outline</ion-button>
</p>
<p>
<ion-button strong fill="clear">Clear</ion-button>
</p>
<p>
<ion-button strong expand="block" color="danger">Block</ion-button>
</p>
<p>
<ion-button strong expand="full" color="dark">Full</ion-button>
</p>
<p>
<ion-button strong shape="round">Strong</ion-button>
</p>
</ion-content>
</ion-app>
</body>
</html>
| core/src/components/button/test/strong/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/0faa355139e144005ebc9993f74cf36a73261fcd | [
0.0001735090627335012,
0.00016941851936280727,
0.00016652602062094957,
0.00016731546202208847,
0.000003157573928547208
] |
{
"id": 0,
"code_window": [
" const instance = getCurrentInstance()!\n",
" const durations = normalizeDuration(duration)\n",
" const enterDuration = durations && durations[0]\n",
" const leaveDuration = durations && durations[1]\n",
" const { appear, onBeforeEnter, onEnter, onLeave } = baseProps\n",
"\n",
" // is appearing\n",
" if (appear && !instance.isMounted) {\n",
" enterFromClass = appearFromClass\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const {\n",
" appear,\n",
" onBeforeEnter,\n",
" onEnter,\n",
" onLeave,\n",
" onEnterCancelled,\n",
" onLeaveCancelled\n",
" } = baseProps\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 101
} | import { E2E_TIMEOUT, setupPuppeteer } from './e2eUtils'
import path from 'path'
import { mockWarn } from '@vue/shared'
import { h, createApp, Transition } from 'vue'
describe('e2e: Transition', () => {
mockWarn()
const { page, html, classList, isVisible } = setupPuppeteer()
const baseUrl = `file://${path.resolve(__dirname, './transition.html')}`
const duration = 50
const buffer = 5
const classWhenTransitionStart = () =>
page().evaluate(() => {
(document.querySelector('#toggleBtn') as any)!.click()
return Promise.resolve().then(() => {
return document.querySelector('#container div')!.className.split(/\s+/g)
})
})
const transitionFinish = (time = duration) =>
new Promise(r => {
setTimeout(r, time + buffer)
})
const nextFrame = () => {
return page().evaluate(() => {
return new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(resolve)
})
})
})
}
beforeEach(async () => {
await page().goto(baseUrl)
await page().waitFor('#app')
})
describe('transition with v-if', () => {
test(
'basic transition',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition>
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'v-leave-active',
'v-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'v-leave-active',
'v-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'v-enter-active',
'v-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'v-enter-active',
'v-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'named transition',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'custom transition classes',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition enter-from-class="hello-from"
enter-active-class="hello-active"
enter-to-class="hello-to"
leave-from-class="bye-from"
leave-active-class="bye-active"
leave-to-class="bye-to">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'bye-active',
'bye-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'bye-active',
'bye-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'hello-active',
'hello-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'hello-active',
'hello-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition with dynamic name',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition :name="name">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
<button id="changeNameBtn" @click="changeName">button</button>
`,
setup: () => {
const name = ref('test')
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
const changeName = () => (name.value = 'changed')
return { toggle, click, name, changeName }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
await page().evaluate(() => {
;(document.querySelector('#changeNameBtn') as any).click()
})
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'changed-enter-active',
'changed-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'changed-enter-active',
'changed-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition events without appear',
async () => {
const beforeLeaveSpy = jest.fn()
const onLeaveSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const onEnterSpy = jest.fn()
const afterEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().evaluate(() => {
const {
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
// todo test event with arguments. Note: not get dom, get object. '{}'
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(beforeLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
expect(afterLeaveSpy).toBeCalled()
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).not.toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
test('onEnterCancelled', async () => {
const enterCancelledSpy = jest.fn()
await page().exposeFunction('enterCancelledSpy', enterCancelledSpy)
await page().evaluate(() => {
const { enterCancelledSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@enter-cancelled="enterCancelledSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(false)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
enterCancelledSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
// cancel (leave)
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
// fixme
expect(enterCancelledSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
})
test(
'transition on appear',
async () => {
await page().evaluate(async () => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
// appear
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition events with appear',
async () => {
const onLeaveSpy = jest.fn()
const onEnterSpy = jest.fn()
const onAppearSpy = jest.fn()
const beforeLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const beforeAppearSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const afterEnterSpy = jest.fn()
const afterAppearSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('onAppearSpy', onAppearSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('beforeAppearSpy', beforeAppearSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().exposeFunction('afterAppearSpy', afterAppearSpy)
const appearClass = await page().evaluate(async () => {
const {
beforeAppearSpy,
onAppearSpy,
afterAppearSpy,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy"
@before-appear="beforeAppearSpy"
@appear="onAppearSpy"
@after-appear="afterAppearSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeAppearSpy,
onAppearSpy,
afterAppearSpy,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
return Promise.resolve().then(() => {
return document.querySelector('.test')!.className.split(/\s+/g)
})
})
// appear fixme spy called
expect(appearClass).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
expect(beforeAppearSpy).not.toBeCalled()
expect(onAppearSpy).not.toBeCalled()
expect(afterAppearSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
expect(onAppearSpy).not.toBeCalled()
expect(afterAppearSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterAppearSpy).not.toBeCalled()
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(onLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
expect(afterLeaveSpy).toBeCalled()
// enter fixme spy called
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
// fixme
test(
'css: false',
async () => {
const onLeaveSpy = jest.fn()
const onEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().evaluate(() => {
const { onLeaveSpy, onEnterSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
:css="false"
name="test"
@enter="onEnterSpy"
@leave="onLeaveSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click"></button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click, onLeaveSpy, onEnterSpy }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
await classWhenTransitionStart()
expect(onLeaveSpy).toBeCalled()
expect(await html('#container')).toBe(
'<div class="test">content</div><!--v-if-->'
)
// enter
await classWhenTransitionStart()
expect(onEnterSpy).toBeCalled()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'no transition detected',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="noop">
<div v-if="toggle">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'noop-leave-active',
'noop-leave-from'
])
await nextFrame()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'noop-enter-active',
'noop-enter-from'
])
await nextFrame()
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'animations',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test-anim">
<div v-if="toggle">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-leave-active',
'test-anim-leave-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-leave-active',
'test-anim-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-enter-active',
'test-anim-enter-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-enter-active',
'test-anim-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'explicit transition type',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container"><transition name="test-anim-long" type="animation"><div v-if="toggle">content</div></transition></div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-to'
])
await new Promise(r => {
setTimeout(r, duration + 5)
})
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-to'
])
await new Promise(r => {
setTimeout(r, duration + 5)
})
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'transition on SVG elements',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<svg id="container">
<transition name="test">
<circle v-if="toggle" cx="0" cy="0" r="10" class="test"></circle>
</transition>
</svg>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe(
'<circle cx="0" cy="0" r="10" class="test"></circle>'
)
const svgTransitionStart = () =>
page().evaluate(() => {
document.querySelector('button')!.click()
return Promise.resolve().then(() => {
return document
.querySelector('.test')!
.getAttribute('class')!
.split(/\s+/g)
})
})
// leave
expect(await svgTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await svgTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<circle cx="0" cy="0" r="10" class="test"></circle>'
)
},
E2E_TIMEOUT
)
test(
'custom transition higher-order component',
async () => {
await page().evaluate(() => {
const { createApp, ref, h, Transition } = (window as any).Vue
createApp({
template: `
<div id="container"><my-transition><div v-if="toggle" class="test">content</div></my-transition></div>
<button id="toggleBtn" @click="click">button</button>
`,
components: {
'my-transition': (props: any, { slots }: any) => {
return h(Transition, { name: 'test' }, slots)
}
},
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition on child components with empty root node',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<component class="test" :is="view"></component>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
<button id="changeViewBtn" @click="change">button</button>
`,
components: {
one: {
template: '<div v-if="false">one</div>'
},
two: {
template: '<div>two</div>'
}
},
setup: () => {
const toggle = ref(true)
const view = ref('one')
const click = () => (toggle.value = !toggle.value)
const change = () =>
(view.value = view.value === 'one' ? 'two' : 'one')
return { toggle, click, change, view }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<!--v-if-->')
// change view -> 'two'
await page().evaluate(() => {
(document.querySelector('#changeViewBtn') as any)!.click()
})
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">two</div>')
// change view -> 'one'
await page().evaluate(() => {
(document.querySelector('#changeViewBtn') as any)!.click()
})
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
},
E2E_TIMEOUT
)
})
describe('transition with v-show', () => {
test(
'named transition with v-show',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(await isVisible('.test')).toBe(true)
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
test(
'transition events with v-show',
async () => {
const beforeLeaveSpy = jest.fn()
const onLeaveSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const onEnterSpy = jest.fn()
const afterEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().evaluate(() => {
const {
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(beforeLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
expect(afterLeaveSpy).toBeCalled()
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).not.toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
test(
'onLeaveCancelled (v-show only)',
async () => {
const onLeaveCancelledSpy = jest.fn()
await page().exposeFunction('onLeaveCancelledSpy', onLeaveCancelledSpy)
await page().evaluate(() => {
const { onLeaveCancelledSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-show="toggle" class="test" @leave-cancelled="onLeaveCancelledSpy">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click, onLeaveCancelledSpy }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(await isVisible('.test')).toBe(true)
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
// cancel (enter)
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
// fixme
expect(onLeaveCancelledSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
test(
'transition on appear with v-show',
async () => {
const appearClass = await page().evaluate(async () => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
return Promise.resolve().then(() => {
return document.querySelector('.test')!.className.split(/\s+/g)
})
})
// appear
expect(appearClass).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
})
test(
'warn when used on multiple elements',
async () => {
createApp({
render() {
return h(Transition, null, {
default: () => [h('div'), h('div')]
})
}
}).mount(document.createElement('div'))
expect(
'<transition> can only be used on a single element or component'
).toHaveBeenWarned()
},
E2E_TIMEOUT
)
describe('explicit durations', () => {
test(
'single value',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" duration="${duration * 2}">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'enter with explicit durations',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{ enter: ${duration * 2} }">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'leave with explicit durations',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{ leave: ${duration * 2} }">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'separate enter and leave',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{
enter: ${duration * 4},
leave: ${duration * 2}
}">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(200)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
// fixme
test.todo('warn invalid durations')
})
})
| packages/vue/__tests__/Transition.spec.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.9979952573776245,
0.11134166270494461,
0.00016646680887788534,
0.00023919105296954513,
0.28402888774871826
] |
{
"id": 0,
"code_window": [
" const instance = getCurrentInstance()!\n",
" const durations = normalizeDuration(duration)\n",
" const enterDuration = durations && durations[0]\n",
" const leaveDuration = durations && durations[1]\n",
" const { appear, onBeforeEnter, onEnter, onLeave } = baseProps\n",
"\n",
" // is appearing\n",
" if (appear && !instance.isMounted) {\n",
" enterFromClass = appearFromClass\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const {\n",
" appear,\n",
" onBeforeEnter,\n",
" onEnter,\n",
" onLeave,\n",
" onEnterCancelled,\n",
" onLeaveCancelled\n",
" } = baseProps\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 101
} | 'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/vue.cjs.prod.js')
} else {
module.exports = require('./dist/vue.cjs.js')
}
| packages/vue/index.js | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017493838095106184,
0.00017493838095106184,
0.00017493838095106184,
0.00017493838095106184,
0
] |
{
"id": 0,
"code_window": [
" const instance = getCurrentInstance()!\n",
" const durations = normalizeDuration(duration)\n",
" const enterDuration = durations && durations[0]\n",
" const leaveDuration = durations && durations[1]\n",
" const { appear, onBeforeEnter, onEnter, onLeave } = baseProps\n",
"\n",
" // is appearing\n",
" if (appear && !instance.isMounted) {\n",
" enterFromClass = appearFromClass\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const {\n",
" appear,\n",
" onBeforeEnter,\n",
" onEnter,\n",
" onLeave,\n",
" onEnterCancelled,\n",
" onLeaveCancelled\n",
" } = baseProps\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 101
} | import { shallowReactive, isReactive, reactive } from '../src/reactive'
import { effect } from '../src/effect'
describe('shallowReactive', () => {
test('should not make non-reactive properties reactive', () => {
const props = shallowReactive({ n: { foo: 1 } })
expect(isReactive(props.n)).toBe(false)
})
test('should keep reactive properties reactive', () => {
const props: any = shallowReactive({ n: reactive({ foo: 1 }) })
props.n = reactive({ foo: 2 })
expect(isReactive(props.n)).toBe(true)
})
describe('collections', () => {
test('should be reactive', () => {
const shallowSet = shallowReactive(new Set())
const a = {}
let size
effect(() => {
size = shallowSet.size
})
expect(size).toBe(0)
shallowSet.add(a)
expect(size).toBe(1)
shallowSet.delete(a)
expect(size).toBe(0)
})
test('should not observe when iterating', () => {
const shallowSet = shallowReactive(new Set())
const a = {}
shallowSet.add(a)
const spreadA = [...shallowSet][0]
expect(isReactive(spreadA)).toBe(false)
})
test('should not get reactive entry', () => {
const shallowMap = shallowReactive(new Map())
const a = {}
const key = 'a'
shallowMap.set(key, a)
expect(isReactive(shallowMap.get(key))).toBe(false)
})
test('should not get reactive on foreach', () => {
const shallowSet = shallowReactive(new Set())
const a = {}
shallowSet.add(a)
shallowSet.forEach(x => expect(isReactive(x)).toBe(false))
})
// #1210
test('onTrack on called on objectSpread', () => {
const onTrackFn = jest.fn()
const shallowSet = shallowReactive(new Set())
let a
effect(
() => {
a = Array.from(shallowSet)
},
{
onTrack: onTrackFn
}
)
expect(a).toMatchObject([])
expect(onTrackFn).toHaveBeenCalled()
})
})
describe('array', () => {
test('should be reactive', () => {
const shallowArray = shallowReactive<unknown[]>([])
const a = {}
let size
effect(() => {
size = shallowArray.length
})
expect(size).toBe(0)
shallowArray.push(a)
expect(size).toBe(1)
shallowArray.pop()
expect(size).toBe(0)
})
test('should not observe when iterating', () => {
const shallowArray = shallowReactive<object[]>([])
const a = {}
shallowArray.push(a)
const spreadA = [...shallowArray][0]
expect(isReactive(spreadA)).toBe(false)
})
test('onTrack on called on objectSpread', () => {
const onTrackFn = jest.fn()
const shallowArray = shallowReactive([])
let a
effect(
() => {
a = Array.from(shallowArray)
},
{
onTrack: onTrackFn
}
)
expect(a).toMatchObject([])
expect(onTrackFn).toHaveBeenCalled()
})
})
})
| packages/reactivity/__tests__/shallowReactive.spec.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00023334621801041067,
0.00017845760157797486,
0.00016760671860538423,
0.00017483648844063282,
0.000016231530025834218
] |
{
"id": 0,
"code_window": [
" const instance = getCurrentInstance()!\n",
" const durations = normalizeDuration(duration)\n",
" const enterDuration = durations && durations[0]\n",
" const leaveDuration = durations && durations[1]\n",
" const { appear, onBeforeEnter, onEnter, onLeave } = baseProps\n",
"\n",
" // is appearing\n",
" if (appear && !instance.isMounted) {\n",
" enterFromClass = appearFromClass\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const {\n",
" appear,\n",
" onBeforeEnter,\n",
" onEnter,\n",
" onLeave,\n",
" onEnterCancelled,\n",
" onLeaveCancelled\n",
" } = baseProps\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 101
} | import { patchProp } from '../src/patchProp'
import { ElementWithTransition } from '../src/components/Transition'
import { svgNS } from '../src/nodeOps'
describe('runtime-dom: class patching', () => {
test('basics', () => {
const el = document.createElement('div')
patchProp(el, 'class', null, 'foo')
expect(el.className).toBe('foo')
patchProp(el, 'class', null, null)
expect(el.className).toBe('')
})
test('transition class', () => {
const el = document.createElement('div') as ElementWithTransition
el._vtc = new Set(['bar', 'baz'])
patchProp(el, 'class', null, 'foo')
expect(el.className).toBe('foo bar baz')
patchProp(el, 'class', null, null)
expect(el.className).toBe('bar baz')
delete el._vtc
patchProp(el, 'class', null, 'foo')
expect(el.className).toBe('foo')
})
test('svg', () => {
const el = document.createElementNS(svgNS, 'svg')
patchProp(el, 'class', null, 'foo', true)
expect(el.getAttribute('class')).toBe('foo')
})
})
| packages/runtime-dom/__tests__/patchClass.spec.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017999281408265233,
0.0001772861141944304,
0.00017521499830763787,
0.0001769683149177581,
0.0000017189596519529005
] |
{
"id": 1,
"code_window": [
" enterActiveClass = appearActiveClass\n",
" enterToClass = appearToClass\n",
" }\n",
"\n",
" type Hook = (el: Element, done?: () => void) => void\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" type Hook =\n",
" | ((el: Element, done: () => void) => void)\n",
" | ((el: Element) => void)\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 110
} | import {
BaseTransition,
BaseTransitionProps,
h,
warn,
FunctionalComponent,
getCurrentInstance,
callWithAsyncErrorHandling
} from '@vue/runtime-core'
import { isObject, toNumber, extend } from '@vue/shared'
import { ErrorCodes } from 'packages/runtime-core/src/errorHandling'
const TRANSITION = 'transition'
const ANIMATION = 'animation'
export interface TransitionProps extends BaseTransitionProps<Element> {
name?: string
type?: typeof TRANSITION | typeof ANIMATION
css?: boolean
duration?: number | { enter: number; leave: number }
// custom transition classes
enterFromClass?: string
enterActiveClass?: string
enterToClass?: string
appearFromClass?: string
appearActiveClass?: string
appearToClass?: string
leaveFromClass?: string
leaveActiveClass?: string
leaveToClass?: string
}
// DOM Transition is a higher-order-component based on the platform-agnostic
// base Transition component, with DOM-specific logic.
export const Transition: FunctionalComponent<TransitionProps> = (
props,
{ slots }
) => h(BaseTransition, resolveTransitionProps(props), slots)
Transition.inheritRef = true
const DOMTransitionPropsValidators = {
name: String,
type: String,
css: {
type: Boolean,
default: true
},
duration: [String, Number, Object],
enterFromClass: String,
enterActiveClass: String,
enterToClass: String,
appearFromClass: String,
appearActiveClass: String,
appearToClass: String,
leaveFromClass: String,
leaveActiveClass: String,
leaveToClass: String
}
export const TransitionPropsValidators = (Transition.props = extend(
{},
(BaseTransition as any).props,
DOMTransitionPropsValidators
))
export function resolveTransitionProps(
rawProps: TransitionProps
): BaseTransitionProps<Element> {
let {
name = 'v',
type,
css = true,
duration,
enterFromClass = `${name}-enter-from`,
enterActiveClass = `${name}-enter-active`,
enterToClass = `${name}-enter-to`,
appearFromClass = enterFromClass,
appearActiveClass = enterActiveClass,
appearToClass = enterToClass,
leaveFromClass = `${name}-leave-from`,
leaveActiveClass = `${name}-leave-active`,
leaveToClass = `${name}-leave-to`
} = rawProps
const baseProps: BaseTransitionProps<Element> = {}
for (const key in rawProps) {
if (!(key in DOMTransitionPropsValidators)) {
;(baseProps as any)[key] = (rawProps as any)[key]
}
}
if (!css) {
return baseProps
}
const originEnterClass = [enterFromClass, enterActiveClass, enterToClass]
const instance = getCurrentInstance()!
const durations = normalizeDuration(duration)
const enterDuration = durations && durations[0]
const leaveDuration = durations && durations[1]
const { appear, onBeforeEnter, onEnter, onLeave } = baseProps
// is appearing
if (appear && !instance.isMounted) {
enterFromClass = appearFromClass
enterActiveClass = appearActiveClass
enterToClass = appearToClass
}
type Hook = (el: Element, done?: () => void) => void
const finishEnter: Hook = (el, done) => {
removeTransitionClass(el, enterToClass)
removeTransitionClass(el, enterActiveClass)
done && done()
// reset enter class
if (appear) {
;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass
}
}
const finishLeave: Hook = (el, done) => {
removeTransitionClass(el, leaveToClass)
removeTransitionClass(el, leaveActiveClass)
done && done()
}
// only needed for user hooks called in nextFrame
// sync errors are already handled by BaseTransition
function callHookWithErrorHandling(hook: Hook, args: any[]) {
callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)
}
return extend(baseProps, {
onBeforeEnter(el) {
onBeforeEnter && onBeforeEnter(el)
addTransitionClass(el, enterActiveClass)
addTransitionClass(el, enterFromClass)
},
onEnter(el, done) {
nextFrame(() => {
const resolve = () => finishEnter(el, done)
onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])
removeTransitionClass(el, enterFromClass)
addTransitionClass(el, enterToClass)
if (!(onEnter && onEnter.length > 1)) {
if (enterDuration) {
setTimeout(resolve, enterDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onLeave(el, done) {
addTransitionClass(el, leaveActiveClass)
addTransitionClass(el, leaveFromClass)
nextFrame(() => {
const resolve = () => finishLeave(el, done)
onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])
removeTransitionClass(el, leaveFromClass)
addTransitionClass(el, leaveToClass)
if (!(onLeave && onLeave.length > 1)) {
if (leaveDuration) {
setTimeout(resolve, leaveDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onEnterCancelled: finishEnter,
onLeaveCancelled: finishLeave
} as BaseTransitionProps<Element>)
}
function normalizeDuration(
duration: TransitionProps['duration']
): [number, number] | null {
if (duration == null) {
return null
} else if (isObject(duration)) {
return [NumberOf(duration.enter), NumberOf(duration.leave)]
} else {
const n = NumberOf(duration)
return [n, n]
}
}
function NumberOf(val: unknown): number {
const res = toNumber(val)
if (__DEV__) validateDuration(res)
return res
}
function validateDuration(val: unknown) {
if (typeof val !== 'number') {
warn(
`<transition> explicit duration is not a valid number - ` +
`got ${JSON.stringify(val)}.`
)
} else if (isNaN(val)) {
warn(
`<transition> explicit duration is NaN - ` +
'the duration expression might be incorrect.'
)
}
}
export interface ElementWithTransition extends HTMLElement {
// _vtc = Vue Transition Classes.
// Store the temporarily-added transition classes on the element
// so that we can avoid overwriting them if the element's class is patched
// during the transition.
_vtc?: Set<string>
}
export function addTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.add(c))
;(
(el as ElementWithTransition)._vtc ||
((el as ElementWithTransition)._vtc = new Set())
).add(cls)
}
export function removeTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.remove(c))
const { _vtc } = el as ElementWithTransition
if (_vtc) {
_vtc.delete(cls)
if (!_vtc!.size) {
;(el as ElementWithTransition)._vtc = undefined
}
}
}
function nextFrame(cb: () => void) {
requestAnimationFrame(() => {
requestAnimationFrame(cb)
})
}
function whenTransitionEnds(
el: Element,
expectedType: TransitionProps['type'] | undefined,
cb: () => void
) {
const { type, timeout, propCount } = getTransitionInfo(el, expectedType)
if (!type) {
return cb()
}
const endEvent = type + 'end'
let ended = 0
const end = () => {
el.removeEventListener(endEvent, onEnd)
cb()
}
const onEnd = (e: Event) => {
if (e.target === el) {
if (++ended >= propCount) {
end()
}
}
}
setTimeout(() => {
if (ended < propCount) {
end()
}
}, timeout + 1)
el.addEventListener(endEvent, onEnd)
}
interface CSSTransitionInfo {
type: typeof TRANSITION | typeof ANIMATION | null
propCount: number
timeout: number
hasTransform: boolean
}
export function getTransitionInfo(
el: Element,
expectedType?: TransitionProps['type']
): CSSTransitionInfo {
const styles: any = window.getComputedStyle(el)
// JSDOM may return undefined for transition properties
const getStyleProperties = (key: string) => (styles[key] || '').split(', ')
const transitionDelays = getStyleProperties(TRANSITION + 'Delay')
const transitionDurations = getStyleProperties(TRANSITION + 'Duration')
const transitionTimeout = getTimeout(transitionDelays, transitionDurations)
const animationDelays = getStyleProperties(ANIMATION + 'Delay')
const animationDurations = getStyleProperties(ANIMATION + 'Duration')
const animationTimeout = getTimeout(animationDelays, animationDurations)
let type: CSSTransitionInfo['type'] = null
let timeout = 0
let propCount = 0
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION
timeout = transitionTimeout
propCount = transitionDurations.length
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION
timeout = animationTimeout
propCount = animationDurations.length
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout)
type =
timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0
}
const hasTransform =
type === TRANSITION &&
/\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property'])
return {
type,
timeout,
propCount,
hasTransform
}
}
function getTimeout(delays: string[], durations: string[]): number {
while (delays.length < durations.length) {
delays = delays.concat(delays)
}
return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])))
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
// numbers in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down
// (i.e. acting as a floor function) causing unexpected behaviors
function toMs(s: string): number {
return Number(s.slice(0, -1).replace(',', '.')) * 1000
}
| packages/runtime-dom/src/components/Transition.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.9979434609413147,
0.23180538415908813,
0.00016328056517522782,
0.0003405681636650115,
0.40858137607574463
] |
{
"id": 1,
"code_window": [
" enterActiveClass = appearActiveClass\n",
" enterToClass = appearToClass\n",
" }\n",
"\n",
" type Hook = (el: Element, done?: () => void) => void\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" type Hook =\n",
" | ((el: Element, done: () => void) => void)\n",
" | ((el: Element) => void)\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 110
} | import {
ComponentInternalInstance,
FunctionalComponent,
Data
} from './component'
import {
VNode,
normalizeVNode,
createVNode,
Comment,
cloneVNode,
Fragment,
VNodeArrayChildren,
isVNode
} from './vnode'
import { handleError, ErrorCodes } from './errorHandling'
import { PatchFlags, ShapeFlags, isOn } from '@vue/shared'
import { warn } from './warning'
import { isHmrUpdating } from './hmr'
// mark the current rendering instance for asset resolution (e.g.
// resolveComponent, resolveDirective) during render
export let currentRenderingInstance: ComponentInternalInstance | null = null
export function setCurrentRenderingInstance(
instance: ComponentInternalInstance | null
) {
currentRenderingInstance = instance
}
// dev only flag to track whether $attrs was used during render.
// If $attrs was used during render then the warning for failed attrs
// fallthrough can be suppressed.
let accessedAttrs: boolean = false
export function markAttrsAccessed() {
accessedAttrs = true
}
export function renderComponentRoot(
instance: ComponentInternalInstance
): VNode {
const {
type: Component,
parent,
vnode,
proxy,
withProxy,
props,
slots,
attrs,
emit,
renderCache
} = instance
let result
currentRenderingInstance = instance
if (__DEV__) {
accessedAttrs = false
}
try {
let fallthroughAttrs
if (vnode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT) {
// withProxy is a proxy with a different `has` trap only for
// runtime-compiled render functions using `with` block.
const proxyToUse = withProxy || proxy
result = normalizeVNode(
instance.render!.call(proxyToUse, proxyToUse!, renderCache)
)
fallthroughAttrs = attrs
} else {
// functional
const render = Component as FunctionalComponent
// in dev, mark attrs accessed if optional props (attrs === props)
if (__DEV__ && attrs === props) {
markAttrsAccessed()
}
result = normalizeVNode(
render.length > 1
? render(
props,
__DEV__
? {
get attrs() {
markAttrsAccessed()
return attrs
},
slots,
emit
}
: { attrs, slots, emit }
)
: render(props, null as any /* we know it doesn't need it */)
)
fallthroughAttrs = Component.props ? attrs : getFallthroughAttrs(attrs)
}
// attr merging
// in dev mode, comments are preserved, and it's possible for a template
// to have comments along side the root element which makes it a fragment
let root = result
let setRoot: ((root: VNode) => void) | undefined = undefined
if (__DEV__) {
;[root, setRoot] = getChildRoot(result)
}
if (
Component.inheritAttrs !== false &&
fallthroughAttrs &&
Object.keys(fallthroughAttrs).length
) {
if (
root.shapeFlag & ShapeFlags.ELEMENT ||
root.shapeFlag & ShapeFlags.COMPONENT
) {
root = cloneVNode(root, fallthroughAttrs)
} else if (__DEV__ && !accessedAttrs && root.type !== Comment) {
const allAttrs = Object.keys(attrs)
const eventAttrs: string[] = []
const extraAttrs: string[] = []
for (let i = 0, l = allAttrs.length; i < l; i++) {
const key = allAttrs[i]
if (isOn(key)) {
// remove `on`, lowercase first letter to reflect event casing accurately
eventAttrs.push(key[2].toLowerCase() + key.slice(3))
} else {
extraAttrs.push(key)
}
}
if (extraAttrs.length) {
warn(
`Extraneous non-props attributes (` +
`${extraAttrs.join(', ')}) ` +
`were passed to component but could not be automatically inherited ` +
`because component renders fragment or text root nodes.`
)
}
if (eventAttrs.length) {
warn(
`Extraneous non-emits event listeners (` +
`${eventAttrs.join(', ')}) ` +
`were passed to component but could not be automatically inherited ` +
`because component renders fragment or text root nodes. ` +
`If the listener is intended to be a component custom event listener only, ` +
`declare it using the "emits" option.`
)
}
}
}
// inherit scopeId
const parentScopeId = parent && parent.type.__scopeId
if (parentScopeId) {
root = cloneVNode(root, { [parentScopeId]: '' })
}
// inherit directives
if (vnode.dirs) {
if (__DEV__ && !isElementRoot(root)) {
warn(
`Runtime directive used on component with non-element root node. ` +
`The directives will not function as intended.`
)
}
root.dirs = vnode.dirs
}
// inherit transition data
if (vnode.transition) {
if (__DEV__ && !isElementRoot(root)) {
warn(
`Component inside <Transition> renders non-element root node ` +
`that cannot be animated.`
)
}
root.transition = vnode.transition
}
// inherit ref
if (Component.inheritRef && vnode.ref != null) {
root.ref = vnode.ref
}
if (__DEV__ && setRoot) {
setRoot(root)
} else {
result = root
}
} catch (err) {
handleError(err, instance, ErrorCodes.RENDER_FUNCTION)
result = createVNode(Comment)
}
currentRenderingInstance = null
return result
}
const getChildRoot = (
vnode: VNode
): [VNode, ((root: VNode) => void) | undefined] => {
if (vnode.type !== Fragment) {
return [vnode, undefined]
}
const rawChildren = vnode.children as VNodeArrayChildren
const dynamicChildren = vnode.dynamicChildren as VNodeArrayChildren
const children = rawChildren.filter(child => {
return !(isVNode(child) && child.type === Comment)
})
if (children.length !== 1) {
return [vnode, undefined]
}
const childRoot = children[0]
const index = rawChildren.indexOf(childRoot)
const dynamicIndex = dynamicChildren
? dynamicChildren.indexOf(childRoot)
: null
const setRoot = (updatedRoot: VNode) => {
rawChildren[index] = updatedRoot
if (dynamicIndex !== null) dynamicChildren[dynamicIndex] = updatedRoot
}
return [normalizeVNode(childRoot), setRoot]
}
const getFallthroughAttrs = (attrs: Data): Data | undefined => {
let res: Data | undefined
for (const key in attrs) {
if (key === 'class' || key === 'style' || isOn(key)) {
;(res || (res = {}))[key] = attrs[key]
}
}
return res
}
const isElementRoot = (vnode: VNode) => {
return (
vnode.shapeFlag & ShapeFlags.COMPONENT ||
vnode.shapeFlag & ShapeFlags.ELEMENT ||
vnode.type === Comment // potential v-if branch switch
)
}
export function shouldUpdateComponent(
prevVNode: VNode,
nextVNode: VNode,
optimized?: boolean
): boolean {
const { props: prevProps, children: prevChildren } = prevVNode
const { props: nextProps, children: nextChildren, patchFlag } = nextVNode
// Parent component's render function was hot-updated. Since this may have
// caused the child component's slots content to have changed, we need to
// force the child to update as well.
if (__DEV__ && (prevChildren || nextChildren) && isHmrUpdating) {
return true
}
// force child update for runtime directive or transition on component vnode.
if (nextVNode.dirs || nextVNode.transition) {
return true
}
if (patchFlag > 0) {
if (patchFlag & PatchFlags.DYNAMIC_SLOTS) {
// slot content that references values that might have changed,
// e.g. in a v-for
return true
}
if (patchFlag & PatchFlags.FULL_PROPS) {
if (!prevProps) {
return !!nextProps
}
// presence of this flag indicates props are always non-null
return hasPropsChanged(prevProps, nextProps!)
} else if (patchFlag & PatchFlags.PROPS) {
const dynamicProps = nextVNode.dynamicProps!
for (let i = 0; i < dynamicProps.length; i++) {
const key = dynamicProps[i]
if (nextProps![key] !== prevProps![key]) {
return true
}
}
}
} else if (!optimized) {
// this path is only taken by manually written render functions
// so presence of any children leads to a forced update
if (prevChildren || nextChildren) {
if (!nextChildren || !(nextChildren as any).$stable) {
return true
}
}
if (prevProps === nextProps) {
return false
}
if (!prevProps) {
return !!nextProps
}
if (!nextProps) {
return true
}
return hasPropsChanged(prevProps, nextProps)
}
return false
}
function hasPropsChanged(prevProps: Data, nextProps: Data): boolean {
const nextKeys = Object.keys(nextProps)
if (nextKeys.length !== Object.keys(prevProps).length) {
return true
}
for (let i = 0; i < nextKeys.length; i++) {
const key = nextKeys[i]
if (nextProps[key] !== prevProps[key]) {
return true
}
}
return false
}
export function updateHOCHostEl(
{ vnode, parent }: ComponentInternalInstance,
el: typeof vnode.el // HostNode
) {
while (parent && parent.subTree === vnode) {
;(vnode = parent.vnode).el = el
parent = parent.parent
}
}
| packages/runtime-core/src/componentRenderUtils.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017674648552201688,
0.00017152703367173672,
0.00016625392891000956,
0.0001715474936645478,
0.000002842764160959632
] |
{
"id": 1,
"code_window": [
" enterActiveClass = appearActiveClass\n",
" enterToClass = appearToClass\n",
" }\n",
"\n",
" type Hook = (el: Element, done?: () => void) => void\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" type Hook =\n",
" | ((el: Element, done: () => void) => void)\n",
" | ((el: Element) => void)\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 110
} | <script src="../../../../node_modules/marked/marked.min.js"></script>
<script src="../../../../node_modules/lodash/lodash.min.js"></script>
<script src="../../dist/vue.global.js"></script>
<div id="editor">
<textarea :value="input" @input="update"></textarea>
<div v-html="output"></div>
</div>
<script>
const delay = window.location.hash === '#test' ? 16 : 300
const { ref, computed } = Vue
Vue.createApp({
setup() {
const input = ref('# hello')
const output = computed(() => marked(input.value, { sanitize: true }))
const update = _.debounce(e => { input.value = e.target.value }, delay)
return {
input,
output,
update
}
}
}).mount('#editor')
</script>
<style>
html, body, #editor {
margin: 0;
height: 100%;
font-family: 'Helvetica Neue', Arial, sans-serif;
color: #333;
}
textarea, #editor div {
display: inline-block;
overflow: auto;
width: 50%;
height: 100%;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0 20px;
}
textarea {
border: none;
border-right: 1px solid #ccc;
resize: none;
outline: none;
background-color: #f6f6f6;
font-size: 14px;
font-family: 'Monaco', courier, monospace;
padding: 20px;
}
code {
color: #f66;
}
</style>
| packages/vue/examples/composition/markdown.html | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017641109297983348,
0.0001732604141579941,
0.00016922573558986187,
0.00017331972776446491,
0.00000230960995395435
] |
{
"id": 1,
"code_window": [
" enterActiveClass = appearActiveClass\n",
" enterToClass = appearToClass\n",
" }\n",
"\n",
" type Hook = (el: Element, done?: () => void) => void\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" type Hook =\n",
" | ((el: Element, done: () => void) => void)\n",
" | ((el: Element) => void)\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 110
} | import { renderSlot } from '../../src/helpers/renderSlot'
import { h } from '../../src/h'
import { mockWarn } from '@vue/shared'
describe('renderSlot', () => {
mockWarn()
it('should render slot', () => {
let child
const vnode = renderSlot(
{ default: () => [(child = h('child'))] },
'default'
)
expect(vnode.children).toEqual([child])
})
it('should render slot fallback', () => {
const vnode = renderSlot({}, 'default', {}, () => ['fallback'])
expect(vnode.children).toEqual(['fallback'])
})
it('should warn render ssr slot', () => {
renderSlot({ default: (a, b, c) => [h('child')] }, 'default')
expect('SSR-optimized slot function detected').toHaveBeenWarned()
})
})
| packages/runtime-core/__tests__/helpers/renderSlot.spec.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017520914843771607,
0.00017351977294310927,
0.0001714920363156125,
0.0001738581486279145,
0.000001536251261313737
] |
{
"id": 2,
"code_window": [
"\n",
" const finishEnter: Hook = (el, done) => {\n",
" removeTransitionClass(el, enterToClass)\n",
" removeTransitionClass(el, enterActiveClass)\n",
" done && done()\n",
" // reset enter class\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishEnter = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 112
} | import {
BaseTransition,
BaseTransitionProps,
h,
warn,
FunctionalComponent,
getCurrentInstance,
callWithAsyncErrorHandling
} from '@vue/runtime-core'
import { isObject, toNumber, extend } from '@vue/shared'
import { ErrorCodes } from 'packages/runtime-core/src/errorHandling'
const TRANSITION = 'transition'
const ANIMATION = 'animation'
export interface TransitionProps extends BaseTransitionProps<Element> {
name?: string
type?: typeof TRANSITION | typeof ANIMATION
css?: boolean
duration?: number | { enter: number; leave: number }
// custom transition classes
enterFromClass?: string
enterActiveClass?: string
enterToClass?: string
appearFromClass?: string
appearActiveClass?: string
appearToClass?: string
leaveFromClass?: string
leaveActiveClass?: string
leaveToClass?: string
}
// DOM Transition is a higher-order-component based on the platform-agnostic
// base Transition component, with DOM-specific logic.
export const Transition: FunctionalComponent<TransitionProps> = (
props,
{ slots }
) => h(BaseTransition, resolveTransitionProps(props), slots)
Transition.inheritRef = true
const DOMTransitionPropsValidators = {
name: String,
type: String,
css: {
type: Boolean,
default: true
},
duration: [String, Number, Object],
enterFromClass: String,
enterActiveClass: String,
enterToClass: String,
appearFromClass: String,
appearActiveClass: String,
appearToClass: String,
leaveFromClass: String,
leaveActiveClass: String,
leaveToClass: String
}
export const TransitionPropsValidators = (Transition.props = extend(
{},
(BaseTransition as any).props,
DOMTransitionPropsValidators
))
export function resolveTransitionProps(
rawProps: TransitionProps
): BaseTransitionProps<Element> {
let {
name = 'v',
type,
css = true,
duration,
enterFromClass = `${name}-enter-from`,
enterActiveClass = `${name}-enter-active`,
enterToClass = `${name}-enter-to`,
appearFromClass = enterFromClass,
appearActiveClass = enterActiveClass,
appearToClass = enterToClass,
leaveFromClass = `${name}-leave-from`,
leaveActiveClass = `${name}-leave-active`,
leaveToClass = `${name}-leave-to`
} = rawProps
const baseProps: BaseTransitionProps<Element> = {}
for (const key in rawProps) {
if (!(key in DOMTransitionPropsValidators)) {
;(baseProps as any)[key] = (rawProps as any)[key]
}
}
if (!css) {
return baseProps
}
const originEnterClass = [enterFromClass, enterActiveClass, enterToClass]
const instance = getCurrentInstance()!
const durations = normalizeDuration(duration)
const enterDuration = durations && durations[0]
const leaveDuration = durations && durations[1]
const { appear, onBeforeEnter, onEnter, onLeave } = baseProps
// is appearing
if (appear && !instance.isMounted) {
enterFromClass = appearFromClass
enterActiveClass = appearActiveClass
enterToClass = appearToClass
}
type Hook = (el: Element, done?: () => void) => void
const finishEnter: Hook = (el, done) => {
removeTransitionClass(el, enterToClass)
removeTransitionClass(el, enterActiveClass)
done && done()
// reset enter class
if (appear) {
;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass
}
}
const finishLeave: Hook = (el, done) => {
removeTransitionClass(el, leaveToClass)
removeTransitionClass(el, leaveActiveClass)
done && done()
}
// only needed for user hooks called in nextFrame
// sync errors are already handled by BaseTransition
function callHookWithErrorHandling(hook: Hook, args: any[]) {
callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)
}
return extend(baseProps, {
onBeforeEnter(el) {
onBeforeEnter && onBeforeEnter(el)
addTransitionClass(el, enterActiveClass)
addTransitionClass(el, enterFromClass)
},
onEnter(el, done) {
nextFrame(() => {
const resolve = () => finishEnter(el, done)
onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])
removeTransitionClass(el, enterFromClass)
addTransitionClass(el, enterToClass)
if (!(onEnter && onEnter.length > 1)) {
if (enterDuration) {
setTimeout(resolve, enterDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onLeave(el, done) {
addTransitionClass(el, leaveActiveClass)
addTransitionClass(el, leaveFromClass)
nextFrame(() => {
const resolve = () => finishLeave(el, done)
onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])
removeTransitionClass(el, leaveFromClass)
addTransitionClass(el, leaveToClass)
if (!(onLeave && onLeave.length > 1)) {
if (leaveDuration) {
setTimeout(resolve, leaveDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onEnterCancelled: finishEnter,
onLeaveCancelled: finishLeave
} as BaseTransitionProps<Element>)
}
function normalizeDuration(
duration: TransitionProps['duration']
): [number, number] | null {
if (duration == null) {
return null
} else if (isObject(duration)) {
return [NumberOf(duration.enter), NumberOf(duration.leave)]
} else {
const n = NumberOf(duration)
return [n, n]
}
}
function NumberOf(val: unknown): number {
const res = toNumber(val)
if (__DEV__) validateDuration(res)
return res
}
function validateDuration(val: unknown) {
if (typeof val !== 'number') {
warn(
`<transition> explicit duration is not a valid number - ` +
`got ${JSON.stringify(val)}.`
)
} else if (isNaN(val)) {
warn(
`<transition> explicit duration is NaN - ` +
'the duration expression might be incorrect.'
)
}
}
export interface ElementWithTransition extends HTMLElement {
// _vtc = Vue Transition Classes.
// Store the temporarily-added transition classes on the element
// so that we can avoid overwriting them if the element's class is patched
// during the transition.
_vtc?: Set<string>
}
export function addTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.add(c))
;(
(el as ElementWithTransition)._vtc ||
((el as ElementWithTransition)._vtc = new Set())
).add(cls)
}
export function removeTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.remove(c))
const { _vtc } = el as ElementWithTransition
if (_vtc) {
_vtc.delete(cls)
if (!_vtc!.size) {
;(el as ElementWithTransition)._vtc = undefined
}
}
}
function nextFrame(cb: () => void) {
requestAnimationFrame(() => {
requestAnimationFrame(cb)
})
}
function whenTransitionEnds(
el: Element,
expectedType: TransitionProps['type'] | undefined,
cb: () => void
) {
const { type, timeout, propCount } = getTransitionInfo(el, expectedType)
if (!type) {
return cb()
}
const endEvent = type + 'end'
let ended = 0
const end = () => {
el.removeEventListener(endEvent, onEnd)
cb()
}
const onEnd = (e: Event) => {
if (e.target === el) {
if (++ended >= propCount) {
end()
}
}
}
setTimeout(() => {
if (ended < propCount) {
end()
}
}, timeout + 1)
el.addEventListener(endEvent, onEnd)
}
interface CSSTransitionInfo {
type: typeof TRANSITION | typeof ANIMATION | null
propCount: number
timeout: number
hasTransform: boolean
}
export function getTransitionInfo(
el: Element,
expectedType?: TransitionProps['type']
): CSSTransitionInfo {
const styles: any = window.getComputedStyle(el)
// JSDOM may return undefined for transition properties
const getStyleProperties = (key: string) => (styles[key] || '').split(', ')
const transitionDelays = getStyleProperties(TRANSITION + 'Delay')
const transitionDurations = getStyleProperties(TRANSITION + 'Duration')
const transitionTimeout = getTimeout(transitionDelays, transitionDurations)
const animationDelays = getStyleProperties(ANIMATION + 'Delay')
const animationDurations = getStyleProperties(ANIMATION + 'Duration')
const animationTimeout = getTimeout(animationDelays, animationDurations)
let type: CSSTransitionInfo['type'] = null
let timeout = 0
let propCount = 0
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION
timeout = transitionTimeout
propCount = transitionDurations.length
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION
timeout = animationTimeout
propCount = animationDurations.length
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout)
type =
timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0
}
const hasTransform =
type === TRANSITION &&
/\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property'])
return {
type,
timeout,
propCount,
hasTransform
}
}
function getTimeout(delays: string[], durations: string[]): number {
while (delays.length < durations.length) {
delays = delays.concat(delays)
}
return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])))
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
// numbers in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down
// (i.e. acting as a floor function) causing unexpected behaviors
function toMs(s: string): number {
return Number(s.slice(0, -1).replace(',', '.')) * 1000
}
| packages/runtime-dom/src/components/Transition.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.9990535378456116,
0.08931291848421097,
0.00016429820971097797,
0.001006038160994649,
0.27453505992889404
] |
{
"id": 2,
"code_window": [
"\n",
" const finishEnter: Hook = (el, done) => {\n",
" removeTransitionClass(el, enterToClass)\n",
" removeTransitionClass(el, enterActiveClass)\n",
" done && done()\n",
" // reset enter class\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishEnter = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 112
} | 'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/compiler-core.cjs.prod.js')
} else {
module.exports = require('./dist/compiler-core.cjs.js')
}
| packages/compiler-core/index.js | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017364924133289605,
0.00017364924133289605,
0.00017364924133289605,
0.00017364924133289605,
0
] |
{
"id": 2,
"code_window": [
"\n",
" const finishEnter: Hook = (el, done) => {\n",
" removeTransitionClass(el, enterToClass)\n",
" removeTransitionClass(el, enterActiveClass)\n",
" done && done()\n",
" // reset enter class\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishEnter = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 112
} | import { createApp, h, Teleport } from 'vue'
import { renderToString, SSRContext } from '../src/renderToString'
import { ssrRenderTeleport } from '../src/helpers/ssrRenderTeleport'
describe('ssrRenderTeleport', () => {
test('teleport rendering (compiled)', async () => {
const ctx: SSRContext = {}
const html = await renderToString(
createApp({
data() {
return { msg: 'hello' }
},
ssrRender(_ctx, _push, _parent) {
ssrRenderTeleport(
_push,
_push => {
_push(`<div>content</div>`)
},
'#target',
false,
_parent
)
}
}),
ctx
)
expect(html).toBe('<!--teleport start--><!--teleport end-->')
expect(ctx.teleports!['#target']).toBe(`<div>content</div><!---->`)
})
test('teleport rendering (compiled + disabled)', async () => {
const ctx: SSRContext = {}
const html = await renderToString(
createApp({
data() {
return { msg: 'hello' }
},
ssrRender(_ctx, _push, _parent) {
ssrRenderTeleport(
_push,
_push => {
_push(`<div>content</div>`)
},
'#target',
true,
_parent
)
}
}),
ctx
)
expect(html).toBe(
'<!--teleport start--><div>content</div><!--teleport end-->'
)
expect(ctx.teleports!['#target']).toBe(`<!---->`)
})
test('teleport rendering (vnode)', async () => {
const ctx: SSRContext = {}
const html = await renderToString(
h(
Teleport,
{
to: `#target`
},
h('span', 'hello')
),
ctx
)
expect(html).toBe('<!--teleport start--><!--teleport end-->')
expect(ctx.teleports!['#target']).toBe('<span>hello</span><!---->')
})
test('teleport rendering (vnode + disabled)', async () => {
const ctx: SSRContext = {}
const html = await renderToString(
h(
Teleport,
{
to: `#target`,
disabled: true
},
h('span', 'hello')
),
ctx
)
expect(html).toBe(
'<!--teleport start--><span>hello</span><!--teleport end-->'
)
expect(ctx.teleports!['#target']).toBe(`<!---->`)
})
test('multiple teleports with same target', async () => {
const ctx: SSRContext = {}
const html = await renderToString(
h('div', [
h(
Teleport,
{
to: `#target`
},
h('span', 'hello')
),
h(Teleport, { to: `#target` }, 'world')
]),
ctx
)
expect(html).toBe(
'<div><!--teleport start--><!--teleport end--><!--teleport start--><!--teleport end--></div>'
)
expect(ctx.teleports!['#target']).toBe(
'<span>hello</span><!---->world<!---->'
)
})
})
| packages/server-renderer/__tests__/ssrTeleport.spec.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017627152556087822,
0.0001735826226649806,
0.00017071219917852432,
0.0001733497774694115,
0.0000015210470110105234
] |
{
"id": 2,
"code_window": [
"\n",
" const finishEnter: Hook = (el, done) => {\n",
" removeTransitionClass(el, enterToClass)\n",
" removeTransitionClass(el, enterActiveClass)\n",
" done && done()\n",
" // reset enter class\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishEnter = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 112
} | export { baseCompile } from './compile'
// Also expose lower level APIs & types
export {
CompilerOptions,
ParserOptions,
TransformOptions,
CodegenOptions,
HoistTransform
} from './options'
export { baseParse, TextModes } from './parse'
export {
transform,
TransformContext,
createTransformContext,
traverseNode,
createStructuralDirectiveTransform,
NodeTransform,
StructuralDirectiveTransform,
DirectiveTransform
} from './transform'
export { generate, CodegenContext, CodegenResult } from './codegen'
export {
ErrorCodes,
CoreCompilerError,
CompilerError,
createCompilerError
} from './errors'
export * from './ast'
export * from './utils'
export * from './runtimeHelpers'
export { getBaseTransformPreset, TransformPreset } from './compile'
export { transformModel } from './transforms/vModel'
export { transformOn } from './transforms/vOn'
export { transformBind } from './transforms/vBind'
export { noopDirectiveTransform } from './transforms/noopDirectiveTransform'
export { processIf } from './transforms/vIf'
export { processFor, createForLoopParams } from './transforms/vFor'
export {
transformExpression,
processExpression
} from './transforms/transformExpression'
export {
buildSlots,
SlotFnBuilder,
trackVForSlotScopes,
trackSlotScopes
} from './transforms/vSlot'
export {
transformElement,
resolveComponentType,
buildProps
} from './transforms/transformElement'
export { processSlotOutlet } from './transforms/transformSlotOutlet'
export { generateCodeFrame } from '@vue/shared'
| packages/compiler-core/src/index.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.0001755407574819401,
0.0001736685080686584,
0.0001716001715976745,
0.0001737007696647197,
0.000001513383494966547
] |
{
"id": 3,
"code_window": [
" ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass\n",
" }\n",
" }\n",
"\n",
" const finishLeave: Hook = (el, done) => {\n",
" removeTransitionClass(el, leaveToClass)\n",
" removeTransitionClass(el, leaveActiveClass)\n",
" done && done()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishLeave = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 122
} | import {
BaseTransition,
BaseTransitionProps,
h,
warn,
FunctionalComponent,
getCurrentInstance,
callWithAsyncErrorHandling
} from '@vue/runtime-core'
import { isObject, toNumber, extend } from '@vue/shared'
import { ErrorCodes } from 'packages/runtime-core/src/errorHandling'
const TRANSITION = 'transition'
const ANIMATION = 'animation'
export interface TransitionProps extends BaseTransitionProps<Element> {
name?: string
type?: typeof TRANSITION | typeof ANIMATION
css?: boolean
duration?: number | { enter: number; leave: number }
// custom transition classes
enterFromClass?: string
enterActiveClass?: string
enterToClass?: string
appearFromClass?: string
appearActiveClass?: string
appearToClass?: string
leaveFromClass?: string
leaveActiveClass?: string
leaveToClass?: string
}
// DOM Transition is a higher-order-component based on the platform-agnostic
// base Transition component, with DOM-specific logic.
export const Transition: FunctionalComponent<TransitionProps> = (
props,
{ slots }
) => h(BaseTransition, resolveTransitionProps(props), slots)
Transition.inheritRef = true
const DOMTransitionPropsValidators = {
name: String,
type: String,
css: {
type: Boolean,
default: true
},
duration: [String, Number, Object],
enterFromClass: String,
enterActiveClass: String,
enterToClass: String,
appearFromClass: String,
appearActiveClass: String,
appearToClass: String,
leaveFromClass: String,
leaveActiveClass: String,
leaveToClass: String
}
export const TransitionPropsValidators = (Transition.props = extend(
{},
(BaseTransition as any).props,
DOMTransitionPropsValidators
))
export function resolveTransitionProps(
rawProps: TransitionProps
): BaseTransitionProps<Element> {
let {
name = 'v',
type,
css = true,
duration,
enterFromClass = `${name}-enter-from`,
enterActiveClass = `${name}-enter-active`,
enterToClass = `${name}-enter-to`,
appearFromClass = enterFromClass,
appearActiveClass = enterActiveClass,
appearToClass = enterToClass,
leaveFromClass = `${name}-leave-from`,
leaveActiveClass = `${name}-leave-active`,
leaveToClass = `${name}-leave-to`
} = rawProps
const baseProps: BaseTransitionProps<Element> = {}
for (const key in rawProps) {
if (!(key in DOMTransitionPropsValidators)) {
;(baseProps as any)[key] = (rawProps as any)[key]
}
}
if (!css) {
return baseProps
}
const originEnterClass = [enterFromClass, enterActiveClass, enterToClass]
const instance = getCurrentInstance()!
const durations = normalizeDuration(duration)
const enterDuration = durations && durations[0]
const leaveDuration = durations && durations[1]
const { appear, onBeforeEnter, onEnter, onLeave } = baseProps
// is appearing
if (appear && !instance.isMounted) {
enterFromClass = appearFromClass
enterActiveClass = appearActiveClass
enterToClass = appearToClass
}
type Hook = (el: Element, done?: () => void) => void
const finishEnter: Hook = (el, done) => {
removeTransitionClass(el, enterToClass)
removeTransitionClass(el, enterActiveClass)
done && done()
// reset enter class
if (appear) {
;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass
}
}
const finishLeave: Hook = (el, done) => {
removeTransitionClass(el, leaveToClass)
removeTransitionClass(el, leaveActiveClass)
done && done()
}
// only needed for user hooks called in nextFrame
// sync errors are already handled by BaseTransition
function callHookWithErrorHandling(hook: Hook, args: any[]) {
callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)
}
return extend(baseProps, {
onBeforeEnter(el) {
onBeforeEnter && onBeforeEnter(el)
addTransitionClass(el, enterActiveClass)
addTransitionClass(el, enterFromClass)
},
onEnter(el, done) {
nextFrame(() => {
const resolve = () => finishEnter(el, done)
onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])
removeTransitionClass(el, enterFromClass)
addTransitionClass(el, enterToClass)
if (!(onEnter && onEnter.length > 1)) {
if (enterDuration) {
setTimeout(resolve, enterDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onLeave(el, done) {
addTransitionClass(el, leaveActiveClass)
addTransitionClass(el, leaveFromClass)
nextFrame(() => {
const resolve = () => finishLeave(el, done)
onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])
removeTransitionClass(el, leaveFromClass)
addTransitionClass(el, leaveToClass)
if (!(onLeave && onLeave.length > 1)) {
if (leaveDuration) {
setTimeout(resolve, leaveDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onEnterCancelled: finishEnter,
onLeaveCancelled: finishLeave
} as BaseTransitionProps<Element>)
}
function normalizeDuration(
duration: TransitionProps['duration']
): [number, number] | null {
if (duration == null) {
return null
} else if (isObject(duration)) {
return [NumberOf(duration.enter), NumberOf(duration.leave)]
} else {
const n = NumberOf(duration)
return [n, n]
}
}
function NumberOf(val: unknown): number {
const res = toNumber(val)
if (__DEV__) validateDuration(res)
return res
}
function validateDuration(val: unknown) {
if (typeof val !== 'number') {
warn(
`<transition> explicit duration is not a valid number - ` +
`got ${JSON.stringify(val)}.`
)
} else if (isNaN(val)) {
warn(
`<transition> explicit duration is NaN - ` +
'the duration expression might be incorrect.'
)
}
}
export interface ElementWithTransition extends HTMLElement {
// _vtc = Vue Transition Classes.
// Store the temporarily-added transition classes on the element
// so that we can avoid overwriting them if the element's class is patched
// during the transition.
_vtc?: Set<string>
}
export function addTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.add(c))
;(
(el as ElementWithTransition)._vtc ||
((el as ElementWithTransition)._vtc = new Set())
).add(cls)
}
export function removeTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.remove(c))
const { _vtc } = el as ElementWithTransition
if (_vtc) {
_vtc.delete(cls)
if (!_vtc!.size) {
;(el as ElementWithTransition)._vtc = undefined
}
}
}
function nextFrame(cb: () => void) {
requestAnimationFrame(() => {
requestAnimationFrame(cb)
})
}
function whenTransitionEnds(
el: Element,
expectedType: TransitionProps['type'] | undefined,
cb: () => void
) {
const { type, timeout, propCount } = getTransitionInfo(el, expectedType)
if (!type) {
return cb()
}
const endEvent = type + 'end'
let ended = 0
const end = () => {
el.removeEventListener(endEvent, onEnd)
cb()
}
const onEnd = (e: Event) => {
if (e.target === el) {
if (++ended >= propCount) {
end()
}
}
}
setTimeout(() => {
if (ended < propCount) {
end()
}
}, timeout + 1)
el.addEventListener(endEvent, onEnd)
}
interface CSSTransitionInfo {
type: typeof TRANSITION | typeof ANIMATION | null
propCount: number
timeout: number
hasTransform: boolean
}
export function getTransitionInfo(
el: Element,
expectedType?: TransitionProps['type']
): CSSTransitionInfo {
const styles: any = window.getComputedStyle(el)
// JSDOM may return undefined for transition properties
const getStyleProperties = (key: string) => (styles[key] || '').split(', ')
const transitionDelays = getStyleProperties(TRANSITION + 'Delay')
const transitionDurations = getStyleProperties(TRANSITION + 'Duration')
const transitionTimeout = getTimeout(transitionDelays, transitionDurations)
const animationDelays = getStyleProperties(ANIMATION + 'Delay')
const animationDurations = getStyleProperties(ANIMATION + 'Duration')
const animationTimeout = getTimeout(animationDelays, animationDurations)
let type: CSSTransitionInfo['type'] = null
let timeout = 0
let propCount = 0
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION
timeout = transitionTimeout
propCount = transitionDurations.length
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION
timeout = animationTimeout
propCount = animationDurations.length
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout)
type =
timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0
}
const hasTransform =
type === TRANSITION &&
/\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property'])
return {
type,
timeout,
propCount,
hasTransform
}
}
function getTimeout(delays: string[], durations: string[]): number {
while (delays.length < durations.length) {
delays = delays.concat(delays)
}
return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])))
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
// numbers in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down
// (i.e. acting as a floor function) causing unexpected behaviors
function toMs(s: string): number {
return Number(s.slice(0, -1).replace(',', '.')) * 1000
}
| packages/runtime-dom/src/components/Transition.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.9990035891532898,
0.21430392563343048,
0.00016706340829841793,
0.0019554835744202137,
0.3951282501220703
] |
{
"id": 3,
"code_window": [
" ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass\n",
" }\n",
" }\n",
"\n",
" const finishLeave: Hook = (el, done) => {\n",
" removeTransitionClass(el, leaveToClass)\n",
" removeTransitionClass(el, leaveActiveClass)\n",
" done && done()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishLeave = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 122
} | import path from 'path'
import {
createCompoundExpression,
createSimpleExpression,
NodeTransform,
NodeTypes,
SimpleExpressionNode
} from '@vue/compiler-core'
import {
isRelativeUrl,
parseUrl,
isExternalUrl,
isDataUrl
} from './templateUtils'
import {
AssetURLOptions,
defaultAssetUrlOptions
} from './templateTransformAssetUrl'
const srcsetTags = ['img', 'source']
interface ImageCandidate {
url: string
descriptor: string
}
// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
export const createSrcsetTransformWithOptions = (
options: Required<AssetURLOptions>
): NodeTransform => {
return (node, context) =>
(transformSrcset as Function)(node, context, options)
}
export const transformSrcset: NodeTransform = (
node,
context,
options: Required<AssetURLOptions> = defaultAssetUrlOptions
) => {
if (node.type === NodeTypes.ELEMENT) {
if (srcsetTags.includes(node.tag) && node.props.length) {
node.props.forEach((attr, index) => {
if (attr.name === 'srcset' && attr.type === NodeTypes.ATTRIBUTE) {
if (!attr.value) return
const value = attr.value.content
const imageCandidates: ImageCandidate[] = value.split(',').map(s => {
// The attribute value arrives here with all whitespace, except
// normal spaces, represented by escape sequences
const [url, descriptor] = s
.replace(escapedSpaceCharacters, ' ')
.trim()
.split(' ', 2)
return { url, descriptor }
})
// for data url need recheck url
for (let i = 0; i < imageCandidates.length; i++) {
if (imageCandidates[i].url.trim().startsWith('data:')) {
imageCandidates[i + 1].url =
imageCandidates[i].url + ',' + imageCandidates[i + 1].url
imageCandidates.splice(i, 1)
}
}
// When srcset does not contain any relative URLs, skip transforming
if (
!options.includeAbsolute &&
!imageCandidates.some(({ url }) => isRelativeUrl(url))
) {
return
}
if (options.base) {
const base = options.base
const set: string[] = []
imageCandidates.forEach(({ url, descriptor }) => {
descriptor = descriptor ? ` ${descriptor}` : ``
if (isRelativeUrl(url)) {
set.push((path.posix || path).join(base, url) + descriptor)
} else {
set.push(url + descriptor)
}
})
attr.value.content = set.join(', ')
return
}
const compoundExpression = createCompoundExpression([], attr.loc)
imageCandidates.forEach(({ url, descriptor }, index) => {
if (
!isExternalUrl(url) &&
!isDataUrl(url) &&
(options.includeAbsolute || isRelativeUrl(url))
) {
const { path } = parseUrl(url)
let exp: SimpleExpressionNode
if (path) {
const importsArray = Array.from(context.imports)
const existingImportsIndex = importsArray.findIndex(
i => i.path === path
)
if (existingImportsIndex > -1) {
exp = createSimpleExpression(
`_imports_${existingImportsIndex}`,
false,
attr.loc,
true
)
} else {
exp = createSimpleExpression(
`_imports_${importsArray.length}`,
false,
attr.loc,
true
)
context.imports.add({ exp, path })
}
compoundExpression.children.push(exp)
}
} else {
const exp = createSimpleExpression(
`"${url}"`,
false,
attr.loc,
true
)
compoundExpression.children.push(exp)
}
const isNotLast = imageCandidates.length - 1 > index
if (descriptor && isNotLast) {
compoundExpression.children.push(` + '${descriptor}, ' + `)
} else if (descriptor) {
compoundExpression.children.push(` + '${descriptor}'`)
} else if (isNotLast) {
compoundExpression.children.push(` + ', ' + `)
}
})
const hoisted = context.hoist(compoundExpression)
hoisted.isRuntimeConstant = true
node.props[index] = {
type: NodeTypes.DIRECTIVE,
name: 'bind',
arg: createSimpleExpression('srcset', true, attr.loc),
exp: hoisted,
modifiers: [],
loc: attr.loc
}
}
})
}
}
}
| packages/compiler-sfc/src/templateTransformSrcset.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017567504255566746,
0.00017091720656026155,
0.00016680714907124639,
0.00017062530969269574,
0.000002439454874547664
] |
{
"id": 3,
"code_window": [
" ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass\n",
" }\n",
" }\n",
"\n",
" const finishLeave: Hook = (el, done) => {\n",
" removeTransitionClass(el, leaveToClass)\n",
" removeTransitionClass(el, leaveActiveClass)\n",
" done && done()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishLeave = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 122
} | import {
h,
ref,
Suspense,
ComponentOptions,
render,
nodeOps,
serializeInner,
nextTick,
onMounted,
watch,
watchEffect,
onUnmounted,
onErrorCaptured,
Component
} from '@vue/runtime-test'
describe('Suspense', () => {
const deps: Promise<any>[] = []
beforeEach(() => {
deps.length = 0
})
// a simple async factory for testing purposes only.
function defineAsyncComponent<T extends ComponentOptions>(
comp: T,
delay: number = 0
) {
return {
setup(props: any, { slots }: any) {
const p = new Promise(resolve => {
setTimeout(() => {
resolve(() => h<Component>(comp, props, slots))
}, delay)
})
// in Node 12, due to timer/nextTick mechanism change, we have to wait
// an extra tick to avoid race conditions
deps.push(p.then(() => Promise.resolve()))
return p
}
}
}
test('fallback content', async () => {
const Async = defineAsyncComponent({
render() {
return h('div', 'async')
}
})
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
})
test('nested async deps', async () => {
const calls: string[] = []
const AsyncOuter = defineAsyncComponent({
setup() {
onMounted(() => {
calls.push('outer mounted')
})
return () => h(AsyncInner)
}
})
const AsyncInner = defineAsyncComponent(
{
setup() {
onMounted(() => {
calls.push('inner mounted')
})
return () => h('div', 'inner')
}
},
10
)
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(AsyncOuter),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([])
await Promise.all(deps)
await nextTick()
expect(calls).toEqual([`outer mounted`, `inner mounted`])
expect(serializeInner(root)).toBe(`<div>inner</div>`)
})
test('onResolve', async () => {
const Async = defineAsyncComponent({
render() {
return h('div', 'async')
}
})
const onResolve = jest.fn()
const Comp = {
setup() {
return () =>
h(
Suspense,
{
onResolve
},
{
default: h(Async),
fallback: h('div', 'fallback')
}
)
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(onResolve).not.toHaveBeenCalled()
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(onResolve).toHaveBeenCalled()
})
test('buffer mounted/updated hooks & watch callbacks', async () => {
const deps: Promise<any>[] = []
const calls: string[] = []
const toggle = ref(true)
const Async = {
async setup() {
const p = new Promise(r => setTimeout(r, 1))
// extra tick needed for Node 12+
deps.push(p.then(() => Promise.resolve()))
watchEffect(() => {
calls.push('immediate effect')
})
const count = ref(0)
watch(count, v => {
calls.push('watch callback')
})
count.value++ // trigger the watcher now
onMounted(() => {
calls.push('mounted')
})
onUnmounted(() => {
calls.push('unmounted')
})
await p
return () => h('div', 'async')
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Async) : null,
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([`immediate effect`])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(calls).toEqual([`immediate effect`, `watch callback`, `mounted`])
// effects inside an already resolved suspense should happen at normal timing
toggle.value = false
await nextTick()
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
expect(calls).toEqual([
`immediate effect`,
`watch callback`,
`mounted`,
'unmounted'
])
})
// #1059
test('mounted/updated hooks & fallback component', async () => {
const deps: Promise<any>[] = []
const calls: string[] = []
const toggle = ref(true)
const Async = {
async setup() {
const p = new Promise(r => setTimeout(r, 1))
// extra tick needed for Node 12+
deps.push(p.then(() => Promise.resolve()))
await p
return () => h('div', 'async')
}
}
const Fallback = {
setup() {
onMounted(() => {
calls.push('mounted')
})
onUnmounted(() => {
calls.push('unmounted')
})
return () => h('div', 'fallback')
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Async) : null,
fallback: h(Fallback)
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual([`mounted`])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(calls).toEqual([`mounted`, `unmounted`])
})
test('content update before suspense resolve', async () => {
const Async = defineAsyncComponent({
props: { msg: String },
setup(props: any) {
return () => h('div', props.msg)
}
})
const msg = ref('foo')
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: h(Async, { msg: msg.value }),
fallback: h('div', `fallback ${msg.value}`)
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback foo</div>`)
// value changed before resolve
msg.value = 'bar'
await nextTick()
// fallback content should be updated
expect(serializeInner(root)).toBe(`<div>fallback bar</div>`)
await Promise.all(deps)
await nextTick()
// async component should receive updated props/slots when resolved
expect(serializeInner(root)).toBe(`<div>bar</div>`)
})
// mount/unmount hooks should not even fire
test('unmount before suspense resolve', async () => {
const deps: Promise<any>[] = []
const calls: string[] = []
const toggle = ref(true)
const Async = {
async setup() {
const p = new Promise(r => setTimeout(r, 1))
deps.push(p)
watchEffect(() => {
calls.push('immediate effect')
})
const count = ref(0)
watch(count, () => {
calls.push('watch callback')
})
count.value++ // trigger the watcher now
onMounted(() => {
calls.push('mounted')
})
onUnmounted(() => {
calls.push('unmounted')
})
await p
return () => h('div', 'async')
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: toggle.value ? h(Async) : null,
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
expect(calls).toEqual(['immediate effect'])
// remove the async dep before it's resolved
toggle.value = false
await nextTick()
// should cause the suspense to resolve immediately
expect(serializeInner(root)).toBe(`<!---->`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
// should discard effects (except for immediate ones)
expect(calls).toEqual(['immediate effect', 'watch callback', 'unmounted'])
})
test('unmount suspense after resolve', async () => {
const toggle = ref(true)
const unmounted = jest.fn()
const Async = defineAsyncComponent({
setup() {
onUnmounted(unmounted)
return () => h('div', 'async')
}
})
const Comp = {
setup() {
return () =>
toggle.value
? h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
: null
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>async</div>`)
expect(unmounted).not.toHaveBeenCalled()
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
expect(unmounted).toHaveBeenCalled()
})
test('unmount suspense before resolve', async () => {
const toggle = ref(true)
const mounted = jest.fn()
const unmounted = jest.fn()
const Async = defineAsyncComponent({
setup() {
onMounted(mounted)
onUnmounted(unmounted)
return () => h('div', 'async')
}
})
const Comp = {
setup() {
return () =>
toggle.value
? h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
: null
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
toggle.value = false
await nextTick()
expect(serializeInner(root)).toBe(`<!---->`)
expect(mounted).not.toHaveBeenCalled()
expect(unmounted).not.toHaveBeenCalled()
await Promise.all(deps)
await nextTick()
// should not resolve and cause unmount
expect(mounted).not.toHaveBeenCalled()
expect(unmounted).not.toHaveBeenCalled()
})
test('nested suspense (parent resolves first)', async () => {
const calls: string[] = []
const AsyncOuter = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('outer mounted')
})
return () => h('div', 'async outer')
}
},
1
)
const AsyncInner = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('inner mounted')
})
return () => h('div', 'async inner')
}
},
10
)
const Inner = {
setup() {
return () =>
h(Suspense, null, {
default: h(AsyncInner),
fallback: h('div', 'fallback inner')
})
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: [h(AsyncOuter), h(Inner)],
fallback: h('div', 'fallback outer')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback outer</div>`)
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(
`<div>async outer</div><div>fallback inner</div>`
)
expect(calls).toEqual([`outer mounted`])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(
`<div>async outer</div><div>async inner</div>`
)
expect(calls).toEqual([`outer mounted`, `inner mounted`])
})
test('nested suspense (child resolves first)', async () => {
const calls: string[] = []
const AsyncOuter = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('outer mounted')
})
return () => h('div', 'async outer')
}
},
10
)
const AsyncInner = defineAsyncComponent(
{
setup: () => {
onMounted(() => {
calls.push('inner mounted')
})
return () => h('div', 'async inner')
}
},
1
)
const Inner = {
setup() {
return () =>
h(Suspense, null, {
default: h(AsyncInner),
fallback: h('div', 'fallback inner')
})
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: [h(AsyncOuter), h(Inner)],
fallback: h('div', 'fallback outer')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback outer</div>`)
await deps[1]
await nextTick()
expect(serializeInner(root)).toBe(`<div>fallback outer</div>`)
expect(calls).toEqual([])
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(
`<div>async outer</div><div>async inner</div>`
)
expect(calls).toEqual([`inner mounted`, `outer mounted`])
})
test('error handling', async () => {
const Async = {
async setup() {
throw new Error('oops')
}
}
const Comp = {
setup() {
const errorMessage = ref<string | null>(null)
onErrorCaptured(err => {
errorMessage.value =
err instanceof Error
? err.message
: `A non-Error value thrown: ${err}`
return true
})
return () =>
errorMessage.value
? h('div', errorMessage.value)
: h(Suspense, null, {
default: h(Async),
fallback: h('div', 'fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>fallback</div>`)
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(`<div>oops</div>`)
})
it('combined usage (nested async + nested suspense + multiple deps)', async () => {
const msg = ref('nested msg')
const calls: number[] = []
const AsyncChildWithSuspense = defineAsyncComponent({
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(0)
})
return () =>
h(Suspense, null, {
default: h(AsyncInsideNestedSuspense, { msg: props.msg }),
fallback: h('div', 'nested fallback')
})
}
})
const AsyncInsideNestedSuspense = defineAsyncComponent(
{
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(2)
})
return () => h('div', props.msg)
}
},
20
)
const AsyncChildParent = defineAsyncComponent({
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(1)
})
return () => h(NestedAsyncChild, { msg: props.msg })
}
})
const NestedAsyncChild = defineAsyncComponent(
{
props: { msg: String },
setup(props: any) {
onMounted(() => {
calls.push(3)
})
return () => h('div', props.msg)
}
},
10
)
const MiddleComponent = {
setup() {
return () =>
h(AsyncChildWithSuspense, {
msg: msg.value
})
}
}
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: [
h(MiddleComponent),
h(AsyncChildParent, {
msg: 'root async'
})
],
fallback: h('div', 'root fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>root fallback</div>`)
expect(calls).toEqual([])
/**
* <Root>
* <Suspense>
* <MiddleComponent>
* <AsyncChildWithSuspense> (0: resolves on macrotask)
* <Suspense>
* <AsyncInsideNestedSuspense> (2: resolves on macrotask + 20ms)
* <AsyncChildParent> (1: resolves on macrotask)
* <NestedAsyncChild> (3: resolves on macrotask + 10ms)
*/
// both top level async deps resolved, but there is another nested dep
// so should still be in fallback state
await Promise.all([deps[0], deps[1]])
await nextTick()
expect(serializeInner(root)).toBe(`<div>root fallback</div>`)
expect(calls).toEqual([])
// root suspense all deps resolved. should show root content now
// with nested suspense showing fallback content
await deps[3]
await nextTick()
expect(serializeInner(root)).toBe(
`<div>nested fallback</div><div>root async</div>`
)
expect(calls).toEqual([0, 1, 3])
// change state for the nested component before it resolves
msg.value = 'nested changed'
// all deps resolved, nested suspense should resolve now
await Promise.all(deps)
await nextTick()
expect(serializeInner(root)).toBe(
`<div>nested changed</div><div>root async</div>`
)
expect(calls).toEqual([0, 1, 3, 2])
// should update just fine after resolve
msg.value = 'nested changed again'
await nextTick()
expect(serializeInner(root)).toBe(
`<div>nested changed again</div><div>root async</div>`
)
})
test('new async dep after resolve should cause suspense to restart', async () => {
const toggle = ref(false)
const ChildA = defineAsyncComponent({
setup() {
return () => h('div', 'Child A')
}
})
const ChildB = defineAsyncComponent({
setup() {
return () => h('div', 'Child B')
}
})
const Comp = {
setup() {
return () =>
h(Suspense, null, {
default: [h(ChildA), toggle.value ? h(ChildB) : null],
fallback: h('div', 'root fallback')
})
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(serializeInner(root)).toBe(`<div>root fallback</div>`)
await deps[0]
await nextTick()
expect(serializeInner(root)).toBe(`<div>Child A</div><!---->`)
toggle.value = true
await nextTick()
expect(serializeInner(root)).toBe(`<div>root fallback</div>`)
await deps[1]
await nextTick()
expect(serializeInner(root)).toBe(`<div>Child A</div><div>Child B</div>`)
})
test.todo('teleport inside suspense')
})
| packages/runtime-core/__tests__/components/Suspense.spec.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.0001776158605935052,
0.00017294664576184005,
0.00016831026005093008,
0.00017278791347052902,
0.0000020853317437286023
] |
{
"id": 3,
"code_window": [
" ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass\n",
" }\n",
" }\n",
"\n",
" const finishLeave: Hook = (el, done) => {\n",
" removeTransitionClass(el, leaveToClass)\n",
" removeTransitionClass(el, leaveActiveClass)\n",
" done && done()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const finishLeave = (el: Element, done?: () => void) => {\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 122
} | import { DirectiveTransform } from '../transform'
import { createObjectProperty, createSimpleExpression, NodeTypes } from '../ast'
import { createCompilerError, ErrorCodes } from '../errors'
import { camelize } from '@vue/shared'
import { CAMELIZE } from '../runtimeHelpers'
// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
// codegen for the entire props object. This transform here is only for v-bind
// *with* args.
export const transformBind: DirectiveTransform = (dir, node, context) => {
const { exp, modifiers, loc } = dir
const arg = dir.arg!
if (!exp || (exp.type === NodeTypes.SIMPLE_EXPRESSION && !exp.content)) {
context.onError(createCompilerError(ErrorCodes.X_V_BIND_NO_EXPRESSION, loc))
}
// .prop is no longer necessary due to new patch behavior
// .sync is replaced by v-model:arg
if (modifiers.includes('camel')) {
if (arg.type === NodeTypes.SIMPLE_EXPRESSION) {
if (arg.isStatic) {
arg.content = camelize(arg.content)
} else {
arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`
}
} else {
arg.children.unshift(`${context.helperString(CAMELIZE)}(`)
arg.children.push(`)`)
}
}
return {
props: [
createObjectProperty(arg!, exp || createSimpleExpression('', true, loc))
]
}
}
| packages/compiler-core/src/transforms/vBind.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017724315694067627,
0.00017348345136269927,
0.00017062578990589827,
0.00017303245840594172,
0.0000025795259261940373
] |
{
"id": 4,
"code_window": [
"\n",
" // only needed for user hooks called in nextFrame\n",
" // sync errors are already handled by BaseTransition\n",
" function callHookWithErrorHandling(hook: Hook, args: any[]) {\n",
" callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)\n",
" }\n",
"\n",
" return extend(baseProps, {\n",
" onBeforeEnter(el) {\n",
" onBeforeEnter && onBeforeEnter(el)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const callHook = (hook: Hook | undefined, args: any[]) => {\n",
" hook &&\n",
" callWithAsyncErrorHandling(\n",
" hook,\n",
" instance,\n",
" ErrorCodes.TRANSITION_HOOK,\n",
" args\n",
" )\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 130
} | import { E2E_TIMEOUT, setupPuppeteer } from './e2eUtils'
import path from 'path'
import { mockWarn } from '@vue/shared'
import { h, createApp, Transition } from 'vue'
describe('e2e: Transition', () => {
mockWarn()
const { page, html, classList, isVisible } = setupPuppeteer()
const baseUrl = `file://${path.resolve(__dirname, './transition.html')}`
const duration = 50
const buffer = 5
const classWhenTransitionStart = () =>
page().evaluate(() => {
(document.querySelector('#toggleBtn') as any)!.click()
return Promise.resolve().then(() => {
return document.querySelector('#container div')!.className.split(/\s+/g)
})
})
const transitionFinish = (time = duration) =>
new Promise(r => {
setTimeout(r, time + buffer)
})
const nextFrame = () => {
return page().evaluate(() => {
return new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(resolve)
})
})
})
}
beforeEach(async () => {
await page().goto(baseUrl)
await page().waitFor('#app')
})
describe('transition with v-if', () => {
test(
'basic transition',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition>
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'v-leave-active',
'v-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'v-leave-active',
'v-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'v-enter-active',
'v-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'v-enter-active',
'v-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'named transition',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'custom transition classes',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition enter-from-class="hello-from"
enter-active-class="hello-active"
enter-to-class="hello-to"
leave-from-class="bye-from"
leave-active-class="bye-active"
leave-to-class="bye-to">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'bye-active',
'bye-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'bye-active',
'bye-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'hello-active',
'hello-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'hello-active',
'hello-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition with dynamic name',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition :name="name">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
<button id="changeNameBtn" @click="changeName">button</button>
`,
setup: () => {
const name = ref('test')
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
const changeName = () => (name.value = 'changed')
return { toggle, click, name, changeName }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
await page().evaluate(() => {
;(document.querySelector('#changeNameBtn') as any).click()
})
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'changed-enter-active',
'changed-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'changed-enter-active',
'changed-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition events without appear',
async () => {
const beforeLeaveSpy = jest.fn()
const onLeaveSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const onEnterSpy = jest.fn()
const afterEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().evaluate(() => {
const {
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
// todo test event with arguments. Note: not get dom, get object. '{}'
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(beforeLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
expect(afterLeaveSpy).toBeCalled()
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).not.toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
test('onEnterCancelled', async () => {
const enterCancelledSpy = jest.fn()
await page().exposeFunction('enterCancelledSpy', enterCancelledSpy)
await page().evaluate(() => {
const { enterCancelledSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@enter-cancelled="enterCancelledSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(false)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
enterCancelledSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
// cancel (leave)
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
// fixme
expect(enterCancelledSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
})
test(
'transition on appear',
async () => {
await page().evaluate(async () => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
// appear
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition events with appear',
async () => {
const onLeaveSpy = jest.fn()
const onEnterSpy = jest.fn()
const onAppearSpy = jest.fn()
const beforeLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const beforeAppearSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const afterEnterSpy = jest.fn()
const afterAppearSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('onAppearSpy', onAppearSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('beforeAppearSpy', beforeAppearSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().exposeFunction('afterAppearSpy', afterAppearSpy)
const appearClass = await page().evaluate(async () => {
const {
beforeAppearSpy,
onAppearSpy,
afterAppearSpy,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy"
@before-appear="beforeAppearSpy"
@appear="onAppearSpy"
@after-appear="afterAppearSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeAppearSpy,
onAppearSpy,
afterAppearSpy,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
return Promise.resolve().then(() => {
return document.querySelector('.test')!.className.split(/\s+/g)
})
})
// appear fixme spy called
expect(appearClass).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
expect(beforeAppearSpy).not.toBeCalled()
expect(onAppearSpy).not.toBeCalled()
expect(afterAppearSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
expect(onAppearSpy).not.toBeCalled()
expect(afterAppearSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterAppearSpy).not.toBeCalled()
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(onLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
expect(afterLeaveSpy).toBeCalled()
// enter fixme spy called
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
// fixme
test(
'css: false',
async () => {
const onLeaveSpy = jest.fn()
const onEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().evaluate(() => {
const { onLeaveSpy, onEnterSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
:css="false"
name="test"
@enter="onEnterSpy"
@leave="onLeaveSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click"></button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click, onLeaveSpy, onEnterSpy }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
await classWhenTransitionStart()
expect(onLeaveSpy).toBeCalled()
expect(await html('#container')).toBe(
'<div class="test">content</div><!--v-if-->'
)
// enter
await classWhenTransitionStart()
expect(onEnterSpy).toBeCalled()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'no transition detected',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="noop">
<div v-if="toggle">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'noop-leave-active',
'noop-leave-from'
])
await nextFrame()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'noop-enter-active',
'noop-enter-from'
])
await nextFrame()
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'animations',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test-anim">
<div v-if="toggle">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-leave-active',
'test-anim-leave-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-leave-active',
'test-anim-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-enter-active',
'test-anim-enter-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-enter-active',
'test-anim-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'explicit transition type',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container"><transition name="test-anim-long" type="animation"><div v-if="toggle">content</div></transition></div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-to'
])
await new Promise(r => {
setTimeout(r, duration + 5)
})
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-to'
])
await new Promise(r => {
setTimeout(r, duration + 5)
})
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'transition on SVG elements',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<svg id="container">
<transition name="test">
<circle v-if="toggle" cx="0" cy="0" r="10" class="test"></circle>
</transition>
</svg>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe(
'<circle cx="0" cy="0" r="10" class="test"></circle>'
)
const svgTransitionStart = () =>
page().evaluate(() => {
document.querySelector('button')!.click()
return Promise.resolve().then(() => {
return document
.querySelector('.test')!
.getAttribute('class')!
.split(/\s+/g)
})
})
// leave
expect(await svgTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await svgTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<circle cx="0" cy="0" r="10" class="test"></circle>'
)
},
E2E_TIMEOUT
)
test(
'custom transition higher-order component',
async () => {
await page().evaluate(() => {
const { createApp, ref, h, Transition } = (window as any).Vue
createApp({
template: `
<div id="container"><my-transition><div v-if="toggle" class="test">content</div></my-transition></div>
<button id="toggleBtn" @click="click">button</button>
`,
components: {
'my-transition': (props: any, { slots }: any) => {
return h(Transition, { name: 'test' }, slots)
}
},
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition on child components with empty root node',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<component class="test" :is="view"></component>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
<button id="changeViewBtn" @click="change">button</button>
`,
components: {
one: {
template: '<div v-if="false">one</div>'
},
two: {
template: '<div>two</div>'
}
},
setup: () => {
const toggle = ref(true)
const view = ref('one')
const click = () => (toggle.value = !toggle.value)
const change = () =>
(view.value = view.value === 'one' ? 'two' : 'one')
return { toggle, click, change, view }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<!--v-if-->')
// change view -> 'two'
await page().evaluate(() => {
(document.querySelector('#changeViewBtn') as any)!.click()
})
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">two</div>')
// change view -> 'one'
await page().evaluate(() => {
(document.querySelector('#changeViewBtn') as any)!.click()
})
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
},
E2E_TIMEOUT
)
})
describe('transition with v-show', () => {
test(
'named transition with v-show',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(await isVisible('.test')).toBe(true)
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
test(
'transition events with v-show',
async () => {
const beforeLeaveSpy = jest.fn()
const onLeaveSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const onEnterSpy = jest.fn()
const afterEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().evaluate(() => {
const {
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(beforeLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
expect(afterLeaveSpy).toBeCalled()
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).not.toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
test(
'onLeaveCancelled (v-show only)',
async () => {
const onLeaveCancelledSpy = jest.fn()
await page().exposeFunction('onLeaveCancelledSpy', onLeaveCancelledSpy)
await page().evaluate(() => {
const { onLeaveCancelledSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-show="toggle" class="test" @leave-cancelled="onLeaveCancelledSpy">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click, onLeaveCancelledSpy }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(await isVisible('.test')).toBe(true)
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
// cancel (enter)
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
// fixme
expect(onLeaveCancelledSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
test(
'transition on appear with v-show',
async () => {
const appearClass = await page().evaluate(async () => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
return Promise.resolve().then(() => {
return document.querySelector('.test')!.className.split(/\s+/g)
})
})
// appear
expect(appearClass).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
})
test(
'warn when used on multiple elements',
async () => {
createApp({
render() {
return h(Transition, null, {
default: () => [h('div'), h('div')]
})
}
}).mount(document.createElement('div'))
expect(
'<transition> can only be used on a single element or component'
).toHaveBeenWarned()
},
E2E_TIMEOUT
)
describe('explicit durations', () => {
test(
'single value',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" duration="${duration * 2}">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'enter with explicit durations',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{ enter: ${duration * 2} }">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'leave with explicit durations',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{ leave: ${duration * 2} }">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'separate enter and leave',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{
enter: ${duration * 4},
leave: ${duration * 2}
}">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(200)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
// fixme
test.todo('warn invalid durations')
})
})
| packages/vue/__tests__/Transition.spec.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.007582463789731264,
0.0004214774817228317,
0.00016643361595924944,
0.00019038605387322605,
0.0009447239572182298
] |
{
"id": 4,
"code_window": [
"\n",
" // only needed for user hooks called in nextFrame\n",
" // sync errors are already handled by BaseTransition\n",
" function callHookWithErrorHandling(hook: Hook, args: any[]) {\n",
" callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)\n",
" }\n",
"\n",
" return extend(baseProps, {\n",
" onBeforeEnter(el) {\n",
" onBeforeEnter && onBeforeEnter(el)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const callHook = (hook: Hook | undefined, args: any[]) => {\n",
" hook &&\n",
" callWithAsyncErrorHandling(\n",
" hook,\n",
" instance,\n",
" ErrorCodes.TRANSITION_HOOK,\n",
" args\n",
" )\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 130
} | import {
NodeTypes,
ElementNode,
SourceLocation,
CompilerError,
TextModes
} from '@vue/compiler-core'
import { RawSourceMap, SourceMapGenerator } from 'source-map'
import { generateCodeFrame } from '@vue/shared'
import { TemplateCompiler } from './compileTemplate'
import * as CompilerDOM from '@vue/compiler-dom'
export interface SFCParseOptions {
filename?: string
sourceMap?: boolean
sourceRoot?: string
pad?: boolean | 'line' | 'space'
compiler?: TemplateCompiler
}
export interface SFCBlock {
type: string
content: string
attrs: Record<string, string | true>
loc: SourceLocation
map?: RawSourceMap
lang?: string
src?: string
}
export interface SFCTemplateBlock extends SFCBlock {
type: 'template'
functional?: boolean
}
export interface SFCScriptBlock extends SFCBlock {
type: 'script'
}
export interface SFCStyleBlock extends SFCBlock {
type: 'style'
scoped?: boolean
module?: string | boolean
}
export interface SFCDescriptor {
filename: string
template: SFCTemplateBlock | null
script: SFCScriptBlock | null
styles: SFCStyleBlock[]
customBlocks: SFCBlock[]
}
export interface SFCParseResult {
descriptor: SFCDescriptor
errors: CompilerError[]
}
const SFC_CACHE_MAX_SIZE = 500
const sourceToSFC =
__GLOBAL__ || __ESM_BROWSER__
? new Map<string, SFCParseResult>()
: (new (require('lru-cache'))(SFC_CACHE_MAX_SIZE) as Map<
string,
SFCParseResult
>)
export function parse(
source: string,
{
sourceMap = true,
filename = 'component.vue',
sourceRoot = '',
pad = false,
compiler = CompilerDOM
}: SFCParseOptions = {}
): SFCParseResult {
const sourceKey =
source + sourceMap + filename + sourceRoot + pad + compiler.parse
const cache = sourceToSFC.get(sourceKey)
if (cache) {
return cache
}
const descriptor: SFCDescriptor = {
filename,
template: null,
script: null,
styles: [],
customBlocks: []
}
const errors: CompilerError[] = []
const ast = compiler.parse(source, {
// there are no components at SFC parsing level
isNativeTag: () => true,
// preserve all whitespaces
isPreTag: () => true,
getTextMode: ({ tag, props }, parent) => {
// all top level elements except <template> are parsed as raw text
// containers
if (
(!parent && tag !== 'template') ||
// <template lang="xxx"> should also be treated as raw text
props.some(
p =>
p.type === NodeTypes.ATTRIBUTE &&
p.name === 'lang' &&
p.value &&
p.value.content !== 'html'
)
) {
return TextModes.RAWTEXT
} else {
return TextModes.DATA
}
},
onError: e => {
errors.push(e)
}
})
ast.children.forEach(node => {
if (node.type !== NodeTypes.ELEMENT) {
return
}
if (!node.children.length && !hasSrc(node)) {
return
}
switch (node.tag) {
case 'template':
if (!descriptor.template) {
descriptor.template = createBlock(
node,
source,
false
) as SFCTemplateBlock
} else {
warnDuplicateBlock(source, filename, node)
}
break
case 'script':
if (!descriptor.script) {
descriptor.script = createBlock(node, source, pad) as SFCScriptBlock
} else {
warnDuplicateBlock(source, filename, node)
}
break
case 'style':
descriptor.styles.push(createBlock(node, source, pad) as SFCStyleBlock)
break
default:
descriptor.customBlocks.push(createBlock(node, source, pad))
break
}
})
if (sourceMap) {
const genMap = (block: SFCBlock | null) => {
if (block && !block.src) {
block.map = generateSourceMap(
filename,
source,
block.content,
sourceRoot,
!pad || block.type === 'template' ? block.loc.start.line - 1 : 0
)
}
}
genMap(descriptor.template)
genMap(descriptor.script)
descriptor.styles.forEach(genMap)
}
const result = {
descriptor,
errors
}
sourceToSFC.set(sourceKey, result)
return result
}
function warnDuplicateBlock(
source: string,
filename: string,
node: ElementNode
) {
const codeFrame = generateCodeFrame(
source,
node.loc.start.offset,
node.loc.end.offset
)
const location = `${filename}:${node.loc.start.line}:${node.loc.start.column}`
console.warn(
`Single file component can contain only one ${
node.tag
} element (${location}):\n\n${codeFrame}`
)
}
function createBlock(
node: ElementNode,
source: string,
pad: SFCParseOptions['pad']
): SFCBlock {
const type = node.tag
let { start, end } = node.loc
let content = ''
if (node.children.length) {
start = node.children[0].loc.start
end = node.children[node.children.length - 1].loc.end
content = source.slice(start.offset, end.offset)
}
const loc = {
source: content,
start,
end
}
const attrs: Record<string, string | true> = {}
const block: SFCBlock = {
type,
content,
loc,
attrs
}
if (pad) {
block.content = padContent(source, block, pad) + block.content
}
node.props.forEach(p => {
if (p.type === NodeTypes.ATTRIBUTE) {
attrs[p.name] = p.value ? p.value.content || true : true
if (p.name === 'lang') {
block.lang = p.value && p.value.content
} else if (p.name === 'src') {
block.src = p.value && p.value.content
} else if (type === 'style') {
if (p.name === 'scoped') {
;(block as SFCStyleBlock).scoped = true
} else if (p.name === 'module') {
;(block as SFCStyleBlock).module = attrs[p.name]
}
} else if (type === 'template' && p.name === 'functional') {
;(block as SFCTemplateBlock).functional = true
}
}
})
return block
}
const splitRE = /\r?\n/g
const emptyRE = /^(?:\/\/)?\s*$/
const replaceRE = /./g
function generateSourceMap(
filename: string,
source: string,
generated: string,
sourceRoot: string,
lineOffset: number
): RawSourceMap {
const map = new SourceMapGenerator({
file: filename.replace(/\\/g, '/'),
sourceRoot: sourceRoot.replace(/\\/g, '/')
})
map.setSourceContent(filename, source)
generated.split(splitRE).forEach((line, index) => {
if (!emptyRE.test(line)) {
const originalLine = index + 1 + lineOffset
const generatedLine = index + 1
for (let i = 0; i < line.length; i++) {
if (!/\s/.test(line[i])) {
map.addMapping({
source: filename,
original: {
line: originalLine,
column: i
},
generated: {
line: generatedLine,
column: i
}
})
}
}
}
})
return JSON.parse(map.toString())
}
function padContent(
content: string,
block: SFCBlock,
pad: SFCParseOptions['pad']
): string {
content = content.slice(0, block.loc.start.offset)
if (pad === 'space') {
return content.replace(replaceRE, ' ')
} else {
const offset = content.split(splitRE).length
const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n'
return Array(offset).join(padChar)
}
}
function hasSrc(node: ElementNode) {
return node.props.some(p => {
if (p.type !== NodeTypes.ATTRIBUTE) {
return false
}
return p.name === 'src'
})
}
| packages/compiler-sfc/src/parse.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.0007729609496891499,
0.00019258999964222312,
0.00016714308003429323,
0.00017157549154944718,
0.00010469147673575208
] |
{
"id": 4,
"code_window": [
"\n",
" // only needed for user hooks called in nextFrame\n",
" // sync errors are already handled by BaseTransition\n",
" function callHookWithErrorHandling(hook: Hook, args: any[]) {\n",
" callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)\n",
" }\n",
"\n",
" return extend(baseProps, {\n",
" onBeforeEnter(el) {\n",
" onBeforeEnter && onBeforeEnter(el)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const callHook = (hook: Hook | undefined, args: any[]) => {\n",
" hook &&\n",
" callWithAsyncErrorHandling(\n",
" hook,\n",
" instance,\n",
" ErrorCodes.TRANSITION_HOOK,\n",
" args\n",
" )\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 130
} | export default {
master: [
{
sha: 'd1527fbee422c7170e56845e55b49c4fd6de72a7',
node_id:
'MDY6Q29tbWl0MTM3MDc4NDg3OmQxNTI3ZmJlZTQyMmM3MTcwZTU2ODQ1ZTU1YjQ5YzRmZDZkZTcyYTc=',
commit: {
author: {
name: 'Haoqun Jiang',
email: '[email protected]',
date: '2019-12-09T19:52:20Z'
},
committer: {
name: 'Evan You',
email: '[email protected]',
date: '2019-12-09T19:52:20Z'
},
message: 'test: add test for runtime-dom/modules/class (#75)',
tree: {
sha: 'f53f761827af281db86c31d113086c068c1d0789',
url:
'https://api.github.com/repos/vuejs/vue-next/git/trees/f53f761827af281db86c31d113086c068c1d0789'
},
url:
'https://api.github.com/repos/vuejs/vue-next/git/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7',
comment_count: 0,
verification: {
verified: false,
reason: 'unsigned',
signature: null,
payload: null
}
},
url:
'https://api.github.com/repos/vuejs/vue-next/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7',
html_url:
'https://github.com/vuejs/vue-next/commit/d1527fbee422c7170e56845e55b49c4fd6de72a7',
comments_url:
'https://api.github.com/repos/vuejs/vue-next/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7/comments',
author: {
login: 'sodatea',
id: 3277634,
node_id: 'MDQ6VXNlcjMyNzc2MzQ=',
avatar_url: 'https://avatars3.githubusercontent.com/u/3277634?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/sodatea',
html_url: 'https://github.com/sodatea',
followers_url: 'https://api.github.com/users/sodatea/followers',
following_url:
'https://api.github.com/users/sodatea/following{/other_user}',
gists_url: 'https://api.github.com/users/sodatea/gists{/gist_id}',
starred_url:
'https://api.github.com/users/sodatea/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/sodatea/subscriptions',
organizations_url: 'https://api.github.com/users/sodatea/orgs',
repos_url: 'https://api.github.com/users/sodatea/repos',
events_url: 'https://api.github.com/users/sodatea/events{/privacy}',
received_events_url:
'https://api.github.com/users/sodatea/received_events',
type: 'User',
site_admin: false
},
committer: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
parents: [
{
sha: '2383b45e322272ddc102d6914c149b284a25d04f',
url:
'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f',
html_url:
'https://github.com/vuejs/vue-next/commit/2383b45e322272ddc102d6914c149b284a25d04f'
}
]
},
{
sha: '2383b45e322272ddc102d6914c149b284a25d04f',
node_id:
'MDY6Q29tbWl0MTM3MDc4NDg3OjIzODNiNDVlMzIyMjcyZGRjMTAyZDY5MTRjMTQ5YjI4NGEyNWQwNGY=',
commit: {
author: {
name: 'GCA',
email: '[email protected]',
date: '2019-12-09T19:23:57Z'
},
committer: {
name: 'Evan You',
email: '[email protected]',
date: '2019-12-09T19:23:57Z'
},
message: 'chore: fix typo (#530) [ci skip]',
tree: {
sha: '2a5872ff8dc8ccb8121abd7e890ac3c0c9f1209f',
url:
'https://api.github.com/repos/vuejs/vue-next/git/trees/2a5872ff8dc8ccb8121abd7e890ac3c0c9f1209f'
},
url:
'https://api.github.com/repos/vuejs/vue-next/git/commits/2383b45e322272ddc102d6914c149b284a25d04f',
comment_count: 0,
verification: {
verified: false,
reason: 'unsigned',
signature: null,
payload: null
}
},
url:
'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f',
html_url:
'https://github.com/vuejs/vue-next/commit/2383b45e322272ddc102d6914c149b284a25d04f',
comments_url:
'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f/comments',
author: {
login: 'gcaaa31928',
id: 6309392,
node_id: 'MDQ6VXNlcjYzMDkzOTI=',
avatar_url: 'https://avatars1.githubusercontent.com/u/6309392?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/gcaaa31928',
html_url: 'https://github.com/gcaaa31928',
followers_url: 'https://api.github.com/users/gcaaa31928/followers',
following_url:
'https://api.github.com/users/gcaaa31928/following{/other_user}',
gists_url: 'https://api.github.com/users/gcaaa31928/gists{/gist_id}',
starred_url:
'https://api.github.com/users/gcaaa31928/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/gcaaa31928/subscriptions',
organizations_url: 'https://api.github.com/users/gcaaa31928/orgs',
repos_url: 'https://api.github.com/users/gcaaa31928/repos',
events_url: 'https://api.github.com/users/gcaaa31928/events{/privacy}',
received_events_url:
'https://api.github.com/users/gcaaa31928/received_events',
type: 'User',
site_admin: false
},
committer: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
parents: [
{
sha: 'e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
url:
'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
html_url:
'https://github.com/vuejs/vue-next/commit/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad'
}
]
},
{
sha: 'e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
node_id:
'MDY6Q29tbWl0MTM3MDc4NDg3OmU3ZTEzMTRjY2NkMWE2NmZjZjhiODUyNmVjMjEzNTBlYzE2Y2MzYWQ=',
commit: {
author: {
name: 'Evan You',
email: '[email protected]',
date: '2019-12-09T19:23:01Z'
},
committer: {
name: 'Evan You',
email: '[email protected]',
date: '2019-12-09T19:23:01Z'
},
message: 'test: fix warning',
tree: {
sha: 'd942b17681e2e2fbbcd2ee04092390c7f2cf534d',
url:
'https://api.github.com/repos/vuejs/vue-next/git/trees/d942b17681e2e2fbbcd2ee04092390c7f2cf534d'
},
url:
'https://api.github.com/repos/vuejs/vue-next/git/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
comment_count: 0,
verification: {
verified: false,
reason: 'unsigned',
signature: null,
payload: null
}
},
url:
'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
html_url:
'https://github.com/vuejs/vue-next/commit/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
comments_url:
'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad/comments',
author: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
committer: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
parents: [
{
sha: '12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e',
url:
'https://api.github.com/repos/vuejs/vue-next/commits/12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e',
html_url:
'https://github.com/vuejs/vue-next/commit/12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e'
}
]
}
],
sync: [
{
sha: 'ecf4da822eea97f5db5fa769d39f994755384a4b',
node_id:
'MDY6Q29tbWl0MTM3MDc4NDg3OmVjZjRkYTgyMmVlYTk3ZjVkYjVmYTc2OWQzOWY5OTQ3NTUzODRhNGI=',
commit: {
author: {
name: 'Evan You',
email: '[email protected]',
date: '2018-11-13T03:42:34Z'
},
committer: {
name: 'Evan You',
email: '[email protected]',
date: '2018-11-13T03:54:01Z'
},
message: 'chore: fix tests',
tree: {
sha: '6ac7bd078a6eb0ad32b5102e0c5d2c29f2b20a48',
url:
'https://api.github.com/repos/vuejs/vue-next/git/trees/6ac7bd078a6eb0ad32b5102e0c5d2c29f2b20a48'
},
url:
'https://api.github.com/repos/vuejs/vue-next/git/commits/ecf4da822eea97f5db5fa769d39f994755384a4b',
comment_count: 0,
verification: {
verified: false,
reason: 'unsigned',
signature: null,
payload: null
}
},
url:
'https://api.github.com/repos/vuejs/vue-next/commits/ecf4da822eea97f5db5fa769d39f994755384a4b',
html_url:
'https://github.com/vuejs/vue-next/commit/ecf4da822eea97f5db5fa769d39f994755384a4b',
comments_url:
'https://api.github.com/repos/vuejs/vue-next/commits/ecf4da822eea97f5db5fa769d39f994755384a4b/comments',
author: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
committer: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
parents: [
{
sha: 'ca296812d54aff123472d7147b83fddfb634d9bc',
url:
'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
html_url:
'https://github.com/vuejs/vue-next/commit/ca296812d54aff123472d7147b83fddfb634d9bc'
}
]
},
{
sha: 'ca296812d54aff123472d7147b83fddfb634d9bc',
node_id:
'MDY6Q29tbWl0MTM3MDc4NDg3OmNhMjk2ODEyZDU0YWZmMTIzNDcyZDcxNDdiODNmZGRmYjYzNGQ5YmM=',
commit: {
author: {
name: 'Evan You',
email: '[email protected]',
date: '2018-11-13T03:21:56Z'
},
committer: {
name: 'Evan You',
email: '[email protected]',
date: '2018-11-13T03:46:06Z'
},
message: 'refactor: bring back clone for reused nodes',
tree: {
sha: '2cec32c97686e0ee9af1b87f0abdbbbdc18b6de6',
url:
'https://api.github.com/repos/vuejs/vue-next/git/trees/2cec32c97686e0ee9af1b87f0abdbbbdc18b6de6'
},
url:
'https://api.github.com/repos/vuejs/vue-next/git/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
comment_count: 0,
verification: {
verified: false,
reason: 'unsigned',
signature: null,
payload: null
}
},
url:
'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
html_url:
'https://github.com/vuejs/vue-next/commit/ca296812d54aff123472d7147b83fddfb634d9bc',
comments_url:
'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc/comments',
author: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
committer: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
parents: [
{
sha: 'e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
url:
'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
html_url:
'https://github.com/vuejs/vue-next/commit/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b'
}
]
},
{
sha: 'e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
node_id:
'MDY6Q29tbWl0MTM3MDc4NDg3OmU2YmU1NWE0OTg5ZWRiNmY4NzUwZGJhYTE0ZWI2OTNlYzFmMGQ2N2I=',
commit: {
author: {
name: 'Evan You',
email: '[email protected]',
date: '2018-11-02T20:59:45Z'
},
committer: {
name: 'Evan You',
email: '[email protected]',
date: '2018-11-02T20:59:45Z'
},
message: 'chore: relax render type for tsx',
tree: {
sha: '7e2b3bb92ab91f755b2251e4a7903e6dd2042602',
url:
'https://api.github.com/repos/vuejs/vue-next/git/trees/7e2b3bb92ab91f755b2251e4a7903e6dd2042602'
},
url:
'https://api.github.com/repos/vuejs/vue-next/git/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
comment_count: 0,
verification: {
verified: false,
reason: 'unsigned',
signature: null,
payload: null
}
},
url:
'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
html_url:
'https://github.com/vuejs/vue-next/commit/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
comments_url:
'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b/comments',
author: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
committer: {
login: 'yyx990803',
id: 499550,
node_id: 'MDQ6VXNlcjQ5OTU1MA==',
avatar_url: 'https://avatars1.githubusercontent.com/u/499550?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/yyx990803',
html_url: 'https://github.com/yyx990803',
followers_url: 'https://api.github.com/users/yyx990803/followers',
following_url:
'https://api.github.com/users/yyx990803/following{/other_user}',
gists_url: 'https://api.github.com/users/yyx990803/gists{/gist_id}',
starred_url:
'https://api.github.com/users/yyx990803/starred{/owner}{/repo}',
subscriptions_url:
'https://api.github.com/users/yyx990803/subscriptions',
organizations_url: 'https://api.github.com/users/yyx990803/orgs',
repos_url: 'https://api.github.com/users/yyx990803/repos',
events_url: 'https://api.github.com/users/yyx990803/events{/privacy}',
received_events_url:
'https://api.github.com/users/yyx990803/received_events',
type: 'User',
site_admin: false
},
parents: [
{
sha: 'ccc835caff0344baad3c92ce786ad4f804bf667b',
url:
'https://api.github.com/repos/vuejs/vue-next/commits/ccc835caff0344baad3c92ce786ad4f804bf667b',
html_url:
'https://github.com/vuejs/vue-next/commit/ccc835caff0344baad3c92ce786ad4f804bf667b'
}
]
}
]
}
| packages/vue/examples/__tests__/commits.mock.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017546527669765055,
0.00017197098350152373,
0.00016660208348184824,
0.0001720371947158128,
0.0000019895708192052552
] |
{
"id": 4,
"code_window": [
"\n",
" // only needed for user hooks called in nextFrame\n",
" // sync errors are already handled by BaseTransition\n",
" function callHookWithErrorHandling(hook: Hook, args: any[]) {\n",
" callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)\n",
" }\n",
"\n",
" return extend(baseProps, {\n",
" onBeforeEnter(el) {\n",
" onBeforeEnter && onBeforeEnter(el)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const callHook = (hook: Hook | undefined, args: any[]) => {\n",
" hook &&\n",
" callWithAsyncErrorHandling(\n",
" hook,\n",
" instance,\n",
" ErrorCodes.TRANSITION_HOOK,\n",
" args\n",
" )\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 130
} | // SFC scoped style ID management.
// These are only used in esm-bundler builds, but since exports cannot be
// conditional, we can only drop inner implementations in non-bundler builds.
import { withCtx } from './withRenderContext'
export let currentScopeId: string | null = null
const scopeIdStack: string[] = []
/**
* @private
*/
export function pushScopeId(id: string) {
scopeIdStack.push((currentScopeId = id))
}
/**
* @private
*/
export function popScopeId() {
scopeIdStack.pop()
currentScopeId = scopeIdStack[scopeIdStack.length - 1] || null
}
/**
* @private
*/
export function withScopeId(id: string): <T extends Function>(fn: T) => T {
return ((fn: Function) =>
withCtx(function(this: any) {
pushScopeId(id)
const res = fn.apply(this, arguments)
popScopeId()
return res
})) as any
}
| packages/runtime-core/src/helpers/scopeId.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.0006247813580557704,
0.0002833980543073267,
0.0001682470174273476,
0.00017028191359713674,
0.00019709992920979857
] |
{
"id": 5,
"code_window": [
" addTransitionClass(el, enterFromClass)\n",
" },\n",
" onEnter(el, done) {\n",
" nextFrame(() => {\n",
" const resolve = () => finishEnter(el, done)\n",
" onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])\n",
" removeTransitionClass(el, enterFromClass)\n",
" addTransitionClass(el, enterToClass)\n",
" if (!(onEnter && onEnter.length > 1)) {\n",
" if (enterDuration) {\n",
" setTimeout(resolve, enterDuration)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" callHook(onEnter, [el, resolve])\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 143
} | import {
BaseTransition,
BaseTransitionProps,
h,
warn,
FunctionalComponent,
getCurrentInstance,
callWithAsyncErrorHandling
} from '@vue/runtime-core'
import { isObject, toNumber, extend } from '@vue/shared'
import { ErrorCodes } from 'packages/runtime-core/src/errorHandling'
const TRANSITION = 'transition'
const ANIMATION = 'animation'
export interface TransitionProps extends BaseTransitionProps<Element> {
name?: string
type?: typeof TRANSITION | typeof ANIMATION
css?: boolean
duration?: number | { enter: number; leave: number }
// custom transition classes
enterFromClass?: string
enterActiveClass?: string
enterToClass?: string
appearFromClass?: string
appearActiveClass?: string
appearToClass?: string
leaveFromClass?: string
leaveActiveClass?: string
leaveToClass?: string
}
// DOM Transition is a higher-order-component based on the platform-agnostic
// base Transition component, with DOM-specific logic.
export const Transition: FunctionalComponent<TransitionProps> = (
props,
{ slots }
) => h(BaseTransition, resolveTransitionProps(props), slots)
Transition.inheritRef = true
const DOMTransitionPropsValidators = {
name: String,
type: String,
css: {
type: Boolean,
default: true
},
duration: [String, Number, Object],
enterFromClass: String,
enterActiveClass: String,
enterToClass: String,
appearFromClass: String,
appearActiveClass: String,
appearToClass: String,
leaveFromClass: String,
leaveActiveClass: String,
leaveToClass: String
}
export const TransitionPropsValidators = (Transition.props = extend(
{},
(BaseTransition as any).props,
DOMTransitionPropsValidators
))
export function resolveTransitionProps(
rawProps: TransitionProps
): BaseTransitionProps<Element> {
let {
name = 'v',
type,
css = true,
duration,
enterFromClass = `${name}-enter-from`,
enterActiveClass = `${name}-enter-active`,
enterToClass = `${name}-enter-to`,
appearFromClass = enterFromClass,
appearActiveClass = enterActiveClass,
appearToClass = enterToClass,
leaveFromClass = `${name}-leave-from`,
leaveActiveClass = `${name}-leave-active`,
leaveToClass = `${name}-leave-to`
} = rawProps
const baseProps: BaseTransitionProps<Element> = {}
for (const key in rawProps) {
if (!(key in DOMTransitionPropsValidators)) {
;(baseProps as any)[key] = (rawProps as any)[key]
}
}
if (!css) {
return baseProps
}
const originEnterClass = [enterFromClass, enterActiveClass, enterToClass]
const instance = getCurrentInstance()!
const durations = normalizeDuration(duration)
const enterDuration = durations && durations[0]
const leaveDuration = durations && durations[1]
const { appear, onBeforeEnter, onEnter, onLeave } = baseProps
// is appearing
if (appear && !instance.isMounted) {
enterFromClass = appearFromClass
enterActiveClass = appearActiveClass
enterToClass = appearToClass
}
type Hook = (el: Element, done?: () => void) => void
const finishEnter: Hook = (el, done) => {
removeTransitionClass(el, enterToClass)
removeTransitionClass(el, enterActiveClass)
done && done()
// reset enter class
if (appear) {
;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass
}
}
const finishLeave: Hook = (el, done) => {
removeTransitionClass(el, leaveToClass)
removeTransitionClass(el, leaveActiveClass)
done && done()
}
// only needed for user hooks called in nextFrame
// sync errors are already handled by BaseTransition
function callHookWithErrorHandling(hook: Hook, args: any[]) {
callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args)
}
return extend(baseProps, {
onBeforeEnter(el) {
onBeforeEnter && onBeforeEnter(el)
addTransitionClass(el, enterActiveClass)
addTransitionClass(el, enterFromClass)
},
onEnter(el, done) {
nextFrame(() => {
const resolve = () => finishEnter(el, done)
onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])
removeTransitionClass(el, enterFromClass)
addTransitionClass(el, enterToClass)
if (!(onEnter && onEnter.length > 1)) {
if (enterDuration) {
setTimeout(resolve, enterDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onLeave(el, done) {
addTransitionClass(el, leaveActiveClass)
addTransitionClass(el, leaveFromClass)
nextFrame(() => {
const resolve = () => finishLeave(el, done)
onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])
removeTransitionClass(el, leaveFromClass)
addTransitionClass(el, leaveToClass)
if (!(onLeave && onLeave.length > 1)) {
if (leaveDuration) {
setTimeout(resolve, leaveDuration)
} else {
whenTransitionEnds(el, type, resolve)
}
}
})
},
onEnterCancelled: finishEnter,
onLeaveCancelled: finishLeave
} as BaseTransitionProps<Element>)
}
function normalizeDuration(
duration: TransitionProps['duration']
): [number, number] | null {
if (duration == null) {
return null
} else if (isObject(duration)) {
return [NumberOf(duration.enter), NumberOf(duration.leave)]
} else {
const n = NumberOf(duration)
return [n, n]
}
}
function NumberOf(val: unknown): number {
const res = toNumber(val)
if (__DEV__) validateDuration(res)
return res
}
function validateDuration(val: unknown) {
if (typeof val !== 'number') {
warn(
`<transition> explicit duration is not a valid number - ` +
`got ${JSON.stringify(val)}.`
)
} else if (isNaN(val)) {
warn(
`<transition> explicit duration is NaN - ` +
'the duration expression might be incorrect.'
)
}
}
export interface ElementWithTransition extends HTMLElement {
// _vtc = Vue Transition Classes.
// Store the temporarily-added transition classes on the element
// so that we can avoid overwriting them if the element's class is patched
// during the transition.
_vtc?: Set<string>
}
export function addTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.add(c))
;(
(el as ElementWithTransition)._vtc ||
((el as ElementWithTransition)._vtc = new Set())
).add(cls)
}
export function removeTransitionClass(el: Element, cls: string) {
cls.split(/\s+/).forEach(c => c && el.classList.remove(c))
const { _vtc } = el as ElementWithTransition
if (_vtc) {
_vtc.delete(cls)
if (!_vtc!.size) {
;(el as ElementWithTransition)._vtc = undefined
}
}
}
function nextFrame(cb: () => void) {
requestAnimationFrame(() => {
requestAnimationFrame(cb)
})
}
function whenTransitionEnds(
el: Element,
expectedType: TransitionProps['type'] | undefined,
cb: () => void
) {
const { type, timeout, propCount } = getTransitionInfo(el, expectedType)
if (!type) {
return cb()
}
const endEvent = type + 'end'
let ended = 0
const end = () => {
el.removeEventListener(endEvent, onEnd)
cb()
}
const onEnd = (e: Event) => {
if (e.target === el) {
if (++ended >= propCount) {
end()
}
}
}
setTimeout(() => {
if (ended < propCount) {
end()
}
}, timeout + 1)
el.addEventListener(endEvent, onEnd)
}
interface CSSTransitionInfo {
type: typeof TRANSITION | typeof ANIMATION | null
propCount: number
timeout: number
hasTransform: boolean
}
export function getTransitionInfo(
el: Element,
expectedType?: TransitionProps['type']
): CSSTransitionInfo {
const styles: any = window.getComputedStyle(el)
// JSDOM may return undefined for transition properties
const getStyleProperties = (key: string) => (styles[key] || '').split(', ')
const transitionDelays = getStyleProperties(TRANSITION + 'Delay')
const transitionDurations = getStyleProperties(TRANSITION + 'Duration')
const transitionTimeout = getTimeout(transitionDelays, transitionDurations)
const animationDelays = getStyleProperties(ANIMATION + 'Delay')
const animationDurations = getStyleProperties(ANIMATION + 'Duration')
const animationTimeout = getTimeout(animationDelays, animationDurations)
let type: CSSTransitionInfo['type'] = null
let timeout = 0
let propCount = 0
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION
timeout = transitionTimeout
propCount = transitionDurations.length
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION
timeout = animationTimeout
propCount = animationDurations.length
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout)
type =
timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0
}
const hasTransform =
type === TRANSITION &&
/\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property'])
return {
type,
timeout,
propCount,
hasTransform
}
}
function getTimeout(delays: string[], durations: string[]): number {
while (delays.length < durations.length) {
delays = delays.concat(delays)
}
return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])))
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
// numbers in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down
// (i.e. acting as a floor function) causing unexpected behaviors
function toMs(s: string): number {
return Number(s.slice(0, -1).replace(',', '.')) * 1000
}
| packages/runtime-dom/src/components/Transition.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.9984764456748962,
0.08936414122581482,
0.00016055989544838667,
0.0010056549217551947,
0.27432316541671753
] |
{
"id": 5,
"code_window": [
" addTransitionClass(el, enterFromClass)\n",
" },\n",
" onEnter(el, done) {\n",
" nextFrame(() => {\n",
" const resolve = () => finishEnter(el, done)\n",
" onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])\n",
" removeTransitionClass(el, enterFromClass)\n",
" addTransitionClass(el, enterToClass)\n",
" if (!(onEnter && onEnter.length > 1)) {\n",
" if (enterDuration) {\n",
" setTimeout(resolve, enterDuration)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" callHook(onEnter, [el, resolve])\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 143
} | module.exports = {
preset: 'ts-jest',
globals: {
__DEV__: true,
__TEST__: true,
__VERSION__: require('./package.json').version,
__BROWSER__: false,
__GLOBAL__: false,
__ESM_BUNDLER__: true,
__ESM_BROWSER__: false,
__NODE_JS__: true,
__FEATURE_OPTIONS__: true,
__FEATURE_SUSPENSE__: true
},
coverageDirectory: 'coverage',
coverageReporters: ['html', 'lcov', 'text'],
collectCoverageFrom: [
'packages/*/src/**/*.ts',
'!packages/runtime-test/src/utils/**',
'!packages/template-explorer/**',
'!packages/size-check/**',
'!packages/runtime-core/src/profiling.ts',
// DOM transitions are tested via e2e so no coverage is collected
'!packages/runtime-dom/src/components/Transition*',
// only called in browsers
'!packages/vue/src/devCheck.ts',
// only used as a build entry
'!packages/vue/src/runtime.ts'
],
watchPathIgnorePatterns: ['/node_modules/', '/dist/', '/.git/'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
moduleNameMapper: {
'^@vue/(.*?)$': '<rootDir>/packages/$1/src',
vue: '<rootDir>/packages/vue/src'
},
rootDir: __dirname,
testMatch: ['<rootDir>/packages/**/__tests__/**/*spec.[jt]s?(x)'],
testPathIgnorePatterns: process.env.SKIP_E2E
? // ignore example tests on netlify builds since they don't contribute
// to coverage and can cause netlify builds to fail
['/node_modules/', '/examples/__tests__']
: ['/node_modules/']
}
| jest.config.js | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017620599828660488,
0.00017257998115383089,
0.00017085437139030546,
0.00017157547699753195,
0.0000019243975657445844
] |
{
"id": 5,
"code_window": [
" addTransitionClass(el, enterFromClass)\n",
" },\n",
" onEnter(el, done) {\n",
" nextFrame(() => {\n",
" const resolve = () => finishEnter(el, done)\n",
" onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])\n",
" removeTransitionClass(el, enterFromClass)\n",
" addTransitionClass(el, enterToClass)\n",
" if (!(onEnter && onEnter.length > 1)) {\n",
" if (enterDuration) {\n",
" setTimeout(resolve, enterDuration)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" callHook(onEnter, [el, resolve])\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 143
} | {
"name": "@vue/compiler-ssr",
"version": "3.0.0-beta.15",
"description": "@vue/compiler-ssr",
"main": "dist/compiler-ssr.cjs.js",
"types": "dist/compiler-ssr.d.ts",
"files": [
"dist"
],
"buildOptions": {
"prod": false,
"formats": [
"cjs"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue-next.git"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue-next/issues"
},
"homepage": "https://github.com/vuejs/vue-next/tree/master/packages/compiler-ssr#readme",
"dependencies": {
"@vue/shared": "3.0.0-beta.15",
"@vue/compiler-dom": "3.0.0-beta.15"
}
}
| packages/compiler-ssr/package.json | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017607130575925112,
0.00017330830451101065,
0.00017014797776937485,
0.0001735069672577083,
0.0000024169530661311
] |
{
"id": 5,
"code_window": [
" addTransitionClass(el, enterFromClass)\n",
" },\n",
" onEnter(el, done) {\n",
" nextFrame(() => {\n",
" const resolve = () => finishEnter(el, done)\n",
" onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve])\n",
" removeTransitionClass(el, enterFromClass)\n",
" addTransitionClass(el, enterToClass)\n",
" if (!(onEnter && onEnter.length > 1)) {\n",
" if (enterDuration) {\n",
" setTimeout(resolve, enterDuration)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" callHook(onEnter, [el, resolve])\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 143
} | import { DirectiveTransform } from '../transform'
export const noopDirectiveTransform: DirectiveTransform = () => ({ props: [] })
| packages/compiler-core/src/transforms/noopDirectiveTransform.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017221189045812935,
0.00017221189045812935,
0.00017221189045812935,
0.00017221189045812935,
0
] |
{
"id": 6,
"code_window": [
" addTransitionClass(el, leaveFromClass)\n",
" nextFrame(() => {\n",
" const resolve = () => finishLeave(el, done)\n",
" onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])\n",
" removeTransitionClass(el, leaveFromClass)\n",
" addTransitionClass(el, leaveToClass)\n",
" if (!(onLeave && onLeave.length > 1)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" callHook(onLeave, [el, resolve])\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 160
} | import { E2E_TIMEOUT, setupPuppeteer } from './e2eUtils'
import path from 'path'
import { mockWarn } from '@vue/shared'
import { h, createApp, Transition } from 'vue'
describe('e2e: Transition', () => {
mockWarn()
const { page, html, classList, isVisible } = setupPuppeteer()
const baseUrl = `file://${path.resolve(__dirname, './transition.html')}`
const duration = 50
const buffer = 5
const classWhenTransitionStart = () =>
page().evaluate(() => {
(document.querySelector('#toggleBtn') as any)!.click()
return Promise.resolve().then(() => {
return document.querySelector('#container div')!.className.split(/\s+/g)
})
})
const transitionFinish = (time = duration) =>
new Promise(r => {
setTimeout(r, time + buffer)
})
const nextFrame = () => {
return page().evaluate(() => {
return new Promise(resolve => {
requestAnimationFrame(() => {
requestAnimationFrame(resolve)
})
})
})
}
beforeEach(async () => {
await page().goto(baseUrl)
await page().waitFor('#app')
})
describe('transition with v-if', () => {
test(
'basic transition',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition>
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'v-leave-active',
'v-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'v-leave-active',
'v-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'v-enter-active',
'v-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'v-enter-active',
'v-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'named transition',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'custom transition classes',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition enter-from-class="hello-from"
enter-active-class="hello-active"
enter-to-class="hello-to"
leave-from-class="bye-from"
leave-active-class="bye-active"
leave-to-class="bye-to">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'bye-active',
'bye-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'bye-active',
'bye-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'hello-active',
'hello-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'hello-active',
'hello-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition with dynamic name',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition :name="name">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
<button id="changeNameBtn" @click="changeName">button</button>
`,
setup: () => {
const name = ref('test')
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
const changeName = () => (name.value = 'changed')
return { toggle, click, name, changeName }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
await page().evaluate(() => {
;(document.querySelector('#changeNameBtn') as any).click()
})
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'changed-enter-active',
'changed-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'changed-enter-active',
'changed-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition events without appear',
async () => {
const beforeLeaveSpy = jest.fn()
const onLeaveSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const onEnterSpy = jest.fn()
const afterEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().evaluate(() => {
const {
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
// todo test event with arguments. Note: not get dom, get object. '{}'
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(beforeLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
expect(afterLeaveSpy).toBeCalled()
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).not.toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
test('onEnterCancelled', async () => {
const enterCancelledSpy = jest.fn()
await page().exposeFunction('enterCancelledSpy', enterCancelledSpy)
await page().evaluate(() => {
const { enterCancelledSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@enter-cancelled="enterCancelledSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(false)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
enterCancelledSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
// cancel (leave)
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
// fixme
expect(enterCancelledSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
})
test(
'transition on appear',
async () => {
await page().evaluate(async () => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
// appear
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition events with appear',
async () => {
const onLeaveSpy = jest.fn()
const onEnterSpy = jest.fn()
const onAppearSpy = jest.fn()
const beforeLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const beforeAppearSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const afterEnterSpy = jest.fn()
const afterAppearSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('onAppearSpy', onAppearSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('beforeAppearSpy', beforeAppearSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().exposeFunction('afterAppearSpy', afterAppearSpy)
const appearClass = await page().evaluate(async () => {
const {
beforeAppearSpy,
onAppearSpy,
afterAppearSpy,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy"
@before-appear="beforeAppearSpy"
@appear="onAppearSpy"
@after-appear="afterAppearSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeAppearSpy,
onAppearSpy,
afterAppearSpy,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
return Promise.resolve().then(() => {
return document.querySelector('.test')!.className.split(/\s+/g)
})
})
// appear fixme spy called
expect(appearClass).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
expect(beforeAppearSpy).not.toBeCalled()
expect(onAppearSpy).not.toBeCalled()
expect(afterAppearSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
expect(onAppearSpy).not.toBeCalled()
expect(afterAppearSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterAppearSpy).not.toBeCalled()
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(onLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
expect(afterLeaveSpy).toBeCalled()
// enter fixme spy called
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
// fixme
test(
'css: false',
async () => {
const onLeaveSpy = jest.fn()
const onEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().evaluate(() => {
const { onLeaveSpy, onEnterSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
:css="false"
name="test"
@enter="onEnterSpy"
@leave="onLeaveSpy">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click"></button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click, onLeaveSpy, onEnterSpy }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
await classWhenTransitionStart()
expect(onLeaveSpy).toBeCalled()
expect(await html('#container')).toBe(
'<div class="test">content</div><!--v-if-->'
)
// enter
await classWhenTransitionStart()
expect(onEnterSpy).toBeCalled()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'no transition detected',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="noop">
<div v-if="toggle">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'noop-leave-active',
'noop-leave-from'
])
await nextFrame()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'noop-enter-active',
'noop-enter-from'
])
await nextFrame()
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'animations',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test-anim">
<div v-if="toggle">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-leave-active',
'test-anim-leave-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-leave-active',
'test-anim-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-enter-active',
'test-anim-enter-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-enter-active',
'test-anim-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'explicit transition type',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container"><transition name="test-anim-long" type="animation"><div v-if="toggle">content</div></transition></div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div>content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-to'
])
await new Promise(r => {
setTimeout(r, duration + 5)
})
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-leave-active',
'test-anim-long-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-from'
])
await nextFrame()
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-to'
])
await new Promise(r => {
setTimeout(r, duration + 5)
})
expect(await classList('#container div')).toStrictEqual([
'test-anim-long-enter-active',
'test-anim-long-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="">content</div>')
},
E2E_TIMEOUT
)
test(
'transition on SVG elements',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<svg id="container">
<transition name="test">
<circle v-if="toggle" cx="0" cy="0" r="10" class="test"></circle>
</transition>
</svg>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe(
'<circle cx="0" cy="0" r="10" class="test"></circle>'
)
const svgTransitionStart = () =>
page().evaluate(() => {
document.querySelector('button')!.click()
return Promise.resolve().then(() => {
return document
.querySelector('.test')!
.getAttribute('class')!
.split(/\s+/g)
})
})
// leave
expect(await svgTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await svgTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<circle cx="0" cy="0" r="10" class="test"></circle>'
)
},
E2E_TIMEOUT
)
test(
'custom transition higher-order component',
async () => {
await page().evaluate(() => {
const { createApp, ref, h, Transition } = (window as any).Vue
createApp({
template: `
<div id="container"><my-transition><div v-if="toggle" class="test">content</div></my-transition></div>
<button id="toggleBtn" @click="click">button</button>
`,
components: {
'my-transition': (props: any, { slots }: any) => {
return h(Transition, { name: 'test' }, slots)
}
},
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'transition on child components with empty root node',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<component class="test" :is="view"></component>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
<button id="changeViewBtn" @click="change">button</button>
`,
components: {
one: {
template: '<div v-if="false">one</div>'
},
two: {
template: '<div>two</div>'
}
},
setup: () => {
const toggle = ref(true)
const view = ref('one')
const click = () => (toggle.value = !toggle.value)
const change = () =>
(view.value = view.value === 'one' ? 'two' : 'one')
return { toggle, click, change, view }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<!--v-if-->')
// change view -> 'two'
await page().evaluate(() => {
(document.querySelector('#changeViewBtn') as any)!.click()
})
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">two</div>')
// change view -> 'one'
await page().evaluate(() => {
(document.querySelector('#changeViewBtn') as any)!.click()
})
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
},
E2E_TIMEOUT
)
})
describe('transition with v-show', () => {
test(
'named transition with v-show',
async () => {
await page().evaluate(() => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(await isVisible('.test')).toBe(true)
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
test(
'transition events with v-show',
async () => {
const beforeLeaveSpy = jest.fn()
const onLeaveSpy = jest.fn()
const afterLeaveSpy = jest.fn()
const beforeEnterSpy = jest.fn()
const onEnterSpy = jest.fn()
const afterEnterSpy = jest.fn()
await page().exposeFunction('onLeaveSpy', onLeaveSpy)
await page().exposeFunction('onEnterSpy', onEnterSpy)
await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy)
await page().exposeFunction('beforeEnterSpy', beforeEnterSpy)
await page().exposeFunction('afterLeaveSpy', afterLeaveSpy)
await page().exposeFunction('afterEnterSpy', afterEnterSpy)
await page().evaluate(() => {
const {
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
} = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition
name="test"
@before-enter="beforeEnterSpy"
@enter="onEnterSpy"
@after-enter="afterEnterSpy"
@before-leave="beforeLeaveSpy"
@leave="onLeaveSpy"
@after-leave="afterLeaveSpy">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return {
toggle,
click,
beforeEnterSpy,
onEnterSpy,
afterEnterSpy,
beforeLeaveSpy,
onLeaveSpy,
afterLeaveSpy
}
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
expect(beforeLeaveSpy).toBeCalled()
expect(onLeaveSpy).not.toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
expect(beforeLeaveSpy).toBeCalled()
expect(afterLeaveSpy).not.toBeCalled()
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
expect(afterLeaveSpy).toBeCalled()
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
expect(beforeEnterSpy).toBeCalled()
expect(onEnterSpy).not.toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
expect(onEnterSpy).toBeCalled()
expect(afterEnterSpy).not.toBeCalled()
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
expect(afterEnterSpy).toBeCalled()
},
E2E_TIMEOUT
)
test(
'onLeaveCancelled (v-show only)',
async () => {
const onLeaveCancelledSpy = jest.fn()
await page().exposeFunction('onLeaveCancelledSpy', onLeaveCancelledSpy)
await page().evaluate(() => {
const { onLeaveCancelledSpy } = window as any
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test">
<div v-show="toggle" class="test" @leave-cancelled="onLeaveCancelledSpy">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click, onLeaveCancelledSpy }
}
}).mount('#app')
})
expect(await html('#container')).toBe('<div class="test">content</div>')
expect(await isVisible('.test')).toBe(true)
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
// cancel (enter)
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
// fixme
expect(onLeaveCancelledSpy).not.toBeCalled()
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
test(
'transition on appear with v-show',
async () => {
const appearClass = await page().evaluate(async () => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test"
appear
appear-from-class="test-appear-from"
appear-to-class="test-appear-to"
appear-active-class="test-appear-active">
<div v-show="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
return Promise.resolve().then(() => {
return document.querySelector('.test')!.className.split(/\s+/g)
})
})
// appear
expect(appearClass).toStrictEqual([
'test',
'test-appear-active',
'test-appear-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-appear-active',
'test-appear-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await isVisible('.test')).toBe(false)
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe(
'<div class="test" style="">content</div>'
)
},
E2E_TIMEOUT
)
})
test(
'warn when used on multiple elements',
async () => {
createApp({
render() {
return h(Transition, null, {
default: () => [h('div'), h('div')]
})
}
}).mount(document.createElement('div'))
expect(
'<transition> can only be used on a single element or component'
).toHaveBeenWarned()
},
E2E_TIMEOUT
)
describe('explicit durations', () => {
test(
'single value',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" duration="${duration * 2}">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'enter with explicit durations',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{ enter: ${duration * 2} }">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'leave with explicit durations',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{ leave: ${duration * 2} }">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish()
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
test(
'separate enter and leave',
async () => {
await page().evaluate(duration => {
const { createApp, ref } = (window as any).Vue
createApp({
template: `
<div id="container">
<transition name="test" :duration="{
enter: ${duration * 4},
leave: ${duration * 2}
}">
<div v-if="toggle" class="test">content</div>
</transition>
</div>
<button id="toggleBtn" @click="click">button</button>
`,
setup: () => {
const toggle = ref(true)
const click = () => (toggle.value = !toggle.value)
return { toggle, click }
}
}).mount('#app')
}, duration)
expect(await html('#container')).toBe('<div class="test">content</div>')
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-leave-active',
'test-leave-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-leave-active',
'test-leave-to'
])
await transitionFinish(duration * 2)
expect(await html('#container')).toBe('<!--v-if-->')
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
'test',
'test-enter-active',
'test-enter-from'
])
await nextFrame()
expect(await classList('.test')).toStrictEqual([
'test',
'test-enter-active',
'test-enter-to'
])
await transitionFinish(200)
expect(await html('#container')).toBe('<div class="test">content</div>')
},
E2E_TIMEOUT
)
// fixme
test.todo('warn invalid durations')
})
})
| packages/vue/__tests__/Transition.spec.ts | 1 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.0021062693558633327,
0.00029672117670997977,
0.0001628532918402925,
0.00019174147746525705,
0.0003158301115036011
] |
{
"id": 6,
"code_window": [
" addTransitionClass(el, leaveFromClass)\n",
" nextFrame(() => {\n",
" const resolve = () => finishLeave(el, done)\n",
" onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])\n",
" removeTransitionClass(el, leaveFromClass)\n",
" addTransitionClass(el, leaveToClass)\n",
" if (!(onLeave && onLeave.length > 1)) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" callHook(onLeave, [el, resolve])\n"
],
"file_path": "packages/runtime-dom/src/components/Transition.ts",
"type": "replace",
"edit_start_line_idx": 160
} | import { createApp, h, Suspense } from 'vue'
import { renderToString } from '../src/renderToString'
import { mockWarn } from '@vue/shared'
describe('SSR Suspense', () => {
mockWarn()
const ResolvingAsync = {
async setup() {
return () => h('div', 'async')
}
}
const RejectingAsync = {
setup() {
return new Promise((_, reject) => reject('foo'))
}
}
test('content', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h(ResolvingAsync),
fallback: h('div', 'fallback')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(`<div>async</div>`)
})
test('reject', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h(RejectingAsync),
fallback: h('div', 'fallback')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(`<!---->`)
expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template').toHaveBeenWarned()
})
test('2 components', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h('div', [h(ResolvingAsync), h(ResolvingAsync)]),
fallback: h('div', 'fallback')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(
`<div><div>async</div><div>async</div></div>`
)
})
test('resolving component + rejecting component', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h('div', [h(ResolvingAsync), h(RejectingAsync)]),
fallback: h('div', 'fallback')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(
`<div><div>async</div><!----></div>`
)
expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template or render function').toHaveBeenWarned()
})
test('failing suspense in passing suspense', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h('div', [
h(ResolvingAsync),
h(Suspense, null, {
default: h('div', [h(RejectingAsync)]),
fallback: h('div', 'fallback 2')
})
]),
fallback: h('div', 'fallback 1')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(
`<div><div>async</div><div><!----></div></div>`
)
expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template').toHaveBeenWarned()
})
test('passing suspense in failing suspense', async () => {
const Comp = {
render() {
return h(Suspense, null, {
default: h('div', [
h(RejectingAsync),
h(Suspense, null, {
default: h('div', [h(ResolvingAsync)]),
fallback: h('div', 'fallback 2')
})
]),
fallback: h('div', 'fallback 1')
})
}
}
expect(await renderToString(createApp(Comp))).toBe(
`<div><!----><div><div>async</div></div></div>`
)
expect('Uncaught error in async setup').toHaveBeenWarned()
expect('missing template').toHaveBeenWarned()
})
})
| packages/server-renderer/__tests__/ssrSuspense.spec.ts | 0 | https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02 | [
0.00017478516383562237,
0.00017275962454732507,
0.00016971146396826953,
0.00017285793728660792,
0.0000015423021295646322
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.