hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 3,
"code_window": [
" }\n",
"\n",
" executablePath(): string {\n",
" if (!this._executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n",
" return this._executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Note: this file should be loadabale with eval() into worker environment.
// Avoid Components.*, ChromeUtils and global const variables.
if (!this.Debugger) {
// Worker has a Debugger defined already.
const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm", {});
addDebuggerToGlobal(Components.utils.getGlobalForObject(this));
}
let lastId = 0;
function generateId() {
return 'id-' + (++lastId);
}
const consoleLevelToProtocolType = {
'dir': 'dir',
'log': 'log',
'debug': 'debug',
'info': 'info',
'error': 'error',
'warn': 'warning',
'dirxml': 'dirxml',
'table': 'table',
'trace': 'trace',
'clear': 'clear',
'group': 'startGroup',
'groupCollapsed': 'startGroupCollapsed',
'groupEnd': 'endGroup',
'assert': 'assert',
'profile': 'profile',
'profileEnd': 'profileEnd',
'count': 'count',
'countReset': 'countReset',
'time': null,
'timeLog': 'timeLog',
'timeEnd': 'timeEnd',
'timeStamp': 'timeStamp',
};
const disallowedMessageCategories = new Set([
'XPConnect JavaScript',
'component javascript',
'chrome javascript',
'chrome registration',
'XBL',
'XBL Prototype Handler',
'XBL Content Sink',
'xbl javascript',
]);
class Runtime {
constructor(isWorker = false) {
this._debugger = new Debugger();
this._pendingPromises = new Map();
this._executionContexts = new Map();
this._windowToExecutionContext = new Map();
this._eventListeners = [];
if (isWorker) {
this._registerWorkerConsoleHandler();
} else {
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
this._registerConsoleServiceListener(Services);
this._registerConsoleObserver(Services);
}
// We can't use event listener here to be compatible with Worker Global Context.
// Use plain callbacks instead.
this.events = {
onConsoleMessage: createEvent(),
onErrorFromWorker: createEvent(),
onExecutionContextCreated: createEvent(),
onExecutionContextDestroyed: createEvent(),
};
}
executionContexts() {
return [...this._executionContexts.values()];
}
async evaluate({executionContextId, expression, returnByValue}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
const exceptionDetails = {};
let result = await executionContext.evaluateScript(expression, exceptionDetails);
if (!result)
return {exceptionDetails};
if (returnByValue)
result = executionContext.ensureSerializedToValue(result);
return {result};
}
async callFunction({executionContextId, functionDeclaration, args, returnByValue}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
const exceptionDetails = {};
let result = await executionContext.evaluateFunction(functionDeclaration, args, exceptionDetails);
if (!result)
return {exceptionDetails};
if (returnByValue)
result = executionContext.ensureSerializedToValue(result);
return {result};
}
async getObjectProperties({executionContextId, objectId}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
return {properties: executionContext.getObjectProperties(objectId)};
}
async disposeObject({executionContextId, objectId}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
return executionContext.disposeObject(objectId);
}
_registerConsoleServiceListener(Services) {
const Ci = Components.interfaces;
const consoleServiceListener = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIConsoleListener]),
observe: message => {
if (!(message instanceof Ci.nsIScriptError) || !message.outerWindowID ||
!message.category || disallowedMessageCategories.has(message.category)) {
return;
}
const errorWindow = Services.wm.getOuterWindowWithId(message.outerWindowID);
if (message.category === 'Web Worker' && message.logLevel === Ci.nsIConsoleMessage.error) {
emitEvent(this.events.onErrorFromWorker, errorWindow, message.message, '' + message.stack);
return;
}
const executionContext = this._windowToExecutionContext.get(errorWindow);
if (!executionContext)
return;
const typeNames = {
[Ci.nsIConsoleMessage.debug]: 'debug',
[Ci.nsIConsoleMessage.info]: 'info',
[Ci.nsIConsoleMessage.warn]: 'warn',
[Ci.nsIConsoleMessage.error]: 'error',
};
emitEvent(this.events.onConsoleMessage, {
args: [{
value: message.message,
}],
type: typeNames[message.logLevel],
executionContextId: executionContext.id(),
location: {
lineNumber: message.lineNumber,
columnNumber: message.columnNumber,
url: message.sourceName,
},
});
},
};
Services.console.registerListener(consoleServiceListener);
this._eventListeners.push(() => Services.console.unregisterListener(consoleServiceListener));
}
_registerConsoleObserver(Services) {
const consoleObserver = ({wrappedJSObject}, topic, data) => {
const executionContext = Array.from(this._executionContexts.values()).find(context => {
const domWindow = context._domWindow;
return domWindow && domWindow.windowUtils.currentInnerWindowID === wrappedJSObject.innerID;
});
if (!executionContext)
return;
this._onConsoleMessage(executionContext, wrappedJSObject);
};
Services.obs.addObserver(consoleObserver, "console-api-log-event");
this._eventListeners.push(() => Services.obs.removeObserver(consoleObserver, "console-api-log-event"));
}
_registerWorkerConsoleHandler() {
setConsoleEventHandler(message => {
const executionContext = Array.from(this._executionContexts.values())[0];
this._onConsoleMessage(executionContext, message);
});
this._eventListeners.push(() => setConsoleEventHandler(null));
}
_onConsoleMessage(executionContext, message) {
const type = consoleLevelToProtocolType[message.level];
if (!type)
return;
const args = message.arguments.map(arg => executionContext.rawValueToRemoteObject(arg));
emitEvent(this.events.onConsoleMessage, {
args,
type,
executionContextId: executionContext.id(),
location: {
lineNumber: message.lineNumber - 1,
columnNumber: message.columnNumber - 1,
url: message.filename,
},
});
}
dispose() {
for (const tearDown of this._eventListeners)
tearDown.call(null);
this._eventListeners = [];
}
async _awaitPromise(executionContext, obj, exceptionDetails = {}) {
if (obj.promiseState === 'fulfilled')
return {success: true, obj: obj.promiseValue};
if (obj.promiseState === 'rejected') {
const global = executionContext._global;
exceptionDetails.text = global.executeInGlobalWithBindings('e.message', {e: obj.promiseReason}).return;
exceptionDetails.stack = global.executeInGlobalWithBindings('e.stack', {e: obj.promiseReason}).return;
return {success: false, obj: null};
}
let resolve, reject;
const promise = new Promise((a, b) => {
resolve = a;
reject = b;
});
this._pendingPromises.set(obj.promiseID, {resolve, reject, executionContext, exceptionDetails});
if (this._pendingPromises.size === 1)
this._debugger.onPromiseSettled = this._onPromiseSettled.bind(this);
return await promise;
}
_onPromiseSettled(obj) {
const pendingPromise = this._pendingPromises.get(obj.promiseID);
if (!pendingPromise)
return;
this._pendingPromises.delete(obj.promiseID);
if (!this._pendingPromises.size)
this._debugger.onPromiseSettled = undefined;
if (obj.promiseState === 'fulfilled') {
pendingPromise.resolve({success: true, obj: obj.promiseValue});
return;
};
const global = pendingPromise.executionContext._global;
pendingPromise.exceptionDetails.text = global.executeInGlobalWithBindings('e.message', {e: obj.promiseReason}).return;
pendingPromise.exceptionDetails.stack = global.executeInGlobalWithBindings('e.stack', {e: obj.promiseReason}).return;
pendingPromise.resolve({success: false, obj: null});
}
createExecutionContext(domWindow, contextGlobal, auxData) {
// Note: domWindow is null for workers.
const context = new ExecutionContext(this, domWindow, contextGlobal, this._debugger.addDebuggee(contextGlobal), auxData);
this._executionContexts.set(context._id, context);
if (domWindow)
this._windowToExecutionContext.set(domWindow, context);
emitEvent(this.events.onExecutionContextCreated, context);
return context;
}
findExecutionContext(executionContextId) {
const executionContext = this._executionContexts.get(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
return executionContext;
}
destroyExecutionContext(destroyedContext) {
for (const [promiseID, {reject, executionContext}] of this._pendingPromises) {
if (executionContext === destroyedContext) {
reject(new Error('Execution context was destroyed!'));
this._pendingPromises.delete(promiseID);
}
}
if (!this._pendingPromises.size)
this._debugger.onPromiseSettled = undefined;
this._debugger.removeDebuggee(destroyedContext._contextGlobal);
this._executionContexts.delete(destroyedContext._id);
if (destroyedContext._domWindow)
this._windowToExecutionContext.delete(destroyedContext._domWindow);
emitEvent(this.events.onExecutionContextDestroyed, destroyedContext);
}
}
class ExecutionContext {
constructor(runtime, domWindow, contextGlobal, global, auxData) {
this._runtime = runtime;
this._domWindow = domWindow;
this._contextGlobal = contextGlobal;
this._global = global;
this._remoteObjects = new Map();
this._id = generateId();
this._auxData = auxData;
this._jsonStringifyObject = this._global.executeInGlobal(`((stringify, dateProto, object) => {
const oldToJson = dateProto.toJSON;
dateProto.toJSON = undefined;
let hasSymbol = false;
const result = stringify(object, (key, value) => {
if (typeof value === 'symbol')
hasSymbol = true;
return value;
});
dateProto.toJSON = oldToJson;
return hasSymbol ? undefined : result;
}).bind(null, JSON.stringify.bind(JSON), Date.prototype)`).return;
}
id() {
return this._id;
}
auxData() {
return this._auxData;
}
async evaluateScript(script, exceptionDetails = {}) {
const userInputHelper = this._domWindow ? this._domWindow.windowUtils.setHandlingUserInput(true) : null;
if (this._domWindow && this._domWindow.document)
this._domWindow.document.notifyUserGestureActivation();
let {success, obj} = this._getResult(this._global.executeInGlobal(script), exceptionDetails);
userInputHelper && userInputHelper.destruct();
if (!success)
return null;
if (obj && obj.isPromise) {
const awaitResult = await this._runtime._awaitPromise(this, obj, exceptionDetails);
if (!awaitResult.success)
return null;
obj = awaitResult.obj;
}
return this._createRemoteObject(obj);
}
async evaluateFunction(functionText, args, exceptionDetails = {}) {
const funEvaluation = this._getResult(this._global.executeInGlobal('(' + functionText + ')'), exceptionDetails);
if (!funEvaluation.success)
return null;
if (!funEvaluation.obj.callable)
throw new Error('functionText does not evaluate to a function!');
args = args.map(arg => {
if (arg.objectId) {
if (!this._remoteObjects.has(arg.objectId))
throw new Error('Cannot find object with id = ' + arg.objectId);
return this._remoteObjects.get(arg.objectId);
}
switch (arg.unserializableValue) {
case 'Infinity': return Infinity;
case '-Infinity': return -Infinity;
case '-0': return -0;
case 'NaN': return NaN;
default: return this._toDebugger(arg.value);
}
});
const userInputHelper = this._domWindow ? this._domWindow.windowUtils.setHandlingUserInput(true) : null;
if (this._domWindow && this._domWindow.document)
this._domWindow.document.notifyUserGestureActivation();
let {success, obj} = this._getResult(funEvaluation.obj.apply(null, args), exceptionDetails);
userInputHelper && userInputHelper.destruct();
if (!success)
return null;
if (obj && obj.isPromise) {
const awaitResult = await this._runtime._awaitPromise(this, obj, exceptionDetails);
if (!awaitResult.success)
return null;
obj = awaitResult.obj;
}
return this._createRemoteObject(obj);
}
unsafeObject(objectId) {
if (!this._remoteObjects.has(objectId))
return;
return { object: this._remoteObjects.get(objectId).unsafeDereference() };
}
rawValueToRemoteObject(rawValue) {
const debuggerObj = this._global.makeDebuggeeValue(rawValue);
return this._createRemoteObject(debuggerObj);
}
_instanceOf(debuggerObj, rawObj, className) {
if (this._domWindow)
return rawObj instanceof this._domWindow[className];
return this._global.executeInGlobalWithBindings('o instanceof this[className]', {o: debuggerObj, className: this._global.makeDebuggeeValue(className)}).return;
}
_createRemoteObject(debuggerObj) {
if (debuggerObj instanceof Debugger.Object) {
const objectId = generateId();
this._remoteObjects.set(objectId, debuggerObj);
const rawObj = debuggerObj.unsafeDereference();
const type = typeof rawObj;
let subtype = undefined;
if (debuggerObj.isProxy)
subtype = 'proxy';
else if (Array.isArray(rawObj))
subtype = 'array';
else if (Object.is(rawObj, null))
subtype = 'null';
else if (this._instanceOf(debuggerObj, rawObj, 'Node'))
subtype = 'node';
else if (this._instanceOf(debuggerObj, rawObj, 'RegExp'))
subtype = 'regexp';
else if (this._instanceOf(debuggerObj, rawObj, 'Date'))
subtype = 'date';
else if (this._instanceOf(debuggerObj, rawObj, 'Map'))
subtype = 'map';
else if (this._instanceOf(debuggerObj, rawObj, 'Set'))
subtype = 'set';
else if (this._instanceOf(debuggerObj, rawObj, 'WeakMap'))
subtype = 'weakmap';
else if (this._instanceOf(debuggerObj, rawObj, 'WeakSet'))
subtype = 'weakset';
else if (this._instanceOf(debuggerObj, rawObj, 'Error'))
subtype = 'error';
else if (this._instanceOf(debuggerObj, rawObj, 'Promise'))
subtype = 'promise';
else if ((this._instanceOf(debuggerObj, rawObj, 'Int8Array')) || (this._instanceOf(debuggerObj, rawObj, 'Uint8Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Uint8ClampedArray')) || (this._instanceOf(debuggerObj, rawObj, 'Int16Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Uint16Array')) || (this._instanceOf(debuggerObj, rawObj, 'Int32Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Uint32Array')) || (this._instanceOf(debuggerObj, rawObj, 'Float32Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Float64Array'))) {
subtype = 'typedarray';
}
return {objectId, type, subtype};
}
if (typeof debuggerObj === 'symbol') {
const objectId = generateId();
this._remoteObjects.set(objectId, debuggerObj);
return {objectId, type: 'symbol'};
}
let unserializableValue = undefined;
if (Object.is(debuggerObj, NaN))
unserializableValue = 'NaN';
else if (Object.is(debuggerObj, -0))
unserializableValue = '-0';
else if (Object.is(debuggerObj, Infinity))
unserializableValue = 'Infinity';
else if (Object.is(debuggerObj, -Infinity))
unserializableValue = '-Infinity';
return unserializableValue ? {unserializableValue} : {value: debuggerObj};
}
ensureSerializedToValue(protocolObject) {
if (!protocolObject.objectId)
return protocolObject;
const obj = this._remoteObjects.get(protocolObject.objectId);
this._remoteObjects.delete(protocolObject.objectId);
return {value: this._serialize(obj)};
}
_toDebugger(obj) {
if (typeof obj !== 'object')
return obj;
if (obj === null)
return obj;
const properties = {};
for (let [key, value] of Object.entries(obj)) {
properties[key] = {
configurable: true,
writable: true,
enumerable: true,
value: this._toDebugger(value),
};
}
const baseObject = Array.isArray(obj) ? '([])' : '({})';
const debuggerObj = this._global.executeInGlobal(baseObject).return;
debuggerObj.defineProperties(properties);
return debuggerObj;
}
_serialize(obj) {
const result = this._global.executeInGlobalWithBindings('stringify(e)', {e: obj, stringify: this._jsonStringifyObject});
if (result.throw)
throw new Error('Object is not serializable');
return result.return === undefined ? undefined : JSON.parse(result.return);
}
disposeObject(objectId) {
this._remoteObjects.delete(objectId);
}
getObjectProperties(objectId) {
if (!this._remoteObjects.has(objectId))
throw new Error('Cannot find object with id = ' + arg.objectId);
const result = [];
for (let obj = this._remoteObjects.get(objectId); obj; obj = obj.proto) {
for (const propertyName of obj.getOwnPropertyNames()) {
const descriptor = obj.getOwnPropertyDescriptor(propertyName);
if (!descriptor.enumerable)
continue;
result.push({
name: propertyName,
value: this._createRemoteObject(descriptor.value),
});
}
}
return result;
}
_getResult(completionValue, exceptionDetails = {}) {
if (!completionValue) {
exceptionDetails.text = 'Evaluation terminated!';
exceptionDetails.stack = '';
return {success: false, obj: null};
}
if (completionValue.throw) {
if (this._global.executeInGlobalWithBindings('e instanceof Error', {e: completionValue.throw}).return) {
exceptionDetails.text = this._global.executeInGlobalWithBindings('e.message', {e: completionValue.throw}).return;
exceptionDetails.stack = this._global.executeInGlobalWithBindings('e.stack', {e: completionValue.throw}).return;
} else {
exceptionDetails.value = this._serialize(completionValue.throw);
}
return {success: false, obj: null};
}
return {success: true, obj: completionValue.return};
}
}
const listenersSymbol = Symbol('listeners');
function createEvent() {
const listeners = new Set();
const subscribeFunction = listener => {
listeners.add(listener);
return () => listeners.delete(listener);
}
subscribeFunction[listenersSymbol] = listeners;
return subscribeFunction;
}
function emitEvent(event, ...args) {
let listeners = event[listenersSymbol];
if (!listeners || !listeners.size)
return;
listeners = new Set(listeners);
for (const listener of listeners)
listener.call(null, ...args);
}
var EXPORTED_SYMBOLS = ['Runtime'];
this.Runtime = Runtime;
| browser_patches/firefox/juggler/content/Runtime.js | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.0047723702155053616,
0.0006382199353538454,
0.00016658809909131378,
0.00017289734387304634,
0.0011190579971298575
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" executablePath(): string {\n",
" if (!this._executablePath)\n",
" throw new Error('Browser is not supported on current platform');\n",
" return this._executablePath;\n",
" }\n",
"\n",
" name(): string {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/server/browserType.ts",
"type": "replace",
"edit_start_line_idx": 56
} | ---
name: Feature request
about: Request new features to be added
title: "[Feature]"
labels: ''
assignees: ''
---
Let us know what functionality you'd like to see in Playwright and what is your use case.
Do you think others might benefit from this as well?
| .github/ISSUE_TEMPLATE/feature_request.md | 0 | https://github.com/microsoft/playwright/commit/f1016c1fc15814c8dc22876a82b29acb59ddcf4b | [
0.00017251413373742253,
0.00017093514907173812,
0.00016935616440605372,
0.00017093514907173812,
0.000001578984665684402
] |
{
"id": 0,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyDown={onKeyDownSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyDown(document.querySelector('input'), {\n",
" key: 'Enter',\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyDown(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 935
} | // @ts-check
import * as React from 'react';
import { expect } from 'chai';
import { spy, stub } from 'sinon';
import {
getClasses,
createMount,
describeConformance,
act,
createClientRender,
fireEvent,
screen,
focusVisible,
simulatePointerDevice,
programmaticFocusTriggersFocusVisible,
} from 'test/utils';
import PropTypes from 'prop-types';
import ButtonBase from './ButtonBase';
describe('<ButtonBase />', () => {
const render = createClientRender();
/**
* @type {ReturnType<typeof createMount>}
*/
const mount = createMount();
/**
* @type {Record<string, string>}
*/
let classes;
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14156632/
let canFireDragEvents = true;
before(() => {
classes = getClasses(<ButtonBase />);
// browser testing config
try {
const EventConstructor = window.DragEvent || window.Event;
// eslint-disable-next-line no-new
new EventConstructor('');
} catch (err) {
canFireDragEvents = false;
}
});
describeConformance(<ButtonBase />, () => ({
classes,
inheritComponent: 'button',
mount,
refInstanceof: window.HTMLButtonElement,
testComponentPropWith: 'a',
}));
describe('root node', () => {
it('should change the button type', () => {
const { getByText } = render(<ButtonBase type="submit">Hello</ButtonBase>);
expect(getByText('Hello')).to.have.attribute('type', 'submit');
});
it('should change the button component and add accessibility requirements', () => {
const { getByRole } = render(
<ButtonBase component="span" role="checkbox" aria-checked={false} />,
);
const checkbox = getByRole('checkbox');
expect(checkbox).to.have.property('nodeName', 'SPAN');
expect(checkbox).attribute('tabIndex').to.equal('0');
});
it('should not apply role="button" if type="button"', () => {
const { getByText } = render(<ButtonBase type="button">Hello</ButtonBase>);
expect(getByText('Hello')).to.not.have.attribute('role');
});
it('should change the button type to span and set role="button"', () => {
const { getByRole } = render(<ButtonBase component="span">Hello</ButtonBase>);
const button = getByRole('button');
expect(button).to.have.property('nodeName', 'SPAN');
expect(button).to.not.have.attribute('type');
});
it('should automatically change the button to an anchor element when href is provided', () => {
const { container } = render(<ButtonBase href="https://google.com">Hello</ButtonBase>);
const button = container.firstChild;
expect(button).to.have.property('nodeName', 'A');
expect(button).not.to.have.attribute('role');
expect(button).not.to.have.attribute('type');
expect(button).to.have.attribute('href', 'https://google.com');
});
it('applies role="button" when an anchor is used without href', () => {
const { getByRole } = render(<ButtonBase component="a">Hello</ButtonBase>);
const button = getByRole('button');
expect(button).to.have.property('nodeName', 'A');
expect(button).not.to.have.attribute('type');
});
it('should not use an anchor element if explicit component and href is passed', () => {
const { getByRole } = render(
// @ts-ignore
<ButtonBase component="span" href="https://google.com">
Hello
</ButtonBase>,
);
const button = getByRole('button');
expect(button).to.have.property('nodeName', 'SPAN');
expect(button).to.have.attribute('href', 'https://google.com');
});
});
describe('event callbacks', () => {
it('should fire event callbacks', () => {
const onClick = spy();
const onBlur = spy();
const onFocus = spy();
const onKeyUp = spy();
const onKeyDown = spy();
const onMouseDown = spy();
const onMouseLeave = spy();
const onMouseUp = spy();
const onDragEnd = spy();
const onTouchStart = spy();
const onTouchEnd = spy();
const { getByText } = render(
<ButtonBase
onClick={onClick}
onBlur={onBlur}
onFocus={onFocus}
onKeyUp={onKeyUp}
onKeyDown={onKeyDown}
onMouseDown={onMouseDown}
onMouseLeave={onMouseLeave}
onMouseUp={onMouseUp}
onDragEnd={onDragEnd}
onTouchEnd={onTouchEnd}
onTouchStart={onTouchStart}
>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
// only run in supported browsers
if (typeof Touch !== 'undefined') {
const touch = new Touch({ identifier: 0, target: button, clientX: 0, clientY: 0 });
fireEvent.touchStart(button, { touches: [touch] });
expect(onTouchStart.callCount).to.equal(1);
fireEvent.touchEnd(button, { touches: [touch] });
expect(onTouchEnd.callCount).to.equal(1);
}
if (canFireDragEvents) {
fireEvent.dragEnd(button);
expect(onDragEnd.callCount).to.equal(1);
}
fireEvent.mouseDown(button);
expect(onMouseDown.callCount).to.equal(1);
fireEvent.mouseUp(button);
expect(onMouseUp.callCount).to.equal(1);
fireEvent.click(button);
expect(onClick.callCount).to.equal(1);
button.focus();
expect(onFocus.callCount).to.equal(1);
fireEvent.keyDown(button);
expect(onKeyDown.callCount).to.equal(1);
fireEvent.keyUp(button);
expect(onKeyUp.callCount).to.equal(1);
button.blur();
expect(onBlur.callCount).to.equal(1);
fireEvent.mouseLeave(button);
expect(onMouseLeave.callCount).to.equal(1);
});
});
describe('ripple', () => {
describe('interactions', () => {
it('should not have a focus ripple by default', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(0);
});
it('should start the ripple when the mouse is pressed', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(0);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should stop the ripple when the mouse is released', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.mouseUp(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(0);
});
it('should start the ripple when the mouse is pressed 2', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.mouseUp(button);
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should stop the ripple when the button blurs', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
button.blur();
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(0);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should restart the ripple when the mouse is pressed again', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(0);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
fireEvent.mouseUp(button);
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should stop the ripple when the mouse leaves', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.mouseLeave(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(0);
});
it('should stop the ripple when dragging has finished', function test() {
if (!canFireDragEvents) {
this.skip();
}
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.dragLeave(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(0);
});
it('should not crash when changes enableRipple from false to true', () => {
function App() {
/** @type {React.MutableRefObject<import('./ButtonBase').ButtonBaseActions | null>} */
const buttonRef = React.useRef(null);
const [enableRipple, setRipple] = React.useState(false);
React.useEffect(() => {
if (buttonRef.current) {
buttonRef.current.focusVisible();
} else {
throw new Error('buttonRef.current must be available');
}
}, []);
return (
<div>
<button
type="button"
data-testid="trigger"
onClick={() => {
setRipple(true);
}}
>
Trigger crash
</button>
<ButtonBase
autoFocus
action={buttonRef}
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
focusRipple
disableRipple={!enableRipple}
>
the button
</ButtonBase>
</div>
);
}
const { container, getByTestId } = render(<App />);
fireEvent.click(getByTestId('trigger'));
expect(container.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(1);
});
});
});
describe('prop: centerRipple', () => {
it('centers the TouchRipple', () => {
const { container, getByRole } = render(
<ButtonBase
centerRipple
TouchRippleProps={{ classes: { root: 'touch-ripple', ripple: 'touch-ripple-ripple' } }}
>
Hello
</ButtonBase>,
);
// @ts-ignore
stub(container.querySelector('.touch-ripple'), 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 100,
bottom: 10,
left: 20,
top: 20,
}));
fireEvent.mouseDown(getByRole('button'), { clientX: 10, clientY: 10 });
const rippleRipple = container.querySelector('.touch-ripple-ripple');
expect(rippleRipple).to.not.equal(null);
// @ts-ignore
const rippleSyle = window.getComputedStyle(rippleRipple);
expect(rippleSyle).to.have.property('height', '101px');
expect(rippleSyle).to.have.property('width', '101px');
});
it('is disabled by default', () => {
const { container, getByRole } = render(
<ButtonBase
TouchRippleProps={{ classes: { root: 'touch-ripple', ripple: 'touch-ripple-ripple' } }}
>
Hello
</ButtonBase>,
);
// @ts-ignore
stub(container.querySelector('.touch-ripple'), 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 100,
bottom: 10,
left: 20,
top: 20,
}));
fireEvent.mouseDown(getByRole('button'), { clientX: 10, clientY: 10 });
const rippleRipple = container.querySelector('.touch-ripple-ripple');
expect(rippleRipple).to.not.equal(null);
// @ts-ignore
const rippleSyle = window.getComputedStyle(rippleRipple);
expect(rippleSyle).to.not.have.property('height', '101px');
expect(rippleSyle).to.not.have.property('width', '101px');
});
});
describe('focusRipple', () => {
before(function beforeHook() {
if (/Version\/10\.\d+\.\d+ Safari/.test(window.navigator.userAgent)) {
// browserstack quirk
this.skip();
}
});
it('should pulsate the ripple when focusVisible', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(1);
});
it('should not stop the ripple when the mouse leaves', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
fireEvent.mouseLeave(button);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(1);
});
it('should stop pulsate and start a ripple when the space button is pressed', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
childLeaving: 'child-leaving',
ripplePulsate: 'ripple-pulsate',
rippleVisible: 'rippled-visible',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
fireEvent.keyDown(button, { key: ' ' });
expect(button.querySelectorAll('.ripple-pulsate .child-leaving')).to.have.lengthOf(1);
expect(button.querySelectorAll('.ripple-visible')).to.have.lengthOf(0);
});
it('should stop and re-pulsate when space bar is released', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
childLeaving: 'child-leaving',
ripplePulsate: 'ripple-pulsate',
rippleVisible: 'ripple-visible',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
fireEvent.keyDown(button, { key: ' ' });
fireEvent.keyUp(button, { key: ' ' });
expect(button.querySelectorAll('.ripple-pulsate .child-leaving')).to.have.lengthOf(1);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(2);
expect(button.querySelectorAll('.ripple-visible')).to.have.lengthOf(3);
});
it('should stop on blur and set focusVisible to false', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
childLeaving: 'child-leaving',
rippleVisible: 'ripple-visible',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
act(() => {
button.blur();
});
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
});
});
describe('prop: disabled', () => {
it('should have a negative tabIndex', () => {
const { getByText } = render(<ButtonBase disabled>Hello</ButtonBase>);
expect(getByText('Hello')).to.have.property('tabIndex', -1);
});
it('should forward it to native buttons', () => {
const { getByText } = render(
<ButtonBase disabled component="button">
Hello
</ButtonBase>,
);
expect(getByText('Hello')).to.have.property('disabled', true);
});
it('should reset the focused state', () => {
const { getByText, setProps } = render(<ButtonBase>Hello</ButtonBase>);
const button = getByText('Hello');
simulatePointerDevice();
focusVisible(button);
expect(button).to.have.class(classes.focusVisible);
setProps({ disabled: true });
expect(button).not.to.have.class(classes.focusVisible);
});
it('should use aria attributes for other components', () => {
const { getByRole } = render(
<ButtonBase component="span" disabled>
Hello
</ButtonBase>,
);
const button = getByRole('button');
expect(button).not.to.have.attribute('disabled');
expect(button).to.have.attribute('aria-disabled', 'true');
});
});
describe('prop: component', () => {
it('should allow to use a link component', () => {
/**
* @type {React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLDivElement>>}
*/
const Link = React.forwardRef((props, ref) => (
<div data-testid="link" ref={ref} {...props} />
));
const { getByTestId } = render(<ButtonBase component={Link}>Hello</ButtonBase>);
expect(getByTestId('link')).to.have.attribute('role', 'button');
});
});
describe('event: focus', () => {
it('when disabled should be called onFocus', () => {
const onFocusSpy = spy();
const { getByRole } = render(
<ButtonBase component="div" disabled onFocus={onFocusSpy}>
Hello
</ButtonBase>,
);
act(() => {
getByRole('button').focus();
});
expect(onFocusSpy.callCount).to.equal(1);
});
it('has a focus-visible polyfill', () => {
const { getByText } = render(<ButtonBase>Hello</ButtonBase>);
const button = getByText('Hello');
simulatePointerDevice();
expect(button).not.to.have.class(classes.focusVisible);
button.focus();
if (programmaticFocusTriggersFocusVisible()) {
expect(button).to.have.class(classes.focusVisible);
} else {
expect(button).not.to.have.class(classes.focusVisible);
}
focusVisible(button);
expect(button).to.have.class(classes.focusVisible);
});
it('removes foucs-visible if focus is re-targetted', () => {
/**
* @type {string[]}
*/
const eventLog = [];
function Test() {
/**
* @type {React.Ref<HTMLButtonElement>}
*/
const focusRetargetRef = React.useRef(null);
return (
<div
onFocus={() => {
const { current: focusRetarget } = focusRetargetRef;
if (focusRetarget === null) {
throw new TypeError('Nothing to focous. Test cannot work.');
}
focusRetarget.focus();
}}
>
<button ref={focusRetargetRef} type="button">
you cannot escape me
</button>
<ButtonBase
onBlur={() => eventLog.push('blur')}
onFocus={() => eventLog.push('focus')}
onFocusVisible={() => eventLog.push('focus-visible')}
>
Hello
</ButtonBase>
</div>
);
}
const { getByText } = render(<Test />);
const buttonBase = getByText('Hello');
const focusRetarget = getByText('you cannot escape me');
simulatePointerDevice();
focusVisible(buttonBase);
expect(focusRetarget).toHaveFocus();
expect(eventLog).to.deep.equal(['focus-visible', 'focus', 'blur']);
expect(buttonBase).not.to.have.class(classes.focusVisible);
});
it('onFocusVisibleHandler() should propagate call to onFocusVisible prop', () => {
const onFocusVisibleSpy = spy();
const { getByRole } = render(
<ButtonBase component="span" onFocusVisible={onFocusVisibleSpy}>
Hello
</ButtonBase>,
);
simulatePointerDevice();
focusVisible(getByRole('button'));
expect(onFocusVisibleSpy.calledOnce).to.equal(true);
expect(onFocusVisibleSpy.firstCall.args).to.have.lengthOf(1);
});
it('can be autoFocused', () => {
// as of [email protected] autoFocus causes focus to be emitted before refs
// so we need to check if we're resilient against it
const { getByText } = render(<ButtonBase autoFocus>Hello</ButtonBase>);
expect(getByText('Hello')).toHaveFocus();
});
});
describe('event: keydown', () => {
it('ripples on repeated keydowns', () => {
const { container, getByText } = render(
<ButtonBase focusRipple TouchRippleProps={{ classes: { rippleVisible: 'ripple-visible' } }}>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
act(() => {
button.focus();
fireEvent.keyDown(button, { key: 'Enter' });
});
expect(container.querySelectorAll('.ripple-visible')).to.have.lengthOf(1);
// technically the second keydown should be fire with repeat: true
// but that isn't implemented in IE11 so we shouldn't mock it here either
fireEvent.keyDown(button, { key: 'Enter' });
expect(container.querySelectorAll('.ripple-visible')).to.have.lengthOf(1);
});
describe('prop: onKeyDown', () => {
it('call it when keydown events are dispatched', () => {
const onKeyDownSpy = spy();
const { getByText } = render(
<ButtonBase autoFocus onKeyDown={onKeyDownSpy}>
Hello
</ButtonBase>,
);
fireEvent.keyDown(getByText('Hello'));
expect(onKeyDownSpy.callCount).to.equal(1);
});
});
describe('prop: disableTouchRipple', () => {
it('creates no ripples on click', () => {
const { getByText } = render(
<ButtonBase
disableTouchRipple
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
},
}}
>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
fireEvent.click(button);
expect(button).not.to.have.class('ripple-visible');
});
});
describe('prop: disableRipple', () => {
it('removes the TouchRipple', () => {
const { getByText } = render(
<ButtonBase disableRipple focusRipple TouchRippleProps={{ className: 'touch-ripple' }}>
Hello
</ButtonBase>,
);
expect(getByText('Hello').querySelector('.touch-ripple')).to.equal(null);
});
});
describe('keyboard accessibility for non interactive elements', () => {
it('does not call onClick when a spacebar is pressed on the element but prevents the default', () => {
const onKeyDown = spy((event) => event.defaultPrevented);
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} onKeyDown={onKeyDown} component="div">
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyDown(button, {
key: ' ',
});
});
expect(onClickSpy.callCount).to.equal(0);
// defaultPrevented?
expect(onKeyDown.returnValues[0]).to.equal(true);
});
it('does call onClick when a spacebar is released on the element', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} component="div">
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyUp(button, {
key: ' ',
});
});
expect(onClickSpy.callCount).to.equal(1);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(false);
});
it('does not call onClick when a spacebar is released and the default is prevented', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase
onClick={onClickSpy}
onKeyUp={
/**
* @param {React.SyntheticEvent} event
*/
(event) => event.preventDefault()
}
component="div"
>
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyUp(button, {
key: ' ',
});
});
expect(onClickSpy.callCount).to.equal(0);
});
it('calls onClick when Enter is pressed on the element', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} component="div">
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyDown(button, {
key: 'Enter',
});
});
expect(onClickSpy.calledOnce).to.equal(true);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(true);
});
it('does not call onClick if Enter was pressed on a child', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const onKeyDownSpy = spy();
render(
<ButtonBase onClick={onClickSpy} onKeyDown={onKeyDownSpy} component="div">
<input autoFocus type="text" />
</ButtonBase>,
);
fireEvent.keyDown(document.querySelector('input'), {
key: 'Enter',
});
expect(onKeyDownSpy.callCount).to.equal(1);
expect(onClickSpy.callCount).to.equal(0);
});
it('does not call onClick if Space was released on a child', () => {
const onClickSpy = spy();
const onKeyUpSpy = spy();
render(
<ButtonBase onClick={onClickSpy} onKeyUp={onKeyUpSpy} component="div">
<input autoFocus type="text" />
</ButtonBase>,
);
fireEvent.keyUp(document.querySelector('input'), {
key: ' ',
});
expect(onKeyUpSpy.callCount).to.equal(1);
expect(onClickSpy.callCount).to.equal(0);
});
it('prevents default with an anchor and empty href', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase component="a" onClick={onClickSpy}>
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyDown(button, { key: 'Enter' });
});
expect(onClickSpy.calledOnce).to.equal(true);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(true);
});
it('should ignore anchors with href', () => {
const onClick = spy();
const onKeyDown = spy((event) => event.defaultPrevented);
const { getByText } = render(
<ButtonBase component="a" href="href" onClick={onClick} onKeyDown={onKeyDown}>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
act(() => {
button.focus();
fireEvent.keyDown(button, {
key: 'Enter',
});
});
expect(onClick.calledOnce).to.equal(false);
// defaultPrevented
expect(onKeyDown.returnValues[0]).to.equal(false);
});
});
});
describe('prop: action', () => {
it('should be able to focus visible the button', () => {
/**
* @type {React.RefObject<import('./ButtonBase').ButtonBaseActions>}
*/
const buttonActionsRef = React.createRef();
const { getByText } = render(
<ButtonBase action={buttonActionsRef} focusVisibleClassName="focusVisible">
Hello
</ButtonBase>,
);
// @ts-ignore
expect(typeof buttonActionsRef.current.focusVisible).to.equal('function');
act(() => {
// @ts-ignore
buttonActionsRef.current.focusVisible();
});
expect(getByText('Hello')).toHaveFocus();
expect(getByText('Hello')).to.match('.focusVisible');
});
});
describe('warnings', () => {
beforeEach(() => {
PropTypes.resetWarningCache();
});
it('warns on invalid `component` prop: ref forward', () => {
// Only run the test on node. On the browser the thrown error is not caught
if (!/jsdom/.test(window.navigator.userAgent)) {
return;
}
/**
*
* @param {import('react').HTMLAttributes<HTMLButtonElement>} props
*/
function Component(props) {
return <button type="button" {...props} />;
}
expect(() => {
PropTypes.checkPropTypes(
// @ts-ignore `Naked` is internal
ButtonBase.Naked.propTypes,
{ classes: {}, component: Component },
'prop',
'MockedName',
);
}).toErrorDev(
'Invalid prop `component` supplied to `MockedName`. Expected an element type that can hold a ref',
);
});
it('warns on invalid `component` prop: prop forward', () => {
const Component = React.forwardRef((props, ref) => (
<button type="button" ref={ref} {...props}>
Hello
</button>
));
// cant match the error message here because flakiness with mocha watchmode
expect(() => {
render(<ButtonBase component={Component} />);
}).toErrorDev('Please make sure the children prop is rendered in this custom component.');
});
});
describe('prop: type', () => {
it('is `button` by default', () => {
render(<ButtonBase />);
expect(screen.getByRole('button')).to.have.property('type', 'button');
});
it('can be changed to other button types', () => {
render(<ButtonBase type="submit" />);
expect(screen.getByRole('button')).to.have.property('type', 'submit');
});
it('allows non-standard values', () => {
// @ts-expect-error `@types/react` only lists standard values
render(<ButtonBase type="fictional-type" />);
expect(screen.getByRole('button')).to.have.attribute('type', 'fictional-type');
// By spec non-supported types result in the default type for `<button>` which is `submit`
expect(screen.getByRole('button')).to.have.property('type', 'submit');
});
it('is forwarded to anchor components', () => {
render(<ButtonBase component="a" href="some-recording.ogg" download type="audio/ogg" />);
expect(screen.getByRole('link')).to.have.attribute('type', 'audio/ogg');
expect(screen.getByRole('link')).to.have.property('type', 'audio/ogg');
});
it('is forwarded to custom components', () => {
/**
* @type {React.ForwardRefExoticComponent<React.ButtonHTMLAttributes<HTMLButtonElement>>}
*/
const CustomButton = React.forwardRef((props, ref) => <button ref={ref} {...props} />);
render(<ButtonBase component={CustomButton} type="reset" />);
expect(screen.getByRole('button')).to.have.property('type', 'reset');
});
});
});
| packages/material-ui/src/ButtonBase/ButtonBase.test.js | 1 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.983893632888794,
0.010529302060604095,
0.0001645468728384003,
0.00048046166193671525,
0.09242793917655945
] |
{
"id": 0,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyDown={onKeyDownSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyDown(document.querySelector('input'), {\n",
" key: 'Enter',\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyDown(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 935
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M11 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0-6c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zM5 18c.2-.63 2.57-1.68 4.96-1.94l2.04-2c-.39-.04-.68-.06-1-.06-2.67 0-8 1.34-8 4v2h9l-2-2H5zm15.6-5.5l-5.13 5.17-2.07-2.08L12 17l3.47 3.5L22 13.91z" />
, 'HowToRegOutlined');
| packages/material-ui-icons/src/HowToRegOutlined.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00017598990234546363,
0.00017598990234546363,
0.00017598990234546363,
0.00017598990234546363,
0
] |
{
"id": 0,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyDown={onKeyDownSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyDown(document.querySelector('input'), {\n",
" key: 'Enter',\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyDown(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 935
} | import * as React from 'react';
import { ButtonBaseTypeMap, ExtendButtonBase, ExtendButtonBaseTypeMap } from '../ButtonBase';
import { OverrideProps } from '../OverridableComponent';
export type BottomNavigationActionTypeMap<
P,
D extends React.ElementType
> = ExtendButtonBaseTypeMap<{
props: P & {
/**
* This prop isn't supported.
* Use the `component` prop if you need to change the children structure.
*/
children?: React.ReactNode;
/**
* Override or extend the styles applied to the component.
*/
classes?: {
/** Styles applied to the root element. */
root?: string;
/** Pseudo-class applied to the root element if selected. */
selected?: string;
/** Pseudo-class applied to the root element if `showLabel={false}` and not selected. */
iconOnly?: string;
/** Styles applied to the span element that wraps the icon and label. */
wrapper?: string;
/** Styles applied to the label's span element. */
label?: string;
};
/**
* The icon element.
*/
icon?: React.ReactNode;
/**
* The label element.
*/
label?: React.ReactNode;
/**
* If `true`, the `BottomNavigationAction` will show its label.
* By default, only the selected `BottomNavigationAction`
* inside `BottomNavigation` will show its label.
*
* The prop defaults to the value (`false`) inherited from the parent BottomNavigation component.
*/
showLabel?: boolean;
/**
* You can provide your own value. Otherwise, we fallback to the child position index.
*/
value?: any;
};
defaultComponent: D;
}>;
/**
*
* Demos:
*
* - [Bottom Navigation](https://material-ui.com/components/bottom-navigation/)
*
* API:
*
* - [BottomNavigationAction API](https://material-ui.com/api/bottom-navigation-action/)
* - inherits [ButtonBase API](https://material-ui.com/api/button-base/)
*/
declare const BottomNavigationAction: ExtendButtonBase<BottomNavigationActionTypeMap<
{},
ButtonBaseTypeMap['defaultComponent']
>>;
export type BottomNavigationActionClassKey = keyof NonNullable<
BottomNavigationActionProps['classes']
>;
export type BottomNavigationActionProps<
D extends React.ElementType = ButtonBaseTypeMap['defaultComponent'],
P = {}
> = OverrideProps<BottomNavigationActionTypeMap<P, D>, D>;
export default BottomNavigationAction;
| packages/material-ui/src/BottomNavigationAction/BottomNavigationAction.d.ts | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00023952034825924784,
0.00017934315837919712,
0.000165332923643291,
0.00017152680084109306,
0.000023250591766554862
] |
{
"id": 0,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyDown={onKeyDownSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyDown(document.querySelector('input'), {\n",
" key: 'Enter',\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyDown(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 935
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z" />
, 'BatteryStd');
| packages/material-ui-icons/src/BatteryStd.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00017547013703733683,
0.00017547013703733683,
0.00017547013703733683,
0.00017547013703733683,
0
] |
{
"id": 1,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyUp={onKeyUpSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyUp(document.querySelector('input'), {\n",
" key: ' ',\n",
" });\n",
"\n",
" expect(onKeyUpSpy.callCount).to.equal(1);\n",
" expect(onClickSpy.callCount).to.equal(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyUp(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 952
} | /* eslint-env mocha */
import React from 'react';
import PropTypes from 'prop-types';
import {
act,
buildQueries,
cleanup,
fireEvent as rtlFireEvent,
queries,
render as testingLibraryRender,
prettyDOM,
within,
} from '@testing-library/react/pure';
// holes are *All* selectors which aren't necessary for id selectors
const [queryDescriptionOf, , getDescriptionOf, , findDescriptionOf] = buildQueries(
function queryAllDescriptionsOf(container, element) {
return container.querySelectorAll(`#${element.getAttribute('aria-describedby')}`);
},
function getMultipleError() {
return `Found multiple descriptions. An element should be described by a unique element.`;
},
function getMissingError() {
return `Found no describing element.`;
},
);
// https://github.com/testing-library/dom-testing-library/issues/723
// hide ByLabelText queries since they only support firefox >= 56, not IE 1:
// - HTMLInputElement.prototype.labels https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/labels
function queryAllByLabelText(container, label) {
throw new Error(
`*ByLabelText() relies on features that are not available in older browsers. Prefer \`*ByRole(someRole, { name: '${label}' })\` `,
);
}
const [
queryByLabelText,
getAllByLabelText,
getByLabelText,
findAllByLabelText,
findByLabelText,
] = buildQueries(
queryAllByLabelText,
function getMultipleError() {
throw new Error('not implemented');
},
function getMissingError() {
throw new Error('not implemented');
},
);
const customQueries = {
queryDescriptionOf,
getDescriptionOf,
findDescriptionOf,
queryAllByLabelText,
queryByLabelText,
getAllByLabelText,
getByLabelText,
findAllByLabelText,
findByLabelText,
};
/**
* @typedef {object} RenderOptions
* @property {HTMLElement} [options.baseElement] - https://testing-library.com/docs/react-testing-library/api#baseelement-1
* @property {HTMLElement} [options.container] - https://testing-library.com/docs/react-testing-library/api#container
* @property {boolean} [options.disableUnnmount] - if true does not cleanup before mount
* @property {boolean} [options.hydrate] - https://testing-library.com/docs/react-testing-library/api#hydrate
* @property {boolean} [options.strict] - wrap in React.StrictMode?
*/
/**
* @param {React.ReactElement} element
* @param {RenderOptions} [options]
* @returns {import('@testing-library/react').RenderResult<typeof queries & typeof customQueries> & { setProps(props: object): void}}
* TODO: type return RenderResult in setProps
*/
function clientRender(element, options = {}) {
const {
baseElement,
container,
hydrate,
strict = true,
wrapper: InnerWrapper = React.Fragment,
} = options;
const Mode = strict ? React.StrictMode : React.Fragment;
function Wrapper({ children }) {
return (
<Mode>
<InnerWrapper>{children}</InnerWrapper>
</Mode>
);
}
Wrapper.propTypes = { children: PropTypes.node };
const result = testingLibraryRender(element, {
baseElement,
container,
hydrate,
queries: { ...queries, ...customQueries },
wrapper: Wrapper,
});
/**
* convenience helper. Better than repeating all props.
*/
result.setProps = function setProps(props) {
result.rerender(React.cloneElement(element, props));
return result;
};
result.forceUpdate = function forceUpdate() {
result.rerender(
React.cloneElement(element, {
'data-force-update': String(Math.random()),
}),
);
return result;
};
return result;
}
/**
* @param {RenderOptions} globalOptions
* @returns {clientRender}
*/
export function createClientRender(globalOptions = {}) {
const { strict: globalStrict } = globalOptions;
// save stack to re-use in async afterEach
const { stack: createClientRenderStack } = new Error();
afterEach(async () => {
if (setTimeout.hasOwnProperty('clock')) {
const error = Error(
"Can't cleanup before fake timers are restored.\n" +
'Be sure to:\n' +
' 1. Restore the clock in `afterEach` instead of `after`.\n' +
' 2. Move the test hook to restore the clock before the call to `createClientRender()`.',
);
// Use saved stack otherwise the stack trace will not include the test location.
error.stack = createClientRenderStack;
throw error;
}
cleanup();
});
return function configuredClientRender(element, options = {}) {
const { strict = globalStrict, ...localOptions } = options;
return clientRender(element, { ...localOptions, strict });
};
}
const originalFireEventKeyDown = rtlFireEvent.keyDown;
const originalFireEventKeyUp = rtlFireEvent.keyUp;
const fireEvent = Object.assign(rtlFireEvent, {
keyDown(element, options = {}) {
// `element` shouldn't be `document` but we catch this later anyway
const document = element.ownerDocument || element;
const target = document.activeElement || document.body || document.documentElement;
if (target !== element) {
// see https://www.w3.org/TR/uievents/#keydown
const error = new Error(
`\`keydown\` events can only be targeted at the active element which is ${prettyDOM(
target,
undefined,
{ maxDepth: 1 },
)}`,
);
// We're only interested in the callsite of fireEvent.keyDown
error.stack = error.stack
.split('\n')
.filter((line) => !/at Function.key/.test(line))
.join('\n');
throw error;
}
originalFireEventKeyDown(element, options);
},
keyUp(element, options = {}) {
// `element` shouldn't be `document` but we catch this later anyway
const document = element.ownerDocument || element;
const target = document.activeElement || document.body || document.documentElement;
if (target !== element) {
// see https://www.w3.org/TR/uievents/#keyup
const error = new Error(
`\`keyup\` events can only be targeted at the active element which is ${prettyDOM(
target,
undefined,
{ maxDepth: 1 },
)}`,
);
// We're only interested in the callsite of fireEvent.keyUp
error.stack = error.stack
.split('\n')
.filter((line) => !/at Function.key/.test(line))
.join('\n');
throw error;
}
originalFireEventKeyUp(element, options);
},
});
export * from '@testing-library/react/pure';
export { act, cleanup, fireEvent };
// We import from `@testing-library/react` and `@testing-library/dom` before creating a JSDOM.
// At this point a global document isn't available yet. Now it is.
export const screen = within(document.body);
export function render() {
throw new Error(
"Don't use `render` directly. Instead use the return value from `createClientRender`",
);
}
| test/utils/createClientRender.js | 1 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.008611634373664856,
0.0006431314977817237,
0.0001639539113966748,
0.00016912136925384402,
0.0017298344755545259
] |
{
"id": 1,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyUp={onKeyUpSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyUp(document.querySelector('input'), {\n",
" key: ' ',\n",
" });\n",
"\n",
" expect(onKeyUpSpy.callCount).to.equal(1);\n",
" expect(onClickSpy.callCount).to.equal(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyUp(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 952
} | /* eslint-disable @typescript-eslint/no-use-before-define */
import * as React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {
createFilterOptions,
} from '@material-ui/core/Autocomplete';
const filter = createFilterOptions<FilmOptionType>();
export default function FreeSoloCreateOption() {
const [value, setValue] = React.useState<FilmOptionType | null>(null);
return (
<Autocomplete
value={value}
onChange={(event, newValue) => {
if (typeof newValue === 'string') {
setValue({
title: newValue,
});
} else if (newValue && newValue.inputValue) {
// Create a new value from the user input
setValue({
title: newValue.inputValue,
});
} else {
setValue(newValue);
}
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
title: `Add "${params.inputValue}"`,
});
}
return filtered;
}}
selectOnFocus
clearOnBlur
handleHomeEndKeys
id="free-solo-with-text-demo"
options={top100Films}
getOptionLabel={(option) => {
// Value selected with enter, right from the input
if (typeof option === 'string') {
return option;
}
// Add "xxx" option created dynamically
if (option.inputValue) {
return option.inputValue;
}
// Regular option
return option.title;
}}
renderOption={(props, option) => <li {...props}>{option.title}</li>}
style={{ width: 300 }}
freeSolo
renderInput={(params) => (
<TextField
{...params}
label="Free solo with text demo"
variant="outlined"
/>
)}
/>
);
}
interface FilmOptionType {
inputValue?: string;
title: string;
year?: number;
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films: FilmOptionType[] = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 },
{ title: '12 Angry Men', year: 1957 },
{ title: "Schindler's List", year: 1993 },
{ title: 'Pulp Fiction', year: 1994 },
{
title: 'The Lord of the Rings: The Return of the King',
year: 2003,
},
{ title: 'The Good, the Bad and the Ugly', year: 1966 },
{ title: 'Fight Club', year: 1999 },
{
title: 'The Lord of the Rings: The Fellowship of the Ring',
year: 2001,
},
{
title: 'Star Wars: Episode V - The Empire Strikes Back',
year: 1980,
},
{ title: 'Forrest Gump', year: 1994 },
{ title: 'Inception', year: 2010 },
{
title: 'The Lord of the Rings: The Two Towers',
year: 2002,
},
{ title: "One Flew Over the Cuckoo's Nest", year: 1975 },
{ title: 'Goodfellas', year: 1990 },
{ title: 'The Matrix', year: 1999 },
{ title: 'Seven Samurai', year: 1954 },
{
title: 'Star Wars: Episode IV - A New Hope',
year: 1977,
},
{ title: 'City of God', year: 2002 },
{ title: 'Se7en', year: 1995 },
{ title: 'The Silence of the Lambs', year: 1991 },
{ title: "It's a Wonderful Life", year: 1946 },
{ title: 'Life Is Beautiful', year: 1997 },
{ title: 'The Usual Suspects', year: 1995 },
{ title: 'Léon: The Professional', year: 1994 },
{ title: 'Spirited Away', year: 2001 },
{ title: 'Saving Private Ryan', year: 1998 },
{ title: 'Once Upon a Time in the West', year: 1968 },
{ title: 'American History X', year: 1998 },
{ title: 'Interstellar', year: 2014 },
{ title: 'Casablanca', year: 1942 },
{ title: 'City Lights', year: 1931 },
{ title: 'Psycho', year: 1960 },
{ title: 'The Green Mile', year: 1999 },
{ title: 'The Intouchables', year: 2011 },
{ title: 'Modern Times', year: 1936 },
{ title: 'Raiders of the Lost Ark', year: 1981 },
{ title: 'Rear Window', year: 1954 },
{ title: 'The Pianist', year: 2002 },
{ title: 'The Departed', year: 2006 },
{ title: 'Terminator 2: Judgment Day', year: 1991 },
{ title: 'Back to the Future', year: 1985 },
{ title: 'Whiplash', year: 2014 },
{ title: 'Gladiator', year: 2000 },
{ title: 'Memento', year: 2000 },
{ title: 'The Prestige', year: 2006 },
{ title: 'The Lion King', year: 1994 },
{ title: 'Apocalypse Now', year: 1979 },
{ title: 'Alien', year: 1979 },
{ title: 'Sunset Boulevard', year: 1950 },
{
title:
'Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb',
year: 1964,
},
{ title: 'The Great Dictator', year: 1940 },
{ title: 'Cinema Paradiso', year: 1988 },
{ title: 'The Lives of Others', year: 2006 },
{ title: 'Grave of the Fireflies', year: 1988 },
{ title: 'Paths of Glory', year: 1957 },
{ title: 'Django Unchained', year: 2012 },
{ title: 'The Shining', year: 1980 },
{ title: 'WALL·E', year: 2008 },
{ title: 'American Beauty', year: 1999 },
{ title: 'The Dark Knight Rises', year: 2012 },
{ title: 'Princess Mononoke', year: 1997 },
{ title: 'Aliens', year: 1986 },
{ title: 'Oldboy', year: 2003 },
{ title: 'Once Upon a Time in America', year: 1984 },
{ title: 'Witness for the Prosecution', year: 1957 },
{ title: 'Das Boot', year: 1981 },
{ title: 'Citizen Kane', year: 1941 },
{ title: 'North by Northwest', year: 1959 },
{ title: 'Vertigo', year: 1958 },
{
title: 'Star Wars: Episode VI - Return of the Jedi',
year: 1983,
},
{ title: 'Reservoir Dogs', year: 1992 },
{ title: 'Braveheart', year: 1995 },
{ title: 'M', year: 1931 },
{ title: 'Requiem for a Dream', year: 2000 },
{ title: 'Amélie', year: 2001 },
{ title: 'A Clockwork Orange', year: 1971 },
{ title: 'Like Stars on Earth', year: 2007 },
{ title: 'Taxi Driver', year: 1976 },
{ title: 'Lawrence of Arabia', year: 1962 },
{ title: 'Double Indemnity', year: 1944 },
{
title: 'Eternal Sunshine of the Spotless Mind',
year: 2004,
},
{ title: 'Amadeus', year: 1984 },
{ title: 'To Kill a Mockingbird', year: 1962 },
{ title: 'Toy Story 3', year: 2010 },
{ title: 'Logan', year: 2017 },
{ title: 'Full Metal Jacket', year: 1987 },
{ title: 'Dangal', year: 2016 },
{ title: 'The Sting', year: 1973 },
{ title: '2001: A Space Odyssey', year: 1968 },
{ title: "Singin' in the Rain", year: 1952 },
{ title: 'Toy Story', year: 1995 },
{ title: 'Bicycle Thieves', year: 1948 },
{ title: 'The Kid', year: 1921 },
{ title: 'Inglourious Basterds', year: 2009 },
{ title: 'Snatch', year: 2000 },
{ title: '3 Idiots', year: 2009 },
{ title: 'Monty Python and the Holy Grail', year: 1975 },
];
| docs/src/pages/components/autocomplete/FreeSoloCreateOption.tsx | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00017652820679359138,
0.00017272688273806125,
0.00016468828835058957,
0.00017346919048577547,
0.0000024125647541950457
] |
{
"id": 1,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyUp={onKeyUpSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyUp(document.querySelector('input'), {\n",
" key: ' ',\n",
" });\n",
"\n",
" expect(onKeyUpSpy.callCount).to.equal(1);\n",
" expect(onClickSpy.callCount).to.equal(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyUp(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 952
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21.5 4H18l1.74 2.61c.11.17-.01.39-.21.39h-2c-.33 0-.65-.17-.83-.45L15 4h-2l1.74 2.61c.11.17-.01.39-.21.39h-2c-.33 0-.65-.17-.83-.45L10 4H8l1.74 2.61c.11.17-.01.39-.21.39h-2c-.33 0-.64-.17-.83-.45L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4.5c0-.28-.22-.5-.5-.5zM11.25 15.25L10 18l-1.25-2.75L6 14l2.75-1.25L10 10l1.25 2.75L14 14l-2.75 1.25zm5.69-3.31L16 14l-.94-2.06L13 11l2.06-.94L16 8l.94 2.06L19 11l-2.06.94z" />
, 'MovieFilterRounded');
| packages/material-ui-icons/src/MovieFilterRounded.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00016663641144987196,
0.00016663641144987196,
0.00016663641144987196,
0.00016663641144987196,
0
] |
{
"id": 1,
"code_window": [
" <ButtonBase onClick={onClickSpy} onKeyUp={onKeyUpSpy} component=\"div\">\n",
" <input autoFocus type=\"text\" />\n",
" </ButtonBase>,\n",
" );\n",
"\n",
" fireEvent.keyUp(document.querySelector('input'), {\n",
" key: ' ',\n",
" });\n",
"\n",
" expect(onKeyUpSpy.callCount).to.equal(1);\n",
" expect(onClickSpy.callCount).to.equal(0);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" fireEvent.keyUp(screen.getByRole('textbox'), {\n"
],
"file_path": "packages/material-ui/src/ButtonBase/ButtonBase.test.js",
"type": "replace",
"edit_start_line_idx": 952
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20 4h-4l-4-4-4 4H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H4V6h4.52l3.52-3.5L15.52 6H20v14zM18 8H6v10h12" />
, 'FilterFrames');
| packages/material-ui-icons/src/FilterFrames.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00017209304496645927,
0.00017209304496645927,
0.00017209304496645927,
0.00017209304496645927,
0
] |
{
"id": 2,
"code_window": [
"\n",
"const originalFireEventKeyDown = rtlFireEvent.keyDown;\n",
"const originalFireEventKeyUp = rtlFireEvent.keyUp;\n",
"const fireEvent = Object.assign(rtlFireEvent, {\n",
" keyDown(element, options = {}) {\n",
" // `element` shouldn't be `document` but we catch this later anyway\n",
" const document = element.ownerDocument || element;\n",
" const target = document.activeElement || document.body || document.documentElement;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"/**\n",
" * @type {typeof rtlFireEvent}\n",
" */\n",
"const fireEvent = (...args) => rtlFireEvent(...args);\n",
"Object.assign(fireEvent, rtlFireEvent, {\n"
],
"file_path": "test/utils/createClientRender.js",
"type": "replace",
"edit_start_line_idx": 160
} | // @ts-check
import * as React from 'react';
import { expect } from 'chai';
import { spy, stub } from 'sinon';
import {
getClasses,
createMount,
describeConformance,
act,
createClientRender,
fireEvent,
screen,
focusVisible,
simulatePointerDevice,
programmaticFocusTriggersFocusVisible,
} from 'test/utils';
import PropTypes from 'prop-types';
import ButtonBase from './ButtonBase';
describe('<ButtonBase />', () => {
const render = createClientRender();
/**
* @type {ReturnType<typeof createMount>}
*/
const mount = createMount();
/**
* @type {Record<string, string>}
*/
let classes;
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14156632/
let canFireDragEvents = true;
before(() => {
classes = getClasses(<ButtonBase />);
// browser testing config
try {
const EventConstructor = window.DragEvent || window.Event;
// eslint-disable-next-line no-new
new EventConstructor('');
} catch (err) {
canFireDragEvents = false;
}
});
describeConformance(<ButtonBase />, () => ({
classes,
inheritComponent: 'button',
mount,
refInstanceof: window.HTMLButtonElement,
testComponentPropWith: 'a',
}));
describe('root node', () => {
it('should change the button type', () => {
const { getByText } = render(<ButtonBase type="submit">Hello</ButtonBase>);
expect(getByText('Hello')).to.have.attribute('type', 'submit');
});
it('should change the button component and add accessibility requirements', () => {
const { getByRole } = render(
<ButtonBase component="span" role="checkbox" aria-checked={false} />,
);
const checkbox = getByRole('checkbox');
expect(checkbox).to.have.property('nodeName', 'SPAN');
expect(checkbox).attribute('tabIndex').to.equal('0');
});
it('should not apply role="button" if type="button"', () => {
const { getByText } = render(<ButtonBase type="button">Hello</ButtonBase>);
expect(getByText('Hello')).to.not.have.attribute('role');
});
it('should change the button type to span and set role="button"', () => {
const { getByRole } = render(<ButtonBase component="span">Hello</ButtonBase>);
const button = getByRole('button');
expect(button).to.have.property('nodeName', 'SPAN');
expect(button).to.not.have.attribute('type');
});
it('should automatically change the button to an anchor element when href is provided', () => {
const { container } = render(<ButtonBase href="https://google.com">Hello</ButtonBase>);
const button = container.firstChild;
expect(button).to.have.property('nodeName', 'A');
expect(button).not.to.have.attribute('role');
expect(button).not.to.have.attribute('type');
expect(button).to.have.attribute('href', 'https://google.com');
});
it('applies role="button" when an anchor is used without href', () => {
const { getByRole } = render(<ButtonBase component="a">Hello</ButtonBase>);
const button = getByRole('button');
expect(button).to.have.property('nodeName', 'A');
expect(button).not.to.have.attribute('type');
});
it('should not use an anchor element if explicit component and href is passed', () => {
const { getByRole } = render(
// @ts-ignore
<ButtonBase component="span" href="https://google.com">
Hello
</ButtonBase>,
);
const button = getByRole('button');
expect(button).to.have.property('nodeName', 'SPAN');
expect(button).to.have.attribute('href', 'https://google.com');
});
});
describe('event callbacks', () => {
it('should fire event callbacks', () => {
const onClick = spy();
const onBlur = spy();
const onFocus = spy();
const onKeyUp = spy();
const onKeyDown = spy();
const onMouseDown = spy();
const onMouseLeave = spy();
const onMouseUp = spy();
const onDragEnd = spy();
const onTouchStart = spy();
const onTouchEnd = spy();
const { getByText } = render(
<ButtonBase
onClick={onClick}
onBlur={onBlur}
onFocus={onFocus}
onKeyUp={onKeyUp}
onKeyDown={onKeyDown}
onMouseDown={onMouseDown}
onMouseLeave={onMouseLeave}
onMouseUp={onMouseUp}
onDragEnd={onDragEnd}
onTouchEnd={onTouchEnd}
onTouchStart={onTouchStart}
>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
// only run in supported browsers
if (typeof Touch !== 'undefined') {
const touch = new Touch({ identifier: 0, target: button, clientX: 0, clientY: 0 });
fireEvent.touchStart(button, { touches: [touch] });
expect(onTouchStart.callCount).to.equal(1);
fireEvent.touchEnd(button, { touches: [touch] });
expect(onTouchEnd.callCount).to.equal(1);
}
if (canFireDragEvents) {
fireEvent.dragEnd(button);
expect(onDragEnd.callCount).to.equal(1);
}
fireEvent.mouseDown(button);
expect(onMouseDown.callCount).to.equal(1);
fireEvent.mouseUp(button);
expect(onMouseUp.callCount).to.equal(1);
fireEvent.click(button);
expect(onClick.callCount).to.equal(1);
button.focus();
expect(onFocus.callCount).to.equal(1);
fireEvent.keyDown(button);
expect(onKeyDown.callCount).to.equal(1);
fireEvent.keyUp(button);
expect(onKeyUp.callCount).to.equal(1);
button.blur();
expect(onBlur.callCount).to.equal(1);
fireEvent.mouseLeave(button);
expect(onMouseLeave.callCount).to.equal(1);
});
});
describe('ripple', () => {
describe('interactions', () => {
it('should not have a focus ripple by default', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(0);
});
it('should start the ripple when the mouse is pressed', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(0);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should stop the ripple when the mouse is released', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.mouseUp(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(0);
});
it('should start the ripple when the mouse is pressed 2', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.mouseUp(button);
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should stop the ripple when the button blurs', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
button.blur();
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(0);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should restart the ripple when the mouse is pressed again', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(0);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
fireEvent.mouseUp(button);
fireEvent.mouseDown(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(1);
});
it('should stop the ripple when the mouse leaves', () => {
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.mouseLeave(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(0);
});
it('should stop the ripple when dragging has finished', function test() {
if (!canFireDragEvents) {
this.skip();
}
const { getByRole } = render(
<ButtonBase
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
child: 'child',
childLeaving: 'child-leaving',
},
}}
/>,
);
const button = getByRole('button');
fireEvent.mouseDown(button);
fireEvent.dragLeave(button);
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
expect(
button.querySelectorAll('.ripple-visible .child:not(.child-leaving)'),
).to.have.lengthOf(0);
});
it('should not crash when changes enableRipple from false to true', () => {
function App() {
/** @type {React.MutableRefObject<import('./ButtonBase').ButtonBaseActions | null>} */
const buttonRef = React.useRef(null);
const [enableRipple, setRipple] = React.useState(false);
React.useEffect(() => {
if (buttonRef.current) {
buttonRef.current.focusVisible();
} else {
throw new Error('buttonRef.current must be available');
}
}, []);
return (
<div>
<button
type="button"
data-testid="trigger"
onClick={() => {
setRipple(true);
}}
>
Trigger crash
</button>
<ButtonBase
autoFocus
action={buttonRef}
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
focusRipple
disableRipple={!enableRipple}
>
the button
</ButtonBase>
</div>
);
}
const { container, getByTestId } = render(<App />);
fireEvent.click(getByTestId('trigger'));
expect(container.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(1);
});
});
});
describe('prop: centerRipple', () => {
it('centers the TouchRipple', () => {
const { container, getByRole } = render(
<ButtonBase
centerRipple
TouchRippleProps={{ classes: { root: 'touch-ripple', ripple: 'touch-ripple-ripple' } }}
>
Hello
</ButtonBase>,
);
// @ts-ignore
stub(container.querySelector('.touch-ripple'), 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 100,
bottom: 10,
left: 20,
top: 20,
}));
fireEvent.mouseDown(getByRole('button'), { clientX: 10, clientY: 10 });
const rippleRipple = container.querySelector('.touch-ripple-ripple');
expect(rippleRipple).to.not.equal(null);
// @ts-ignore
const rippleSyle = window.getComputedStyle(rippleRipple);
expect(rippleSyle).to.have.property('height', '101px');
expect(rippleSyle).to.have.property('width', '101px');
});
it('is disabled by default', () => {
const { container, getByRole } = render(
<ButtonBase
TouchRippleProps={{ classes: { root: 'touch-ripple', ripple: 'touch-ripple-ripple' } }}
>
Hello
</ButtonBase>,
);
// @ts-ignore
stub(container.querySelector('.touch-ripple'), 'getBoundingClientRect').callsFake(() => ({
width: 100,
height: 100,
bottom: 10,
left: 20,
top: 20,
}));
fireEvent.mouseDown(getByRole('button'), { clientX: 10, clientY: 10 });
const rippleRipple = container.querySelector('.touch-ripple-ripple');
expect(rippleRipple).to.not.equal(null);
// @ts-ignore
const rippleSyle = window.getComputedStyle(rippleRipple);
expect(rippleSyle).to.not.have.property('height', '101px');
expect(rippleSyle).to.not.have.property('width', '101px');
});
});
describe('focusRipple', () => {
before(function beforeHook() {
if (/Version\/10\.\d+\.\d+ Safari/.test(window.navigator.userAgent)) {
// browserstack quirk
this.skip();
}
});
it('should pulsate the ripple when focusVisible', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(1);
});
it('should not stop the ripple when the mouse leaves', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
ripplePulsate: 'ripple-pulsate',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
fireEvent.mouseLeave(button);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(1);
});
it('should stop pulsate and start a ripple when the space button is pressed', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
childLeaving: 'child-leaving',
ripplePulsate: 'ripple-pulsate',
rippleVisible: 'rippled-visible',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
fireEvent.keyDown(button, { key: ' ' });
expect(button.querySelectorAll('.ripple-pulsate .child-leaving')).to.have.lengthOf(1);
expect(button.querySelectorAll('.ripple-visible')).to.have.lengthOf(0);
});
it('should stop and re-pulsate when space bar is released', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
childLeaving: 'child-leaving',
ripplePulsate: 'ripple-pulsate',
rippleVisible: 'ripple-visible',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
fireEvent.keyDown(button, { key: ' ' });
fireEvent.keyUp(button, { key: ' ' });
expect(button.querySelectorAll('.ripple-pulsate .child-leaving')).to.have.lengthOf(1);
expect(button.querySelectorAll('.ripple-pulsate')).to.have.lengthOf(2);
expect(button.querySelectorAll('.ripple-visible')).to.have.lengthOf(3);
});
it('should stop on blur and set focusVisible to false', () => {
const { getByRole } = render(
<ButtonBase
focusRipple
TouchRippleProps={{
classes: {
childLeaving: 'child-leaving',
rippleVisible: 'ripple-visible',
},
}}
/>,
);
const button = getByRole('button');
simulatePointerDevice();
focusVisible(button);
act(() => {
button.blur();
});
expect(button.querySelectorAll('.ripple-visible .child-leaving')).to.have.lengthOf(1);
});
});
describe('prop: disabled', () => {
it('should have a negative tabIndex', () => {
const { getByText } = render(<ButtonBase disabled>Hello</ButtonBase>);
expect(getByText('Hello')).to.have.property('tabIndex', -1);
});
it('should forward it to native buttons', () => {
const { getByText } = render(
<ButtonBase disabled component="button">
Hello
</ButtonBase>,
);
expect(getByText('Hello')).to.have.property('disabled', true);
});
it('should reset the focused state', () => {
const { getByText, setProps } = render(<ButtonBase>Hello</ButtonBase>);
const button = getByText('Hello');
simulatePointerDevice();
focusVisible(button);
expect(button).to.have.class(classes.focusVisible);
setProps({ disabled: true });
expect(button).not.to.have.class(classes.focusVisible);
});
it('should use aria attributes for other components', () => {
const { getByRole } = render(
<ButtonBase component="span" disabled>
Hello
</ButtonBase>,
);
const button = getByRole('button');
expect(button).not.to.have.attribute('disabled');
expect(button).to.have.attribute('aria-disabled', 'true');
});
});
describe('prop: component', () => {
it('should allow to use a link component', () => {
/**
* @type {React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLDivElement>>}
*/
const Link = React.forwardRef((props, ref) => (
<div data-testid="link" ref={ref} {...props} />
));
const { getByTestId } = render(<ButtonBase component={Link}>Hello</ButtonBase>);
expect(getByTestId('link')).to.have.attribute('role', 'button');
});
});
describe('event: focus', () => {
it('when disabled should be called onFocus', () => {
const onFocusSpy = spy();
const { getByRole } = render(
<ButtonBase component="div" disabled onFocus={onFocusSpy}>
Hello
</ButtonBase>,
);
act(() => {
getByRole('button').focus();
});
expect(onFocusSpy.callCount).to.equal(1);
});
it('has a focus-visible polyfill', () => {
const { getByText } = render(<ButtonBase>Hello</ButtonBase>);
const button = getByText('Hello');
simulatePointerDevice();
expect(button).not.to.have.class(classes.focusVisible);
button.focus();
if (programmaticFocusTriggersFocusVisible()) {
expect(button).to.have.class(classes.focusVisible);
} else {
expect(button).not.to.have.class(classes.focusVisible);
}
focusVisible(button);
expect(button).to.have.class(classes.focusVisible);
});
it('removes foucs-visible if focus is re-targetted', () => {
/**
* @type {string[]}
*/
const eventLog = [];
function Test() {
/**
* @type {React.Ref<HTMLButtonElement>}
*/
const focusRetargetRef = React.useRef(null);
return (
<div
onFocus={() => {
const { current: focusRetarget } = focusRetargetRef;
if (focusRetarget === null) {
throw new TypeError('Nothing to focous. Test cannot work.');
}
focusRetarget.focus();
}}
>
<button ref={focusRetargetRef} type="button">
you cannot escape me
</button>
<ButtonBase
onBlur={() => eventLog.push('blur')}
onFocus={() => eventLog.push('focus')}
onFocusVisible={() => eventLog.push('focus-visible')}
>
Hello
</ButtonBase>
</div>
);
}
const { getByText } = render(<Test />);
const buttonBase = getByText('Hello');
const focusRetarget = getByText('you cannot escape me');
simulatePointerDevice();
focusVisible(buttonBase);
expect(focusRetarget).toHaveFocus();
expect(eventLog).to.deep.equal(['focus-visible', 'focus', 'blur']);
expect(buttonBase).not.to.have.class(classes.focusVisible);
});
it('onFocusVisibleHandler() should propagate call to onFocusVisible prop', () => {
const onFocusVisibleSpy = spy();
const { getByRole } = render(
<ButtonBase component="span" onFocusVisible={onFocusVisibleSpy}>
Hello
</ButtonBase>,
);
simulatePointerDevice();
focusVisible(getByRole('button'));
expect(onFocusVisibleSpy.calledOnce).to.equal(true);
expect(onFocusVisibleSpy.firstCall.args).to.have.lengthOf(1);
});
it('can be autoFocused', () => {
// as of [email protected] autoFocus causes focus to be emitted before refs
// so we need to check if we're resilient against it
const { getByText } = render(<ButtonBase autoFocus>Hello</ButtonBase>);
expect(getByText('Hello')).toHaveFocus();
});
});
describe('event: keydown', () => {
it('ripples on repeated keydowns', () => {
const { container, getByText } = render(
<ButtonBase focusRipple TouchRippleProps={{ classes: { rippleVisible: 'ripple-visible' } }}>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
act(() => {
button.focus();
fireEvent.keyDown(button, { key: 'Enter' });
});
expect(container.querySelectorAll('.ripple-visible')).to.have.lengthOf(1);
// technically the second keydown should be fire with repeat: true
// but that isn't implemented in IE11 so we shouldn't mock it here either
fireEvent.keyDown(button, { key: 'Enter' });
expect(container.querySelectorAll('.ripple-visible')).to.have.lengthOf(1);
});
describe('prop: onKeyDown', () => {
it('call it when keydown events are dispatched', () => {
const onKeyDownSpy = spy();
const { getByText } = render(
<ButtonBase autoFocus onKeyDown={onKeyDownSpy}>
Hello
</ButtonBase>,
);
fireEvent.keyDown(getByText('Hello'));
expect(onKeyDownSpy.callCount).to.equal(1);
});
});
describe('prop: disableTouchRipple', () => {
it('creates no ripples on click', () => {
const { getByText } = render(
<ButtonBase
disableTouchRipple
TouchRippleProps={{
classes: {
rippleVisible: 'ripple-visible',
},
}}
>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
fireEvent.click(button);
expect(button).not.to.have.class('ripple-visible');
});
});
describe('prop: disableRipple', () => {
it('removes the TouchRipple', () => {
const { getByText } = render(
<ButtonBase disableRipple focusRipple TouchRippleProps={{ className: 'touch-ripple' }}>
Hello
</ButtonBase>,
);
expect(getByText('Hello').querySelector('.touch-ripple')).to.equal(null);
});
});
describe('keyboard accessibility for non interactive elements', () => {
it('does not call onClick when a spacebar is pressed on the element but prevents the default', () => {
const onKeyDown = spy((event) => event.defaultPrevented);
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} onKeyDown={onKeyDown} component="div">
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyDown(button, {
key: ' ',
});
});
expect(onClickSpy.callCount).to.equal(0);
// defaultPrevented?
expect(onKeyDown.returnValues[0]).to.equal(true);
});
it('does call onClick when a spacebar is released on the element', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} component="div">
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyUp(button, {
key: ' ',
});
});
expect(onClickSpy.callCount).to.equal(1);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(false);
});
it('does not call onClick when a spacebar is released and the default is prevented', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase
onClick={onClickSpy}
onKeyUp={
/**
* @param {React.SyntheticEvent} event
*/
(event) => event.preventDefault()
}
component="div"
>
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyUp(button, {
key: ' ',
});
});
expect(onClickSpy.callCount).to.equal(0);
});
it('calls onClick when Enter is pressed on the element', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase onClick={onClickSpy} component="div">
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyDown(button, {
key: 'Enter',
});
});
expect(onClickSpy.calledOnce).to.equal(true);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(true);
});
it('does not call onClick if Enter was pressed on a child', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const onKeyDownSpy = spy();
render(
<ButtonBase onClick={onClickSpy} onKeyDown={onKeyDownSpy} component="div">
<input autoFocus type="text" />
</ButtonBase>,
);
fireEvent.keyDown(document.querySelector('input'), {
key: 'Enter',
});
expect(onKeyDownSpy.callCount).to.equal(1);
expect(onClickSpy.callCount).to.equal(0);
});
it('does not call onClick if Space was released on a child', () => {
const onClickSpy = spy();
const onKeyUpSpy = spy();
render(
<ButtonBase onClick={onClickSpy} onKeyUp={onKeyUpSpy} component="div">
<input autoFocus type="text" />
</ButtonBase>,
);
fireEvent.keyUp(document.querySelector('input'), {
key: ' ',
});
expect(onKeyUpSpy.callCount).to.equal(1);
expect(onClickSpy.callCount).to.equal(0);
});
it('prevents default with an anchor and empty href', () => {
const onClickSpy = spy((event) => event.defaultPrevented);
const { getByRole } = render(
<ButtonBase component="a" onClick={onClickSpy}>
Hello
</ButtonBase>,
);
const button = getByRole('button');
act(() => {
button.focus();
fireEvent.keyDown(button, { key: 'Enter' });
});
expect(onClickSpy.calledOnce).to.equal(true);
// defaultPrevented?
expect(onClickSpy.returnValues[0]).to.equal(true);
});
it('should ignore anchors with href', () => {
const onClick = spy();
const onKeyDown = spy((event) => event.defaultPrevented);
const { getByText } = render(
<ButtonBase component="a" href="href" onClick={onClick} onKeyDown={onKeyDown}>
Hello
</ButtonBase>,
);
const button = getByText('Hello');
act(() => {
button.focus();
fireEvent.keyDown(button, {
key: 'Enter',
});
});
expect(onClick.calledOnce).to.equal(false);
// defaultPrevented
expect(onKeyDown.returnValues[0]).to.equal(false);
});
});
});
describe('prop: action', () => {
it('should be able to focus visible the button', () => {
/**
* @type {React.RefObject<import('./ButtonBase').ButtonBaseActions>}
*/
const buttonActionsRef = React.createRef();
const { getByText } = render(
<ButtonBase action={buttonActionsRef} focusVisibleClassName="focusVisible">
Hello
</ButtonBase>,
);
// @ts-ignore
expect(typeof buttonActionsRef.current.focusVisible).to.equal('function');
act(() => {
// @ts-ignore
buttonActionsRef.current.focusVisible();
});
expect(getByText('Hello')).toHaveFocus();
expect(getByText('Hello')).to.match('.focusVisible');
});
});
describe('warnings', () => {
beforeEach(() => {
PropTypes.resetWarningCache();
});
it('warns on invalid `component` prop: ref forward', () => {
// Only run the test on node. On the browser the thrown error is not caught
if (!/jsdom/.test(window.navigator.userAgent)) {
return;
}
/**
*
* @param {import('react').HTMLAttributes<HTMLButtonElement>} props
*/
function Component(props) {
return <button type="button" {...props} />;
}
expect(() => {
PropTypes.checkPropTypes(
// @ts-ignore `Naked` is internal
ButtonBase.Naked.propTypes,
{ classes: {}, component: Component },
'prop',
'MockedName',
);
}).toErrorDev(
'Invalid prop `component` supplied to `MockedName`. Expected an element type that can hold a ref',
);
});
it('warns on invalid `component` prop: prop forward', () => {
const Component = React.forwardRef((props, ref) => (
<button type="button" ref={ref} {...props}>
Hello
</button>
));
// cant match the error message here because flakiness with mocha watchmode
expect(() => {
render(<ButtonBase component={Component} />);
}).toErrorDev('Please make sure the children prop is rendered in this custom component.');
});
});
describe('prop: type', () => {
it('is `button` by default', () => {
render(<ButtonBase />);
expect(screen.getByRole('button')).to.have.property('type', 'button');
});
it('can be changed to other button types', () => {
render(<ButtonBase type="submit" />);
expect(screen.getByRole('button')).to.have.property('type', 'submit');
});
it('allows non-standard values', () => {
// @ts-expect-error `@types/react` only lists standard values
render(<ButtonBase type="fictional-type" />);
expect(screen.getByRole('button')).to.have.attribute('type', 'fictional-type');
// By spec non-supported types result in the default type for `<button>` which is `submit`
expect(screen.getByRole('button')).to.have.property('type', 'submit');
});
it('is forwarded to anchor components', () => {
render(<ButtonBase component="a" href="some-recording.ogg" download type="audio/ogg" />);
expect(screen.getByRole('link')).to.have.attribute('type', 'audio/ogg');
expect(screen.getByRole('link')).to.have.property('type', 'audio/ogg');
});
it('is forwarded to custom components', () => {
/**
* @type {React.ForwardRefExoticComponent<React.ButtonHTMLAttributes<HTMLButtonElement>>}
*/
const CustomButton = React.forwardRef((props, ref) => <button ref={ref} {...props} />);
render(<ButtonBase component={CustomButton} type="reset" />);
expect(screen.getByRole('button')).to.have.property('type', 'reset');
});
});
});
| packages/material-ui/src/ButtonBase/ButtonBase.test.js | 1 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.9986214637756348,
0.26945948600769043,
0.00016441433399450034,
0.00017481358372606337,
0.4406466782093048
] |
{
"id": 2,
"code_window": [
"\n",
"const originalFireEventKeyDown = rtlFireEvent.keyDown;\n",
"const originalFireEventKeyUp = rtlFireEvent.keyUp;\n",
"const fireEvent = Object.assign(rtlFireEvent, {\n",
" keyDown(element, options = {}) {\n",
" // `element` shouldn't be `document` but we catch this later anyway\n",
" const document = element.ownerDocument || element;\n",
" const target = document.activeElement || document.body || document.documentElement;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"/**\n",
" * @type {typeof rtlFireEvent}\n",
" */\n",
"const fireEvent = (...args) => rtlFireEvent(...args);\n",
"Object.assign(fireEvent, rtlFireEvent, {\n"
],
"file_path": "test/utils/createClientRender.js",
"type": "replace",
"edit_start_line_idx": 160
} | import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Pagination from '@material-ui/core/Pagination';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
marginTop: theme.spacing(2),
},
},
}));
export default function PaginationButtons() {
const classes = useStyles();
return (
<div className={classes.root}>
<Pagination count={10} showFirstButton showLastButton />
<Pagination count={10} hidePrevButton hideNextButton />
</div>
);
}
| docs/src/pages/components/pagination/PaginationButtons.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.0001749067014316097,
0.00017398181080352515,
0.00017341940838377923,
0.00017361927893944085,
6.590772727577132e-7
] |
{
"id": 2,
"code_window": [
"\n",
"const originalFireEventKeyDown = rtlFireEvent.keyDown;\n",
"const originalFireEventKeyUp = rtlFireEvent.keyUp;\n",
"const fireEvent = Object.assign(rtlFireEvent, {\n",
" keyDown(element, options = {}) {\n",
" // `element` shouldn't be `document` but we catch this later anyway\n",
" const document = element.ownerDocument || element;\n",
" const target = document.activeElement || document.body || document.documentElement;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"/**\n",
" * @type {typeof rtlFireEvent}\n",
" */\n",
"const fireEvent = (...args) => rtlFireEvent(...args);\n",
"Object.assign(fireEvent, rtlFireEvent, {\n"
],
"file_path": "test/utils/createClientRender.js",
"type": "replace",
"edit_start_line_idx": 160
} | export { default } from './SpeedDialAction';
| packages/material-ui/src/SpeedDialAction/index.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00017490201571490616,
0.00017490201571490616,
0.00017490201571490616,
0.00017490201571490616,
0
] |
{
"id": 2,
"code_window": [
"\n",
"const originalFireEventKeyDown = rtlFireEvent.keyDown;\n",
"const originalFireEventKeyUp = rtlFireEvent.keyUp;\n",
"const fireEvent = Object.assign(rtlFireEvent, {\n",
" keyDown(element, options = {}) {\n",
" // `element` shouldn't be `document` but we catch this later anyway\n",
" const document = element.ownerDocument || element;\n",
" const target = document.activeElement || document.body || document.documentElement;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"/**\n",
" * @type {typeof rtlFireEvent}\n",
" */\n",
"const fireEvent = (...args) => rtlFireEvent(...args);\n",
"Object.assign(fireEvent, rtlFireEvent, {\n"
],
"file_path": "test/utils/createClientRender.js",
"type": "replace",
"edit_start_line_idx": 160
} | import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import CssBaseline from '@material-ui/core/CssBaseline';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import Paper from '@material-ui/core/Paper';
import Fab from '@material-ui/core/Fab';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import ListItemText from '@material-ui/core/ListItemText';
import ListSubheader from '@material-ui/core/ListSubheader';
import Avatar from '@material-ui/core/Avatar';
import MenuIcon from '@material-ui/icons/Menu';
import AddIcon from '@material-ui/icons/Add';
import SearchIcon from '@material-ui/icons/Search';
import MoreIcon from '@material-ui/icons/MoreVert';
const messages = [
{
id: 1,
primary: 'Brunch this week?',
secondary:
"I'll be in the neighbourhood this week. Let's grab a bite to eat",
person: '/static/images/avatar/5.jpg',
},
{
id: 2,
primary: 'Birthday Gift',
secondary: `Do you have a suggestion for a good present for John on his work
anniversary. I am really confused & would love your thoughts on it.`,
person: '/static/images/avatar/1.jpg',
},
{
id: 3,
primary: 'Recipe to try',
secondary:
'I am try out this new BBQ recipe, I think this might be amazing',
person: '/static/images/avatar/2.jpg',
},
{
id: 4,
primary: 'Yes!',
secondary: 'I have the tickets to the ReactConf for this year.',
person: '/static/images/avatar/3.jpg',
},
{
id: 5,
primary: "Doctor's Appointment",
secondary:
'My appointment for the doctor was rescheduled for next Saturday.',
person: '/static/images/avatar/4.jpg',
},
{
id: 6,
primary: 'Discussion',
secondary: `Menus that are generated by the bottom app bar (such as a bottom
navigation drawer or overflow menu) open as bottom sheets at a higher elevation
than the bar.`,
person: '/static/images/avatar/5.jpg',
},
{
id: 7,
primary: 'Summer BBQ',
secondary: `Who wants to have a cookout this weekend? I just got some furniture
for my backyard and would love to fire up the grill.`,
person: '/static/images/avatar/1.jpg',
},
];
const useStyles = makeStyles((theme) => ({
text: {
padding: theme.spacing(2, 2, 0),
},
paper: {
paddingBottom: 50,
},
list: {
marginBottom: theme.spacing(2),
},
subheader: {
backgroundColor: theme.palette.background.paper,
},
appBar: {
top: 'auto',
bottom: 0,
},
grow: {
flexGrow: 1,
},
fabButton: {
position: 'absolute',
zIndex: 1,
top: -30,
left: 0,
right: 0,
margin: '0 auto',
},
}));
export default function BottomAppBar() {
const classes = useStyles();
return (
<React.Fragment>
<CssBaseline />
<Paper square className={classes.paper}>
<Typography className={classes.text} variant="h5" gutterBottom>
Inbox
</Typography>
<List className={classes.list}>
{messages.map(({ id, primary, secondary, person }) => (
<React.Fragment key={id}>
{id === 1 && (
<ListSubheader className={classes.subheader}>
Today
</ListSubheader>
)}
{id === 3 && (
<ListSubheader className={classes.subheader}>
Yesterday
</ListSubheader>
)}
<ListItem button>
<ListItemAvatar>
<Avatar alt="Profile Picture" src={person} />
</ListItemAvatar>
<ListItemText primary={primary} secondary={secondary} />
</ListItem>
</React.Fragment>
))}
</List>
</Paper>
<AppBar position="fixed" color="primary" className={classes.appBar}>
<Toolbar>
<IconButton edge="start" color="inherit" aria-label="open drawer">
<MenuIcon />
</IconButton>
<Fab color="secondary" aria-label="add" className={classes.fabButton}>
<AddIcon />
</Fab>
<div className={classes.grow} />
<IconButton color="inherit">
<SearchIcon />
</IconButton>
<IconButton edge="end" color="inherit">
<MoreIcon />
</IconButton>
</Toolbar>
</AppBar>
</React.Fragment>
);
}
| docs/src/pages/components/app-bar/BottomAppBar.js | 0 | https://github.com/mui/material-ui/commit/6f6450f8b14ff9761073b0b540c233cfcb95ee92 | [
0.00017883346299640834,
0.00017592564108781517,
0.00017304412904195487,
0.000175925757503137,
0.0000016089049950096523
] |
{
"id": 0,
"code_window": [
" display: 'inline-flex',\n",
" alignItems: 'baseline',\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-middle`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingSM,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-middle': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 182
} | // deps-lint-skip-all
import { CSSObject } from '@ant-design/cssinjs';
import {
FullToken,
genComponentStyleHook,
GenerateStyle,
mergeToken,
resetComponent,
} from '../../_util/theme';
interface DescriptionsToken extends FullToken<'Descriptions'> {
descriptionsTitleMarginBottom: number;
descriptionsExtraColor: string;
descriptionItemPaddingBottom: number;
descriptionItemTrailingColon: boolean;
descriptionsDefaultPadding: string;
descriptionsBg: string;
descriptionsMiddlePadding: string;
descriptionsSmallPadding: string;
descriptionsItemLabelColonMarginRight: number;
descriptionsItemLabelColonMarginLeft: number;
}
const genBorderedStyle = (token: DescriptionsToken): CSSObject => {
const {
componentCls,
descriptionsSmallPadding,
descriptionsDefaultPadding,
descriptionsMiddlePadding,
descriptionsBg,
} = token;
return {
[`&${componentCls}-bordered`]: {
[`${componentCls}-view`]: {
border: `1px solid ${token.colorSplit}`,
'> table': {
tableLayout: 'auto',
borderCollapse: 'collapse',
},
},
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsDefaultPadding,
borderInlineEnd: `1px solid ${token.colorSplit}`,
'&:last-child': {
borderInlineEnd: 'none',
},
},
[`${componentCls}-item-label`]: {
backgroundColor: descriptionsBg,
'&::after': {
display: 'none',
},
},
[`${componentCls}-row`]: {
borderBottom: `1px solid ${token.colorSplit}`,
'&:last-child': {
borderBottom: 'none',
},
},
[`&${componentCls}-middle`]: {
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsMiddlePadding,
},
},
[`&${componentCls}-small`]: {
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsSmallPadding,
},
},
},
};
};
const genDescriptionStyles: GenerateStyle<DescriptionsToken> = (token: DescriptionsToken) => {
const {
componentCls,
descriptionsExtraColor,
descriptionItemPaddingBottom,
descriptionItemTrailingColon,
descriptionsItemLabelColonMarginRight,
descriptionsItemLabelColonMarginLeft,
descriptionsTitleMarginBottom,
} = token;
return {
[componentCls]: {
...resetComponent(token),
...genBorderedStyle(token),
[`&-rtl`]: {
direction: 'rtl',
},
[`${componentCls}-header`]: {
display: 'flex',
alignItems: 'center',
// FIXME: hardcode in v4
marginBottom: descriptionsTitleMarginBottom,
},
[`${componentCls}-title`]: {
flex: 'auto',
overflow: 'hidden',
color: token.colorText,
fontWeight: 'bold',
// FIXME: hardcode in v4
fontSize: token.fontSizeLG,
lineHeight: token.lineHeight,
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
},
[`${componentCls}-extra`]: {
marginInlineStart: 'auto',
color: descriptionsExtraColor,
// FIXME: hardcode in v4
fontSize: token.fontSize,
},
[`${componentCls}-view`]: {
width: '100%',
// FIXME: hardcode in v4
borderRadius: token.radiusBase,
table: {
width: '100%',
tableLayout: 'fixed',
},
},
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: descriptionItemPaddingBottom,
},
'&:last-child': {
borderBottom: 'none',
},
},
[`${componentCls}-item-label`]: {
color: token.colorText,
fontWeight: 'normal',
// FIXME: hardcode in v4
fontSize: token.fontSize,
lineHeight: token.lineHeight,
textAlign: `start`,
'&::after': {
content: descriptionItemTrailingColon ? '":"' : '" "',
position: 'relative',
// FIXME: hardcode in v4
top: -0.5,
marginInline: `${descriptionsItemLabelColonMarginLeft}px ${descriptionsItemLabelColonMarginRight}px`,
},
[`&${componentCls}-item-no-colon::after`]: {
content: '""',
},
},
[`${componentCls}-item-no-label`]: {
'&::after': {
margin: 0,
content: '""',
},
},
[`${componentCls}-item-content`]: {
display: 'table-cell',
flex: 1,
color: token.colorText,
// FIXME: hardcode in v4
fontSize: token.fontSize,
lineHeight: token.lineHeight,
wordBreak: 'break-word',
overflowWrap: 'break-word',
},
[`${componentCls}-item`]: {
paddingBottom: 0,
verticalAlign: 'top',
'&-container': {
display: 'flex',
[`${componentCls}-item-label`]: {
display: 'inline-flex',
alignItems: 'baseline',
},
[`${componentCls}-item-content`]: {
display: 'inline-flex',
alignItems: 'baseline',
},
},
},
[`${componentCls}-middle`]: {
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: token.paddingSM,
},
},
},
[`${componentCls}-small`]: {
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: token.paddingXS,
},
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook('Descriptions', token => {
const descriptionsBg = '#fafafa';
const descriptionsTitleMarginBottom = 20;
const descriptionsExtraColor = token.colorText;
const descriptionsSmallPadding = `${token.paddingXS}px ${token.padding}px`;
const descriptionsDefaultPadding = `${token.padding}px ${token.paddingLG}px`;
const descriptionsMiddlePadding = `${token.paddingSM}px ${token.paddingLG}px`;
const descriptionItemPaddingBottom = token.padding;
const descriptionItemTrailingColon = true;
const descriptionsItemLabelColonMarginRight = 8;
const descriptionsItemLabelColonMarginLeft = 2;
const descriptionToken = mergeToken<DescriptionsToken>(token, {
descriptionsBg,
descriptionsTitleMarginBottom,
descriptionsExtraColor,
descriptionItemPaddingBottom,
descriptionItemTrailingColon,
descriptionsSmallPadding,
descriptionsDefaultPadding,
descriptionsMiddlePadding,
descriptionsItemLabelColonMarginRight,
descriptionsItemLabelColonMarginLeft,
});
return [genDescriptionStyles(descriptionToken)];
});
| components/descriptions/style/index.tsx | 1 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.9899992346763611,
0.09342137724161148,
0.00016719155246391892,
0.0026245296467095613,
0.2625696361064911
] |
{
"id": 0,
"code_window": [
" display: 'inline-flex',\n",
" alignItems: 'baseline',\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-middle`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingSM,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-middle': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 182
} | import { imageDemoTest } from '../../../tests/shared/imageTest';
describe('Modal image', () => {
imageDemoTest('modal');
});
| components/modal/__tests__/image.test.ts | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017415915499441326,
0.00017415915499441326,
0.00017415915499441326,
0.00017415915499441326,
0
] |
{
"id": 0,
"code_window": [
" display: 'inline-flex',\n",
" alignItems: 'baseline',\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-middle`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingSM,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-middle': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 182
} | import locale from '../locale/zh_HK';
export default locale;
| components/locale-provider/zh_HK.tsx | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017140884301625192,
0.00017140884301625192,
0.00017140884301625192,
0.00017140884301625192,
0
] |
{
"id": 0,
"code_window": [
" display: 'inline-flex',\n",
" alignItems: 'baseline',\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-middle`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingSM,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-middle': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 182
} | ---
order: 2
title:
zh-CN: 位置
en-US: Position
---
## zh-CN
位置有 4 个方向。
## en-US
There are 4 position options available.
```jsx
import { Carousel, Radio } from 'antd';
const contentStyle = {
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const PositionCarouselDemo = () => {
const [dotPosition, setDotPosition] = React.useState('top');
const handlePositionChange = ({ target: { value } }) => {
setDotPosition(value);
};
return (
<>
<Radio.Group onChange={handlePositionChange} value={dotPosition} style={{ marginBottom: 8 }}>
<Radio.Button value="top">Top</Radio.Button>
<Radio.Button value="bottom">Bottom</Radio.Button>
<Radio.Button value="left">Left</Radio.Button>
<Radio.Button value="right">Right</Radio.Button>
</Radio.Group>
<Carousel dotPosition={dotPosition}>
<div>
<h3 style={contentStyle}>1</h3>
</div>
<div>
<h3 style={contentStyle}>2</h3>
</div>
<div>
<h3 style={contentStyle}>3</h3>
</div>
<div>
<h3 style={contentStyle}>4</h3>
</div>
</Carousel>
</>
);
};
export default () => <PositionCarouselDemo />;
```
| components/carousel/demo/position.md | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.0001721500011626631,
0.000169281818671152,
0.00016473808500450104,
0.00016961374785751104,
0.000002201440793214715
] |
{
"id": 1,
"code_window": [
" paddingBottom: token.paddingSM,\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-small`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingXS,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-small': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 190
} | // deps-lint-skip-all
import { CSSObject } from '@ant-design/cssinjs';
import {
FullToken,
genComponentStyleHook,
GenerateStyle,
mergeToken,
resetComponent,
} from '../../_util/theme';
interface DescriptionsToken extends FullToken<'Descriptions'> {
descriptionsTitleMarginBottom: number;
descriptionsExtraColor: string;
descriptionItemPaddingBottom: number;
descriptionItemTrailingColon: boolean;
descriptionsDefaultPadding: string;
descriptionsBg: string;
descriptionsMiddlePadding: string;
descriptionsSmallPadding: string;
descriptionsItemLabelColonMarginRight: number;
descriptionsItemLabelColonMarginLeft: number;
}
const genBorderedStyle = (token: DescriptionsToken): CSSObject => {
const {
componentCls,
descriptionsSmallPadding,
descriptionsDefaultPadding,
descriptionsMiddlePadding,
descriptionsBg,
} = token;
return {
[`&${componentCls}-bordered`]: {
[`${componentCls}-view`]: {
border: `1px solid ${token.colorSplit}`,
'> table': {
tableLayout: 'auto',
borderCollapse: 'collapse',
},
},
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsDefaultPadding,
borderInlineEnd: `1px solid ${token.colorSplit}`,
'&:last-child': {
borderInlineEnd: 'none',
},
},
[`${componentCls}-item-label`]: {
backgroundColor: descriptionsBg,
'&::after': {
display: 'none',
},
},
[`${componentCls}-row`]: {
borderBottom: `1px solid ${token.colorSplit}`,
'&:last-child': {
borderBottom: 'none',
},
},
[`&${componentCls}-middle`]: {
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsMiddlePadding,
},
},
[`&${componentCls}-small`]: {
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsSmallPadding,
},
},
},
};
};
const genDescriptionStyles: GenerateStyle<DescriptionsToken> = (token: DescriptionsToken) => {
const {
componentCls,
descriptionsExtraColor,
descriptionItemPaddingBottom,
descriptionItemTrailingColon,
descriptionsItemLabelColonMarginRight,
descriptionsItemLabelColonMarginLeft,
descriptionsTitleMarginBottom,
} = token;
return {
[componentCls]: {
...resetComponent(token),
...genBorderedStyle(token),
[`&-rtl`]: {
direction: 'rtl',
},
[`${componentCls}-header`]: {
display: 'flex',
alignItems: 'center',
// FIXME: hardcode in v4
marginBottom: descriptionsTitleMarginBottom,
},
[`${componentCls}-title`]: {
flex: 'auto',
overflow: 'hidden',
color: token.colorText,
fontWeight: 'bold',
// FIXME: hardcode in v4
fontSize: token.fontSizeLG,
lineHeight: token.lineHeight,
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
},
[`${componentCls}-extra`]: {
marginInlineStart: 'auto',
color: descriptionsExtraColor,
// FIXME: hardcode in v4
fontSize: token.fontSize,
},
[`${componentCls}-view`]: {
width: '100%',
// FIXME: hardcode in v4
borderRadius: token.radiusBase,
table: {
width: '100%',
tableLayout: 'fixed',
},
},
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: descriptionItemPaddingBottom,
},
'&:last-child': {
borderBottom: 'none',
},
},
[`${componentCls}-item-label`]: {
color: token.colorText,
fontWeight: 'normal',
// FIXME: hardcode in v4
fontSize: token.fontSize,
lineHeight: token.lineHeight,
textAlign: `start`,
'&::after': {
content: descriptionItemTrailingColon ? '":"' : '" "',
position: 'relative',
// FIXME: hardcode in v4
top: -0.5,
marginInline: `${descriptionsItemLabelColonMarginLeft}px ${descriptionsItemLabelColonMarginRight}px`,
},
[`&${componentCls}-item-no-colon::after`]: {
content: '""',
},
},
[`${componentCls}-item-no-label`]: {
'&::after': {
margin: 0,
content: '""',
},
},
[`${componentCls}-item-content`]: {
display: 'table-cell',
flex: 1,
color: token.colorText,
// FIXME: hardcode in v4
fontSize: token.fontSize,
lineHeight: token.lineHeight,
wordBreak: 'break-word',
overflowWrap: 'break-word',
},
[`${componentCls}-item`]: {
paddingBottom: 0,
verticalAlign: 'top',
'&-container': {
display: 'flex',
[`${componentCls}-item-label`]: {
display: 'inline-flex',
alignItems: 'baseline',
},
[`${componentCls}-item-content`]: {
display: 'inline-flex',
alignItems: 'baseline',
},
},
},
[`${componentCls}-middle`]: {
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: token.paddingSM,
},
},
},
[`${componentCls}-small`]: {
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: token.paddingXS,
},
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook('Descriptions', token => {
const descriptionsBg = '#fafafa';
const descriptionsTitleMarginBottom = 20;
const descriptionsExtraColor = token.colorText;
const descriptionsSmallPadding = `${token.paddingXS}px ${token.padding}px`;
const descriptionsDefaultPadding = `${token.padding}px ${token.paddingLG}px`;
const descriptionsMiddlePadding = `${token.paddingSM}px ${token.paddingLG}px`;
const descriptionItemPaddingBottom = token.padding;
const descriptionItemTrailingColon = true;
const descriptionsItemLabelColonMarginRight = 8;
const descriptionsItemLabelColonMarginLeft = 2;
const descriptionToken = mergeToken<DescriptionsToken>(token, {
descriptionsBg,
descriptionsTitleMarginBottom,
descriptionsExtraColor,
descriptionItemPaddingBottom,
descriptionItemTrailingColon,
descriptionsSmallPadding,
descriptionsDefaultPadding,
descriptionsMiddlePadding,
descriptionsItemLabelColonMarginRight,
descriptionsItemLabelColonMarginLeft,
});
return [genDescriptionStyles(descriptionToken)];
});
| components/descriptions/style/index.tsx | 1 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.9938181042671204,
0.07265868782997131,
0.0001656069653108716,
0.0020712269470095634,
0.23238489031791687
] |
{
"id": 1,
"code_window": [
" paddingBottom: token.paddingSM,\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-small`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingXS,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-small': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 190
} | import demoTest from '../../../tests/shared/demoTest';
demoTest('auto-complete');
| components/auto-complete/__tests__/demo.test.js | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017201004084199667,
0.00017201004084199667,
0.00017201004084199667,
0.00017201004084199667,
0
] |
{
"id": 1,
"code_window": [
" paddingBottom: token.paddingSM,\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-small`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingXS,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-small': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 190
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders ./components/modal/demo/async.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Open Modal with async logic
</span>
</button>
`;
exports[`renders ./components/modal/demo/basic.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Open Modal
</span>
</button>
`;
exports[`renders ./components/modal/demo/button-props.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Open Modal with customized button props
</span>
</button>
`;
exports[`renders ./components/modal/demo/confirm.md extend context correctly 1`] = `
<div
class="ant-space ant-space-horizontal ant-space-align-center"
style="flex-wrap:wrap;margin-bottom:-8px"
>
<div
class="ant-space-item"
style="margin-right:8px;padding-bottom:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Confirm
</span>
</button>
</div>
<div
class="ant-space-item"
style="margin-right:8px;padding-bottom:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
With promise
</span>
</button>
</div>
<div
class="ant-space-item"
style="margin-right:8px;padding-bottom:8px"
>
<button
class="ant-btn ant-btn-dashed"
type="button"
>
<span>
Delete
</span>
</button>
</div>
<div
class="ant-space-item"
style="padding-bottom:8px"
>
<button
class="ant-btn ant-btn-dashed"
type="button"
>
<span>
With extra props
</span>
</button>
</div>
</div>
`;
exports[`renders ./components/modal/demo/confirm-router.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Confirm
</span>
</button>
`;
exports[`renders ./components/modal/demo/dark.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Open Modal
</span>
</button>
`;
exports[`renders ./components/modal/demo/footer.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Open Modal with customized footer
</span>
</button>
`;
exports[`renders ./components/modal/demo/hooks.md extend context correctly 1`] = `
<div
class="ant-space ant-space-horizontal ant-space-align-center"
>
<div
class="ant-space-item"
style="margin-right:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Confirm
</span>
</button>
</div>
<div
class="ant-space-item"
style="margin-right:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Warning
</span>
</button>
</div>
<div
class="ant-space-item"
style="margin-right:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Info
</span>
</button>
</div>
<div
class="ant-space-item"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Error
</span>
</button>
</div>
</div>
`;
exports[`renders ./components/modal/demo/info.md extend context correctly 1`] = `
<div
class="ant-space ant-space-horizontal ant-space-align-center"
style="flex-wrap:wrap;margin-bottom:-8px"
>
<div
class="ant-space-item"
style="margin-right:8px;padding-bottom:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Info
</span>
</button>
</div>
<div
class="ant-space-item"
style="margin-right:8px;padding-bottom:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Success
</span>
</button>
</div>
<div
class="ant-space-item"
style="margin-right:8px;padding-bottom:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Error
</span>
</button>
</div>
<div
class="ant-space-item"
style="padding-bottom:8px"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Warning
</span>
</button>
</div>
</div>
`;
exports[`renders ./components/modal/demo/locale.md extend context correctly 1`] = `
<div
class="ant-space ant-space-horizontal ant-space-align-center"
>
<div
class="ant-space-item"
style="margin-right:8px"
>
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Modal
</span>
</button>
</div>
<div
class="ant-space-item"
>
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Confirm
</span>
</button>
</div>
</div>
`;
exports[`renders ./components/modal/demo/manual.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Open modal to close in 5s
</span>
</button>
`;
exports[`renders ./components/modal/demo/modal-render.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-default"
type="button"
>
<span>
Open Draggable Modal
</span>
</button>
`;
exports[`renders ./components/modal/demo/position.md extend context correctly 1`] = `
Array [
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Display a modal dialog at 20px to Top
</span>
</button>,
<br />,
<br />,
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Vertically centered modal dialog
</span>
</button>,
]
`;
exports[`renders ./components/modal/demo/width.md extend context correctly 1`] = `
<button
class="ant-btn ant-btn-primary"
type="button"
>
<span>
Open Modal of 1000px width
</span>
</button>
`;
| components/modal/__tests__/__snapshots__/demo-extend.test.ts.snap | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017039428348653018,
0.00016727835463825613,
0.0001629943581065163,
0.0001674553204793483,
0.000002052764330073842
] |
{
"id": 1,
"code_window": [
" paddingBottom: token.paddingSM,\n",
" },\n",
" },\n",
" },\n",
" [`${componentCls}-small`]: {\n",
" [`${componentCls}-row`]: {\n",
" '> th, > td': {\n",
" // FIXME: hardcode in v4\n",
" paddingBottom: token.paddingXS,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '&-small': {\n"
],
"file_path": "components/descriptions/style/index.tsx",
"type": "replace",
"edit_start_line_idx": 190
} | import locale from '../locale/ur_PK';
export default locale;
| components/locale-provider/ur_PK.tsx | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017236829444300383,
0.00017236829444300383,
0.00017236829444300383,
0.00017236829444300383,
0
] |
{
"id": 2,
"code_window": [
" cursor: 'not-allowed',\n",
" },\n",
"\n",
" [`${componentCls}-btn`]: {\n",
" display: 'table',\n",
" height: '100%',\n",
" outline: 'none',\n",
" },\n",
"\n",
" [`${componentCls}-drag-container`]: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" width: '100%',\n"
],
"file_path": "components/upload/style/dragger.tsx",
"type": "add",
"edit_start_line_idx": 28
} | // deps-lint-skip-all
import { CSSObject } from '@ant-design/cssinjs';
import {
FullToken,
genComponentStyleHook,
GenerateStyle,
mergeToken,
resetComponent,
} from '../../_util/theme';
interface DescriptionsToken extends FullToken<'Descriptions'> {
descriptionsTitleMarginBottom: number;
descriptionsExtraColor: string;
descriptionItemPaddingBottom: number;
descriptionItemTrailingColon: boolean;
descriptionsDefaultPadding: string;
descriptionsBg: string;
descriptionsMiddlePadding: string;
descriptionsSmallPadding: string;
descriptionsItemLabelColonMarginRight: number;
descriptionsItemLabelColonMarginLeft: number;
}
const genBorderedStyle = (token: DescriptionsToken): CSSObject => {
const {
componentCls,
descriptionsSmallPadding,
descriptionsDefaultPadding,
descriptionsMiddlePadding,
descriptionsBg,
} = token;
return {
[`&${componentCls}-bordered`]: {
[`${componentCls}-view`]: {
border: `1px solid ${token.colorSplit}`,
'> table': {
tableLayout: 'auto',
borderCollapse: 'collapse',
},
},
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsDefaultPadding,
borderInlineEnd: `1px solid ${token.colorSplit}`,
'&:last-child': {
borderInlineEnd: 'none',
},
},
[`${componentCls}-item-label`]: {
backgroundColor: descriptionsBg,
'&::after': {
display: 'none',
},
},
[`${componentCls}-row`]: {
borderBottom: `1px solid ${token.colorSplit}`,
'&:last-child': {
borderBottom: 'none',
},
},
[`&${componentCls}-middle`]: {
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsMiddlePadding,
},
},
[`&${componentCls}-small`]: {
[`${componentCls}-item-label, ${componentCls}-item-content`]: {
padding: descriptionsSmallPadding,
},
},
},
};
};
const genDescriptionStyles: GenerateStyle<DescriptionsToken> = (token: DescriptionsToken) => {
const {
componentCls,
descriptionsExtraColor,
descriptionItemPaddingBottom,
descriptionItemTrailingColon,
descriptionsItemLabelColonMarginRight,
descriptionsItemLabelColonMarginLeft,
descriptionsTitleMarginBottom,
} = token;
return {
[componentCls]: {
...resetComponent(token),
...genBorderedStyle(token),
[`&-rtl`]: {
direction: 'rtl',
},
[`${componentCls}-header`]: {
display: 'flex',
alignItems: 'center',
// FIXME: hardcode in v4
marginBottom: descriptionsTitleMarginBottom,
},
[`${componentCls}-title`]: {
flex: 'auto',
overflow: 'hidden',
color: token.colorText,
fontWeight: 'bold',
// FIXME: hardcode in v4
fontSize: token.fontSizeLG,
lineHeight: token.lineHeight,
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
},
[`${componentCls}-extra`]: {
marginInlineStart: 'auto',
color: descriptionsExtraColor,
// FIXME: hardcode in v4
fontSize: token.fontSize,
},
[`${componentCls}-view`]: {
width: '100%',
// FIXME: hardcode in v4
borderRadius: token.radiusBase,
table: {
width: '100%',
tableLayout: 'fixed',
},
},
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: descriptionItemPaddingBottom,
},
'&:last-child': {
borderBottom: 'none',
},
},
[`${componentCls}-item-label`]: {
color: token.colorText,
fontWeight: 'normal',
// FIXME: hardcode in v4
fontSize: token.fontSize,
lineHeight: token.lineHeight,
textAlign: `start`,
'&::after': {
content: descriptionItemTrailingColon ? '":"' : '" "',
position: 'relative',
// FIXME: hardcode in v4
top: -0.5,
marginInline: `${descriptionsItemLabelColonMarginLeft}px ${descriptionsItemLabelColonMarginRight}px`,
},
[`&${componentCls}-item-no-colon::after`]: {
content: '""',
},
},
[`${componentCls}-item-no-label`]: {
'&::after': {
margin: 0,
content: '""',
},
},
[`${componentCls}-item-content`]: {
display: 'table-cell',
flex: 1,
color: token.colorText,
// FIXME: hardcode in v4
fontSize: token.fontSize,
lineHeight: token.lineHeight,
wordBreak: 'break-word',
overflowWrap: 'break-word',
},
[`${componentCls}-item`]: {
paddingBottom: 0,
verticalAlign: 'top',
'&-container': {
display: 'flex',
[`${componentCls}-item-label`]: {
display: 'inline-flex',
alignItems: 'baseline',
},
[`${componentCls}-item-content`]: {
display: 'inline-flex',
alignItems: 'baseline',
},
},
},
[`${componentCls}-middle`]: {
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: token.paddingSM,
},
},
},
[`${componentCls}-small`]: {
[`${componentCls}-row`]: {
'> th, > td': {
// FIXME: hardcode in v4
paddingBottom: token.paddingXS,
},
},
},
},
};
};
// ============================== Export ==============================
export default genComponentStyleHook('Descriptions', token => {
const descriptionsBg = '#fafafa';
const descriptionsTitleMarginBottom = 20;
const descriptionsExtraColor = token.colorText;
const descriptionsSmallPadding = `${token.paddingXS}px ${token.padding}px`;
const descriptionsDefaultPadding = `${token.padding}px ${token.paddingLG}px`;
const descriptionsMiddlePadding = `${token.paddingSM}px ${token.paddingLG}px`;
const descriptionItemPaddingBottom = token.padding;
const descriptionItemTrailingColon = true;
const descriptionsItemLabelColonMarginRight = 8;
const descriptionsItemLabelColonMarginLeft = 2;
const descriptionToken = mergeToken<DescriptionsToken>(token, {
descriptionsBg,
descriptionsTitleMarginBottom,
descriptionsExtraColor,
descriptionItemPaddingBottom,
descriptionItemTrailingColon,
descriptionsSmallPadding,
descriptionsDefaultPadding,
descriptionsMiddlePadding,
descriptionsItemLabelColonMarginRight,
descriptionsItemLabelColonMarginLeft,
});
return [genDescriptionStyles(descriptionToken)];
});
| components/descriptions/style/index.tsx | 1 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.0032719450537115335,
0.0005731593118980527,
0.0001651506026973948,
0.00027577875880524516,
0.0007641643169336021
] |
{
"id": 2,
"code_window": [
" cursor: 'not-allowed',\n",
" },\n",
"\n",
" [`${componentCls}-btn`]: {\n",
" display: 'table',\n",
" height: '100%',\n",
" outline: 'none',\n",
" },\n",
"\n",
" [`${componentCls}-drag-container`]: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" width: '100%',\n"
],
"file_path": "components/upload/style/dragger.tsx",
"type": "add",
"edit_start_line_idx": 28
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Form Form item hidden noStyle should not work when hidden 1`] = `
<form
class="ant-form ant-form-horizontal"
>
<div
class="ant-row ant-form-item ant-form-item-hidden"
>
<div
class="ant-col ant-form-item-control"
>
<div
class="ant-form-item-control-input"
>
<div
class="ant-form-item-control-input-content"
>
<input
class="ant-input"
id="light"
type="text"
value=""
/>
</div>
</div>
</div>
</div>
</form>
`;
exports[`Form Form item hidden should work 1`] = `
<form
class="ant-form ant-form-horizontal"
>
<div
class="ant-row ant-form-item ant-form-item-hidden"
>
<div
class="ant-col ant-form-item-control"
>
<div
class="ant-form-item-control-input"
>
<div
class="ant-form-item-control-input-content"
>
<input
class="ant-input"
id="light"
type="text"
value=""
/>
</div>
</div>
</div>
</div>
</form>
`;
exports[`Form Form.Item should support data-*、aria-* and custom attribute 1`] = `
<form
class="ant-form ant-form-horizontal"
>
<div
aria-hidden="true"
cccc="bbbb"
class="ant-row ant-form-item"
data-text="123"
>
<div
class="ant-col ant-form-item-control"
>
<div
class="ant-form-item-control-input"
>
<div
class="ant-form-item-control-input-content"
>
text
</div>
</div>
</div>
</div>
</form>
`;
exports[`Form rtl render component should be rendered correctly in RTL direction 1`] = `
<form
class="ant-form ant-form-horizontal ant-form-rtl"
/>
`;
exports[`Form rtl render component should be rendered correctly in RTL direction 2`] = `
<div
class="ant-row ant-row-rtl ant-form-item"
>
<div
class="ant-col ant-form-item-control ant-col-rtl"
>
<div
class="ant-form-item-control-input"
>
<div
class="ant-form-item-control-input-content"
/>
</div>
</div>
</div>
`;
| components/form/__tests__/__snapshots__/index.test.js.snap | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017229699005838484,
0.00016807611973490566,
0.00016341950686182827,
0.00016822514589875937,
0.000002413424226688221
] |
{
"id": 2,
"code_window": [
" cursor: 'not-allowed',\n",
" },\n",
"\n",
" [`${componentCls}-btn`]: {\n",
" display: 'table',\n",
" height: '100%',\n",
" outline: 'none',\n",
" },\n",
"\n",
" [`${componentCls}-drag-container`]: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" width: '100%',\n"
],
"file_path": "components/upload/style/dragger.tsx",
"type": "add",
"edit_start_line_idx": 28
} | ---
category: Components
subtitle: 徽标数
type: 数据展示
title: Badge
cover: https://gw.alipayobjects.com/zos/antfincdn/6%26GF9WHwvY/Badge.svg
---
图标右上角的圆形徽标数字。
## 何时使用
一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。
## API
### Badge
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| color | 自定义小圆点的颜色 | string | - | |
| count | 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏 | ReactNode | - | |
| dot | 不展示数字,只有一个小红点 | boolean | false | |
| offset | 设置状态点的位置偏移 | \[number, number] | - | |
| overflowCount | 展示封顶的数字值 | number | 99 | |
| showZero | 当数值为 0 时,是否展示 Badge | boolean | false | |
| size | 在设置了 `count` 的前提下有效,设置小圆点的大小 | `default` \| `small` | - | 4.6.0 |
| status | 设置 Badge 为状态点 | `success` \| `processing` \| `default` \| `error` \| `warning` | - | |
| text | 在设置了 `status` 的前提下有效,设置状态点的文本 | ReactNode | - | |
| title | 设置鼠标放在状态点上时显示的文字 | string | - | |
### Badge.Ribbon (4.5.0+)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| color | 自定义缎带的颜色 | string | - | |
| placement | 缎带的位置,`start` 和 `end` 随文字方向(RTL 或 LTR)变动 | `start` \| `end` | `end` | |
| text | 缎带中填入的内容 | ReactNode | - | |
| components/badge/index.zh-CN.md | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.00017220943118445575,
0.00016939399938564748,
0.00016507456894032657,
0.0001701459987089038,
0.0000028790927899535745
] |
{
"id": 2,
"code_window": [
" cursor: 'not-allowed',\n",
" },\n",
"\n",
" [`${componentCls}-btn`]: {\n",
" display: 'table',\n",
" height: '100%',\n",
" outline: 'none',\n",
" },\n",
"\n",
" [`${componentCls}-drag-container`]: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" width: '100%',\n"
],
"file_path": "components/upload/style/dragger.tsx",
"type": "add",
"edit_start_line_idx": 28
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders ./components/card/demo/basic.md extend context correctly 1`] = `
Array [
<div
class="ant-card ant-card-bordered"
style="width:300px"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Default size card
</div>
<div
class="ant-card-extra"
>
<a
href="#"
>
More
</a>
</div>
</div>
</div>
<div
class="ant-card-body"
>
<p>
Card content
</p>
<p>
Card content
</p>
<p>
Card content
</p>
</div>
</div>,
<div
class="ant-card ant-card-bordered ant-card-small"
style="width:300px"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Small size card
</div>
<div
class="ant-card-extra"
>
<a
href="#"
>
More
</a>
</div>
</div>
</div>
<div
class="ant-card-body"
>
<p>
Card content
</p>
<p>
Card content
</p>
<p>
Card content
</p>
</div>
</div>,
]
`;
exports[`renders ./components/card/demo/border-less.md extend context correctly 1`] = `
<div
class="site-card-border-less-wrapper"
>
<div
class="ant-card"
style="width:300px"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card title
</div>
</div>
</div>
<div
class="ant-card-body"
>
<p>
Card content
</p>
<p>
Card content
</p>
<p>
Card content
</p>
</div>
</div>
</div>
`;
exports[`renders ./components/card/demo/flexible-content.md extend context correctly 1`] = `
<div
class="ant-card ant-card-bordered ant-card-hoverable"
style="width:240px"
>
<div
class="ant-card-cover"
>
<img
alt="example"
src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png"
/>
</div>
<div
class="ant-card-body"
>
<div
class="ant-card-meta"
>
<div
class="ant-card-meta-detail"
>
<div
class="ant-card-meta-title"
>
Europe Street beat
</div>
<div
class="ant-card-meta-description"
>
www.instagram.com
</div>
</div>
</div>
</div>
</div>
`;
exports[`renders ./components/card/demo/grid-card.md extend context correctly 1`] = `
<div
class="ant-card ant-card-bordered ant-card-contain-grid"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card Title
</div>
</div>
</div>
<div
class="ant-card-body"
>
<div
class="ant-card-grid ant-card-grid-hoverable"
style="width:25%;text-align:center"
>
Content
</div>
<div
class="ant-card-grid"
style="width:25%;text-align:center"
>
Content
</div>
<div
class="ant-card-grid ant-card-grid-hoverable"
style="width:25%;text-align:center"
>
Content
</div>
<div
class="ant-card-grid ant-card-grid-hoverable"
style="width:25%;text-align:center"
>
Content
</div>
<div
class="ant-card-grid ant-card-grid-hoverable"
style="width:25%;text-align:center"
>
Content
</div>
<div
class="ant-card-grid ant-card-grid-hoverable"
style="width:25%;text-align:center"
>
Content
</div>
<div
class="ant-card-grid ant-card-grid-hoverable"
style="width:25%;text-align:center"
>
Content
</div>
</div>
</div>
`;
exports[`renders ./components/card/demo/in-column.md extend context correctly 1`] = `
<div
class="site-card-wrapper"
>
<div
class="ant-row"
style="margin-left:-8px;margin-right:-8px"
>
<div
class="ant-col ant-col-8"
style="padding-left:8px;padding-right:8px"
>
<div
class="ant-card"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card title
</div>
</div>
</div>
<div
class="ant-card-body"
>
Card content
</div>
</div>
</div>
<div
class="ant-col ant-col-8"
style="padding-left:8px;padding-right:8px"
>
<div
class="ant-card"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card title
</div>
</div>
</div>
<div
class="ant-card-body"
>
Card content
</div>
</div>
</div>
<div
class="ant-col ant-col-8"
style="padding-left:8px;padding-right:8px"
>
<div
class="ant-card"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card title
</div>
</div>
</div>
<div
class="ant-card-body"
>
Card content
</div>
</div>
</div>
</div>
</div>
`;
exports[`renders ./components/card/demo/inner.md extend context correctly 1`] = `
<div
class="ant-card ant-card-bordered"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card title
</div>
</div>
</div>
<div
class="ant-card-body"
>
<div
class="ant-card ant-card-bordered ant-card-type-inner"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Inner Card title
</div>
<div
class="ant-card-extra"
>
<a
href="#"
>
More
</a>
</div>
</div>
</div>
<div
class="ant-card-body"
>
Inner Card content
</div>
</div>
<div
class="ant-card ant-card-bordered ant-card-type-inner"
style="margin-top:16px"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Inner Card title
</div>
<div
class="ant-card-extra"
>
<a
href="#"
>
More
</a>
</div>
</div>
</div>
<div
class="ant-card-body"
>
Inner Card content
</div>
</div>
</div>
</div>
`;
exports[`renders ./components/card/demo/loading.md extend context correctly 1`] = `
Array [
<button
aria-checked="false"
class="ant-switch"
role="switch"
type="button"
>
<div
class="ant-switch-handle"
/>
<span
class="ant-switch-inner"
/>
</button>,
<div
class="ant-card ant-card-loading ant-card-bordered"
style="width:300px;margin-top:16px"
>
<div
class="ant-card-body"
>
<div
class="ant-card-loading-content"
>
<div
class="ant-row"
style="margin-left:-4px;margin-right:-4px"
>
<div
class="ant-col ant-col-22"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
</div>
<div
class="ant-row"
style="margin-left:-4px;margin-right:-4px"
>
<div
class="ant-col ant-col-8"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
<div
class="ant-col ant-col-15"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
</div>
<div
class="ant-row"
style="margin-left:-4px;margin-right:-4px"
>
<div
class="ant-col ant-col-6"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
<div
class="ant-col ant-col-18"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
</div>
<div
class="ant-row"
style="margin-left:-4px;margin-right:-4px"
>
<div
class="ant-col ant-col-13"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
<div
class="ant-col ant-col-9"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
</div>
<div
class="ant-row"
style="margin-left:-4px;margin-right:-4px"
>
<div
class="ant-col ant-col-4"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
<div
class="ant-col ant-col-3"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
<div
class="ant-col ant-col-16"
style="padding-left:4px;padding-right:4px"
>
<div
class="ant-card-loading-block"
/>
</div>
</div>
</div>
</div>
</div>,
<div
class="ant-card ant-card-bordered"
style="width:300px;margin-top:16px"
>
<div
class="ant-card-body"
>
<div
class="ant-skeleton ant-skeleton-with-avatar ant-skeleton-active"
>
<div
class="ant-skeleton-header"
>
<span
class="ant-skeleton-avatar ant-skeleton-avatar-lg ant-skeleton-avatar-circle"
/>
</div>
<div
class="ant-skeleton-content"
>
<h3
class="ant-skeleton-title"
style="width:50%"
/>
<ul
class="ant-skeleton-paragraph"
>
<li />
<li />
</ul>
</div>
</div>
</div>
<ul
class="ant-card-actions"
>
<li
style="width:33.333333333333336%"
>
<span>
<span
aria-label="setting"
class="anticon anticon-setting"
role="img"
>
<svg
aria-hidden="true"
data-icon="setting"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M924.8 625.7l-65.5-56c3.1-19 4.7-38.4 4.7-57.8s-1.6-38.8-4.7-57.8l65.5-56a32.03 32.03 0 009.3-35.2l-.9-2.6a443.74 443.74 0 00-79.7-137.9l-1.8-2.1a32.12 32.12 0 00-35.1-9.5l-81.3 28.9c-30-24.6-63.5-44-99.7-57.6l-15.7-85a32.05 32.05 0 00-25.8-25.7l-2.7-.5c-52.1-9.4-106.9-9.4-159 0l-2.7.5a32.05 32.05 0 00-25.8 25.7l-15.8 85.4a351.86 351.86 0 00-99 57.4l-81.9-29.1a32 32 0 00-35.1 9.5l-1.8 2.1a446.02 446.02 0 00-79.7 137.9l-.9 2.6c-4.5 12.5-.8 26.5 9.3 35.2l66.3 56.6c-3.1 18.8-4.6 38-4.6 57.1 0 19.2 1.5 38.4 4.6 57.1L99 625.5a32.03 32.03 0 00-9.3 35.2l.9 2.6c18.1 50.4 44.9 96.9 79.7 137.9l1.8 2.1a32.12 32.12 0 0035.1 9.5l81.9-29.1c29.8 24.5 63.1 43.9 99 57.4l15.8 85.4a32.05 32.05 0 0025.8 25.7l2.7.5a449.4 449.4 0 00159 0l2.7-.5a32.05 32.05 0 0025.8-25.7l15.7-85a350 350 0 0099.7-57.6l81.3 28.9a32 32 0 0035.1-9.5l1.8-2.1c34.8-41.1 61.6-87.5 79.7-137.9l.9-2.6c4.5-12.3.8-26.3-9.3-35zM788.3 465.9c2.5 15.1 3.8 30.6 3.8 46.1s-1.3 31-3.8 46.1l-6.6 40.1 74.7 63.9a370.03 370.03 0 01-42.6 73.6L721 702.8l-31.4 25.8c-23.9 19.6-50.5 35-79.3 45.8l-38.1 14.3-17.9 97a377.5 377.5 0 01-85 0l-17.9-97.2-37.8-14.5c-28.5-10.8-55-26.2-78.7-45.7l-31.4-25.9-93.4 33.2c-17-22.9-31.2-47.6-42.6-73.6l75.5-64.5-6.5-40c-2.4-14.9-3.7-30.3-3.7-45.5 0-15.3 1.2-30.6 3.7-45.5l6.5-40-75.5-64.5c11.3-26.1 25.6-50.7 42.6-73.6l93.4 33.2 31.4-25.9c23.7-19.5 50.2-34.9 78.7-45.7l37.9-14.3 17.9-97.2c28.1-3.2 56.8-3.2 85 0l17.9 97 38.1 14.3c28.7 10.8 55.4 26.2 79.3 45.8l31.4 25.8 92.8-32.9c17 22.9 31.2 47.6 42.6 73.6L781.8 426l6.5 39.9zM512 326c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm79.2 255.2A111.6 111.6 0 01512 614c-29.9 0-58-11.7-79.2-32.8A111.6 111.6 0 01400 502c0-29.9 11.7-58 32.8-79.2C454 401.6 482.1 390 512 390c29.9 0 58 11.6 79.2 32.8A111.6 111.6 0 01624 502c0 29.9-11.7 58-32.8 79.2z"
/>
</svg>
</span>
</span>
</li>
<li
style="width:33.333333333333336%"
>
<span>
<span
aria-label="edit"
class="anticon anticon-edit"
role="img"
>
<svg
aria-hidden="true"
data-icon="edit"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M257.7 752c2 0 4-.2 6-.5L431.9 722c2-.4 3.9-1.3 5.3-2.8l423.9-423.9a9.96 9.96 0 000-14.1L694.9 114.9c-1.9-1.9-4.4-2.9-7.1-2.9s-5.2 1-7.1 2.9L256.8 538.8c-1.5 1.5-2.4 3.3-2.8 5.3l-29.5 168.2a33.5 33.5 0 009.4 29.8c6.6 6.4 14.9 9.9 23.8 9.9zm67.4-174.4L687.8 215l73.3 73.3-362.7 362.6-88.9 15.7 15.6-89zM880 836H144c-17.7 0-32 14.3-32 32v36c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-36c0-17.7-14.3-32-32-32z"
/>
</svg>
</span>
</span>
</li>
<li
style="width:33.333333333333336%"
>
<span>
<span
aria-label="ellipsis"
class="anticon anticon-ellipsis"
role="img"
>
<svg
aria-hidden="true"
data-icon="ellipsis"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"
/>
</svg>
</span>
</span>
</li>
</ul>
</div>,
]
`;
exports[`renders ./components/card/demo/meta.md extend context correctly 1`] = `
<div
class="ant-card ant-card-bordered"
style="width:300px"
>
<div
class="ant-card-cover"
>
<img
alt="example"
src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
/>
</div>
<div
class="ant-card-body"
>
<div
class="ant-card-meta"
>
<div
class="ant-card-meta-avatar"
>
<span
class="ant-avatar ant-avatar-circle ant-avatar-image"
>
<img
src="https://joeschmoe.io/api/v1/random"
/>
</span>
</div>
<div
class="ant-card-meta-detail"
>
<div
class="ant-card-meta-title"
>
Card title
</div>
<div
class="ant-card-meta-description"
>
This is the description
</div>
</div>
</div>
</div>
<ul
class="ant-card-actions"
>
<li
style="width:33.333333333333336%"
>
<span>
<span
aria-label="setting"
class="anticon anticon-setting"
role="img"
>
<svg
aria-hidden="true"
data-icon="setting"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M924.8 625.7l-65.5-56c3.1-19 4.7-38.4 4.7-57.8s-1.6-38.8-4.7-57.8l65.5-56a32.03 32.03 0 009.3-35.2l-.9-2.6a443.74 443.74 0 00-79.7-137.9l-1.8-2.1a32.12 32.12 0 00-35.1-9.5l-81.3 28.9c-30-24.6-63.5-44-99.7-57.6l-15.7-85a32.05 32.05 0 00-25.8-25.7l-2.7-.5c-52.1-9.4-106.9-9.4-159 0l-2.7.5a32.05 32.05 0 00-25.8 25.7l-15.8 85.4a351.86 351.86 0 00-99 57.4l-81.9-29.1a32 32 0 00-35.1 9.5l-1.8 2.1a446.02 446.02 0 00-79.7 137.9l-.9 2.6c-4.5 12.5-.8 26.5 9.3 35.2l66.3 56.6c-3.1 18.8-4.6 38-4.6 57.1 0 19.2 1.5 38.4 4.6 57.1L99 625.5a32.03 32.03 0 00-9.3 35.2l.9 2.6c18.1 50.4 44.9 96.9 79.7 137.9l1.8 2.1a32.12 32.12 0 0035.1 9.5l81.9-29.1c29.8 24.5 63.1 43.9 99 57.4l15.8 85.4a32.05 32.05 0 0025.8 25.7l2.7.5a449.4 449.4 0 00159 0l2.7-.5a32.05 32.05 0 0025.8-25.7l15.7-85a350 350 0 0099.7-57.6l81.3 28.9a32 32 0 0035.1-9.5l1.8-2.1c34.8-41.1 61.6-87.5 79.7-137.9l.9-2.6c4.5-12.3.8-26.3-9.3-35zM788.3 465.9c2.5 15.1 3.8 30.6 3.8 46.1s-1.3 31-3.8 46.1l-6.6 40.1 74.7 63.9a370.03 370.03 0 01-42.6 73.6L721 702.8l-31.4 25.8c-23.9 19.6-50.5 35-79.3 45.8l-38.1 14.3-17.9 97a377.5 377.5 0 01-85 0l-17.9-97.2-37.8-14.5c-28.5-10.8-55-26.2-78.7-45.7l-31.4-25.9-93.4 33.2c-17-22.9-31.2-47.6-42.6-73.6l75.5-64.5-6.5-40c-2.4-14.9-3.7-30.3-3.7-45.5 0-15.3 1.2-30.6 3.7-45.5l6.5-40-75.5-64.5c11.3-26.1 25.6-50.7 42.6-73.6l93.4 33.2 31.4-25.9c23.7-19.5 50.2-34.9 78.7-45.7l37.9-14.3 17.9-97.2c28.1-3.2 56.8-3.2 85 0l17.9 97 38.1 14.3c28.7 10.8 55.4 26.2 79.3 45.8l31.4 25.8 92.8-32.9c17 22.9 31.2 47.6 42.6 73.6L781.8 426l6.5 39.9zM512 326c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176zm79.2 255.2A111.6 111.6 0 01512 614c-29.9 0-58-11.7-79.2-32.8A111.6 111.6 0 01400 502c0-29.9 11.7-58 32.8-79.2C454 401.6 482.1 390 512 390c29.9 0 58 11.6 79.2 32.8A111.6 111.6 0 01624 502c0 29.9-11.7 58-32.8 79.2z"
/>
</svg>
</span>
</span>
</li>
<li
style="width:33.333333333333336%"
>
<span>
<span
aria-label="edit"
class="anticon anticon-edit"
role="img"
>
<svg
aria-hidden="true"
data-icon="edit"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M257.7 752c2 0 4-.2 6-.5L431.9 722c2-.4 3.9-1.3 5.3-2.8l423.9-423.9a9.96 9.96 0 000-14.1L694.9 114.9c-1.9-1.9-4.4-2.9-7.1-2.9s-5.2 1-7.1 2.9L256.8 538.8c-1.5 1.5-2.4 3.3-2.8 5.3l-29.5 168.2a33.5 33.5 0 009.4 29.8c6.6 6.4 14.9 9.9 23.8 9.9zm67.4-174.4L687.8 215l73.3 73.3-362.7 362.6-88.9 15.7 15.6-89zM880 836H144c-17.7 0-32 14.3-32 32v36c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-36c0-17.7-14.3-32-32-32z"
/>
</svg>
</span>
</span>
</li>
<li
style="width:33.333333333333336%"
>
<span>
<span
aria-label="ellipsis"
class="anticon anticon-ellipsis"
role="img"
>
<svg
aria-hidden="true"
data-icon="ellipsis"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"
/>
</svg>
</span>
</span>
</li>
</ul>
</div>
`;
exports[`renders ./components/card/demo/simple.md extend context correctly 1`] = `
<div
class="ant-card ant-card-bordered"
style="width:300px"
>
<div
class="ant-card-body"
>
<p>
Card content
</p>
<p>
Card content
</p>
<p>
Card content
</p>
</div>
</div>
`;
exports[`renders ./components/card/demo/tabs.md extend context correctly 1`] = `
Array [
<div
class="ant-card ant-card-bordered ant-card-contain-tabs"
style="width:100%"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
>
<div
class="ant-card-head-title"
>
Card title
</div>
<div
class="ant-card-extra"
>
<a
href="#"
>
More
</a>
</div>
</div>
<div
class="ant-tabs ant-tabs-top ant-tabs-large ant-card-head-tabs"
>
<div
class="ant-tabs-nav"
role="tablist"
>
<div
class="ant-tabs-nav-wrap"
>
<div
class="ant-tabs-nav-list"
style="transform:translate(0px, 0px)"
>
<div
class="ant-tabs-tab ant-tabs-tab-active"
>
<div
aria-selected="true"
class="ant-tabs-tab-btn"
role="tab"
tabindex="0"
>
tab1
</div>
</div>
<div
class="ant-tabs-tab"
>
<div
aria-selected="false"
class="ant-tabs-tab-btn"
role="tab"
tabindex="0"
>
tab2
</div>
</div>
<div
class="ant-tabs-ink-bar ant-tabs-ink-bar-animated"
/>
</div>
</div>
<div
class="ant-tabs-nav-operations ant-tabs-nav-operations-hidden"
>
<button
aria-controls="null-more-popup"
aria-expanded="false"
aria-haspopup="listbox"
aria-hidden="true"
class="ant-tabs-nav-more"
id="null-more"
style="visibility:hidden;order:1"
tabindex="-1"
type="button"
>
<span
aria-label="ellipsis"
class="anticon anticon-ellipsis"
role="img"
>
<svg
aria-hidden="true"
data-icon="ellipsis"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"
/>
</svg>
</span>
</button>
<div>
<div
class="ant-tabs-dropdown"
style="opacity:0"
>
<ul
aria-label="expanded dropdown"
class="ant-tabs-dropdown-menu ant-tabs-dropdown-menu-root ant-tabs-dropdown-menu-vertical"
data-dropdown-inject="true"
data-menu-list="true"
id="null-more-popup"
role="listbox"
tabindex="-1"
/>
<div
aria-hidden="true"
style="display:none"
/>
</div>
</div>
</div>
</div>
<div
class="ant-tabs-content-holder"
>
<div
class="ant-tabs-content ant-tabs-content-top"
>
<div
aria-hidden="false"
class="ant-tabs-tabpane ant-tabs-tabpane-active"
role="tabpanel"
tabindex="0"
/>
<div
aria-hidden="true"
class="ant-tabs-tabpane"
role="tabpanel"
style="display:none"
tabindex="-1"
/>
</div>
</div>
</div>
</div>
<div
class="ant-card-body"
>
<p>
content1
</p>
</div>
</div>,
<br />,
<br />,
<div
class="ant-card ant-card-bordered ant-card-contain-tabs"
style="width:100%"
>
<div
class="ant-card-head"
>
<div
class="ant-card-head-wrapper"
/>
<div
class="ant-tabs ant-tabs-top ant-tabs-large ant-card-head-tabs"
>
<div
class="ant-tabs-nav"
role="tablist"
>
<div
class="ant-tabs-nav-wrap"
>
<div
class="ant-tabs-nav-list"
style="transform:translate(0px, 0px)"
>
<div
class="ant-tabs-tab"
>
<div
aria-selected="false"
class="ant-tabs-tab-btn"
role="tab"
tabindex="0"
>
article
</div>
</div>
<div
class="ant-tabs-tab ant-tabs-tab-active"
>
<div
aria-selected="true"
class="ant-tabs-tab-btn"
role="tab"
tabindex="0"
>
app
</div>
</div>
<div
class="ant-tabs-tab"
>
<div
aria-selected="false"
class="ant-tabs-tab-btn"
role="tab"
tabindex="0"
>
project
</div>
</div>
<div
class="ant-tabs-ink-bar ant-tabs-ink-bar-animated"
/>
</div>
</div>
<div
class="ant-tabs-nav-operations ant-tabs-nav-operations-hidden"
>
<button
aria-controls="null-more-popup"
aria-expanded="false"
aria-haspopup="listbox"
aria-hidden="true"
class="ant-tabs-nav-more"
id="null-more"
style="visibility:hidden;order:1"
tabindex="-1"
type="button"
>
<span
aria-label="ellipsis"
class="anticon anticon-ellipsis"
role="img"
>
<svg
aria-hidden="true"
data-icon="ellipsis"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"
/>
</svg>
</span>
</button>
<div>
<div
class="ant-tabs-dropdown"
style="opacity:0"
>
<ul
aria-label="expanded dropdown"
class="ant-tabs-dropdown-menu ant-tabs-dropdown-menu-root ant-tabs-dropdown-menu-vertical"
data-dropdown-inject="true"
data-menu-list="true"
id="null-more-popup"
role="listbox"
tabindex="-1"
/>
<div
aria-hidden="true"
style="display:none"
/>
</div>
</div>
</div>
<div
class="ant-tabs-extra-content"
>
<a
href="#"
>
More
</a>
</div>
</div>
<div
class="ant-tabs-content-holder"
>
<div
class="ant-tabs-content ant-tabs-content-top"
>
<div
aria-hidden="true"
class="ant-tabs-tabpane"
role="tabpanel"
style="display:none"
tabindex="-1"
/>
<div
aria-hidden="false"
class="ant-tabs-tabpane ant-tabs-tabpane-active"
role="tabpanel"
tabindex="0"
/>
<div
aria-hidden="true"
class="ant-tabs-tabpane"
role="tabpanel"
style="display:none"
tabindex="-1"
/>
</div>
</div>
</div>
</div>
<div
class="ant-card-body"
>
<p>
app content
</p>
</div>
</div>,
]
`;
| components/card/__tests__/__snapshots__/demo-extend.test.ts.snap | 0 | https://github.com/ant-design/ant-design/commit/9169de21f8fa0f5c89a49fa6b3c8898fefc1b910 | [
0.0005585254402831197,
0.0001769349619280547,
0.00016336185217369348,
0.00016912282444536686,
0.000043739768443629146
] |
{
"id": 0,
"code_window": [
" for (const s of symbols) {\n",
" if (s.name.startsWith('__') || !s.public || this.completions.has(s.name)) {\n",
" continue;\n",
" }\n",
" this.completions.set(s.name, {\n",
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" // The pipe method should not include parentheses.\n",
" // e.g. {{ value_expression | slice : start [ : end ] }}\n",
" const shouldInsertParentheses = s.callable && s.kind !== ng.CompletionKind.PIPE;\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "add",
"edit_start_line_idx": 471
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {createLanguageService} from '../src/language_service';
import {CompletionKind} from '../src/types';
import {TypeScriptServiceHost} from '../src/typescript_host';
import {MockTypescriptHost} from './test_utils';
const APP_COMPONENT = '/app/app.component.ts';
const PARSING_CASES = '/app/parsing-cases.ts';
const TEST_TEMPLATE = '/app/test.ng';
const EXPRESSION_CASES = '/app/expression-cases.ts';
describe('completions', () => {
const mockHost = new MockTypescriptHost(['/app/main.ts']);
const tsLS = ts.createLanguageService(mockHost);
const ngHost = new TypeScriptServiceHost(mockHost, tsLS);
const ngLS = createLanguageService(ngHost);
beforeEach(() => { mockHost.reset(); });
it('should be able to get entity completions', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'entity-amp');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);
});
it('should be able to return html elements', () => {
const locations = ['empty', 'start-tag-h1', 'h1-content', 'start-tag', 'start-tag-after-h'];
for (const location of locations) {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, location);
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.HTML_ELEMENT, ['div', 'h1', 'h2', 'span']);
}
});
it('should be able to return component directives', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'empty');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.COMPONENT, [
'ng-form',
'my-app',
'ng-component',
'test-comp',
]);
});
it('should be able to return attribute directives', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h1-after-space');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, ['string-model', 'number-model']);
});
it('should be able to return angular pseudo elements', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'empty');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ANGULAR_ELEMENT, [
'ng-container',
'ng-content',
'ng-template',
]);
});
it('should be able to return h1 attributes', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h1-after-space');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.HTML_ATTRIBUTE, [
'class',
'id',
'onclick',
'onmouseup',
]);
});
it('should be able to find common Angular attributes', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'div-attributes');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, [
'ngClass',
'ngForm',
'ngModel',
'string-model',
'number-model',
]);
});
it('should be able to get the completions at the beginning of an interpolation', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h2-hero');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'hero']);
});
it('should not include private members of a class', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h2-hero');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expect(completions).toBeDefined();
const internal = completions !.entries.find(e => e.name === 'internal');
expect(internal).toBeUndefined();
});
it('should be able to get the completions at the end of an interpolation', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'sub-end');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'hero']);
});
it('should be able to get the completions in a property', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h2-name');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should suggest template references', () => {
mockHost.override(TEST_TEMPLATE, `<div *~{cursor}></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, [
'ngFor',
'ngForOf',
'ngIf',
'ngSwitchCase',
'ngSwitchDefault',
'ngPluralCase',
]);
});
it('should be able to return attribute names with an incomplete attribute', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'no-value-attribute');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.HTML_ATTRIBUTE, ['id', 'class', 'dir', 'lang']);
});
it('should be able to return attributes of an incomplete element', () => {
const m1 = mockHost.getLocationMarkerFor(PARSING_CASES, 'incomplete-open-lt');
const c1 = ngLS.getCompletionsAt(PARSING_CASES, m1.start);
expectContain(c1, CompletionKind.HTML_ELEMENT, ['a', 'div', 'p', 'span']);
const m2 = mockHost.getLocationMarkerFor(PARSING_CASES, 'incomplete-open-a');
const c2 = ngLS.getCompletionsAt(PARSING_CASES, m2.start);
expectContain(c2, CompletionKind.HTML_ELEMENT, ['a', 'div', 'p', 'span']);
const m3 = mockHost.getLocationMarkerFor(PARSING_CASES, 'incomplete-open-attr');
const c3 = ngLS.getCompletionsAt(PARSING_CASES, m3.start);
expectContain(c3, CompletionKind.HTML_ATTRIBUTE, ['id', 'class', 'href', 'name']);
});
it('should be able to return completions with a missing closing tag', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'missing-closing');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.HTML_ELEMENT, ['a', 'div', 'p', 'span', 'h1', 'h2']);
});
it('should be able to return common attributes of an unknown tag', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'unknown-element');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.HTML_ATTRIBUTE, ['id', 'dir', 'lang']);
});
it('should be able to get completions in an empty interpolation', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'empty-interpolation');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'subTitle']);
});
it('should suggest $any() type cast function in an interpolation', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'sub-start');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.METHOD, ['$any']);
});
it('should suggest attribute values', () => {
mockHost.override(TEST_TEMPLATE, `<div [id]="~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, [
'title',
'hero',
'heroes',
'league',
'anyValue',
]);
});
it('should suggest event handlers', () => {
mockHost.override(TEST_TEMPLATE, `<div (click)="~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.METHOD, ['myClick']);
});
it('for methods should include parentheses', () => {
mockHost.override(TEST_TEMPLATE, `<div (click)="~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeDefined();
expect(completions !.entries).toContain(jasmine.objectContaining({
name: 'myClick',
kind: CompletionKind.METHOD as any,
insertText: 'myClick()',
}));
});
describe('in external template', () => {
it('should be able to get entity completions in external template', () => {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'entity-amp');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);
});
it('should not return html elements', () => {
const locations = ['empty', 'start-tag-h1', 'h1-content', 'start-tag', 'start-tag-after-h'];
for (const location of locations) {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, location);
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeDefined();
const {entries} = completions !;
expect(entries).not.toContain(jasmine.objectContaining({name: 'div'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'h1'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'h2'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'span'}));
}
});
it('should be able to return element directives', () => {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'empty');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.COMPONENT, [
'ng-form',
'my-app',
'ng-component',
'test-comp',
]);
});
it('should not return html attributes', () => {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'h1-after-space');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeDefined();
const {entries} = completions !;
expect(entries).not.toContain(jasmine.objectContaining({name: 'class'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'id'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'onclick'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'onmouseup'}));
});
it('should be able to find common Angular attributes', () => {
mockHost.override(TEST_TEMPLATE, `<div ~{cursor}></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, [
'ngClass',
'ngForm',
'ngModel',
'string-model',
'number-model',
]);
});
});
describe('with a *ngIf', () => {
it('should be able to get completions for exported *ngIf variable', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'promised-person-name');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['name', 'age', 'street']);
});
});
describe('with a *ngFor', () => {
it('should suggest NgForRow members for let initialization expression', () => {
mockHost.override(TEST_TEMPLATE, `<div *ngFor="let i=~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, [
'$implicit',
'ngForOf',
'index',
'count',
'first',
'last',
'even',
'odd',
]);
});
it('should not provide suggestion before the = sign', () => {
mockHost.override(TEST_TEMPLATE, `<div *ngFor="let i~{cursor}="></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeUndefined();
});
it('should include field reference', () => {
mockHost.override(TEST_TEMPLATE, `<div *ngFor="let x of ~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'heroes', 'league']);
// the symbol 'x' declared in *ngFor is also in scope. This asserts that
// we are actually taking the AST into account and not just referring to
// the symbol table of the Component.
expectContain(completions, CompletionKind.VARIABLE, ['x']);
});
it('should include variable in the let scope in interpolation', () => {
mockHost.override(TEST_TEMPLATE, `
<div *ngFor="let h of heroes">
{{~{cursor}}}
</div>
`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.VARIABLE, ['h']);
});
it('should be able to infer the type of a ngForOf', () => {
mockHost.override(TEST_TEMPLATE, `
<div *ngFor="let h of heroes">
{{ h.~{cursor} }}
</div>
`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should be able to infer the type of a ngForOf with an async pipe', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'async-person-name');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['name', 'age', 'street']);
});
it('should be able to resolve variable in nested loop', () => {
mockHost.override(TEST_TEMPLATE, `
<div *ngFor="let leagueMembers of league">
<div *ngFor="let member of leagueMembers">
{{member.~{position}}}
</div>
</div>
`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'position');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
// member variable of type Hero has properties 'id' and 'name'.
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
});
describe('data binding', () => {
it('should be able to complete property value', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'property-binding-model');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['test']);
});
it('should be able to complete an event', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'event-binding-model');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.METHOD, ['modelChanged']);
});
it('should be able to complete a the LHS of a two-way binding', () => {
mockHost.override(TEST_TEMPLATE, `<div [(~{cursor})]></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, ['ngModel']);
});
it('should be able to complete a the RHS of a two-way binding', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'two-way-binding-model');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['test']);
});
it('should suggest property binding for input', () => {
// Property binding via []
mockHost.override(TEST_TEMPLATE, `<div number-model [~{cursor}]></div>`);
const m1 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c1 = ngLS.getCompletionsAt(TEST_TEMPLATE, m1.start);
expectContain(c1, CompletionKind.ATTRIBUTE, ['inputAlias']);
// Property binding via bind-
mockHost.override(TEST_TEMPLATE, `<div number-model bind-~{cursor}></div>`);
const m2 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c2 = ngLS.getCompletionsAt(TEST_TEMPLATE, m2.start);
expectContain(c2, CompletionKind.ATTRIBUTE, ['inputAlias']);
});
it('should suggest event binding for output', () => {
// Event binding via ()
mockHost.override(TEST_TEMPLATE, `<div number-model (~{cursor})></div>`);
const m1 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c1 = ngLS.getCompletionsAt(TEST_TEMPLATE, m1.start);
expectContain(c1, CompletionKind.ATTRIBUTE, ['outputAlias']);
// Event binding via on-
mockHost.override(TEST_TEMPLATE, `<div number-mode on-~{cursor}></div>`);
const m2 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c2 = ngLS.getCompletionsAt(TEST_TEMPLATE, m2.start);
expectContain(c2, CompletionKind.ATTRIBUTE, ['outputAlias']);
});
it('should suggest two-way binding for input and output', () => {
// Banana-in-a-box via [()]
mockHost.override(TEST_TEMPLATE, `<div string-model [(~{cursor})]></div>`);
const m1 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c1 = ngLS.getCompletionsAt(TEST_TEMPLATE, m1.start);
expectContain(c1, CompletionKind.ATTRIBUTE, ['model']);
// Banana-in-a-box via bindon-
mockHost.override(TEST_TEMPLATE, `<div string-model bindon-~{cursor}></div>`);
const m2 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c2 = ngLS.getCompletionsAt(TEST_TEMPLATE, m2.start);
expectContain(c2, CompletionKind.ATTRIBUTE, ['model']);
});
});
describe('for pipes', () => {
it('should be able to get a list of pipe values', () => {
for (const location of ['before-pipe', 'in-pipe', 'after-pipe']) {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, location);
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PIPE, [
'async',
'uppercase',
'lowercase',
'titlecase',
]);
}
});
it('should be able to resolve lowercase', () => {
const marker = mockHost.getLocationMarkerFor(EXPRESSION_CASES, 'string-pipe');
const completions = ngLS.getCompletionsAt(EXPRESSION_CASES, marker.start);
expectContain(completions, CompletionKind.METHOD, [
'charAt',
'replace',
'substring',
'toLowerCase',
]);
});
});
describe('with references', () => {
it('should list references', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'test-comp-content');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.REFERENCE, ['div', 'test1', 'test2']);
});
it('should reference the component', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'test-comp-after-test');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['name', 'testEvent']);
});
// TODO: Enable when we have a flag that indicates the project targets the DOM
// it('should reference the element if no component', () => {
// const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'test-comp-after-div');
// const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
// expectContain(completions, CompletionKind.PROPERTY, ['innerText']);
// });
});
describe('replacement span', () => {
it('should not generate replacement entries for zero-length replacements', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div>{{obj.~{key}}}</div>
\`,
})
export class FooComponent {
obj: {key: 'value'};
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'key');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'key') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('property');
expect(completion.replacementSpan).toBeUndefined();
});
it('should work for start of template', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`~{start}abc\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'start');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'acronym') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('html element');
expect(completion.replacementSpan).toEqual({start: location.start, length: 3});
});
it('should work for end of template', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`acro~{end}\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'end');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'acronym') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('html element');
expect(completion.replacementSpan).toEqual({start: location.start - 4, length: 4});
});
it('should work for middle-word replacements', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div>{{obj.ke~{key}key}}</div>
\`,
})
export class FooComponent {
obj: {key: 'value'};
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'key');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'key') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('property');
expect(completion.replacementSpan).toEqual({start: location.start - 2, length: 5});
});
it('should work for all kinds of identifier characters', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div>{{~{field}$title_1}}</div>
\`,
})
export class FooComponent {
$title_1: string;
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'field');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === '$title_1') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('property');
expect(completion.replacementSpan).toEqual({start: location.start, length: 8});
});
it('should work for attributes', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div (cl~{click})></div>
\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'click');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'click') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe(CompletionKind.ATTRIBUTE);
expect(completion.replacementSpan).toEqual({start: location.start - 2, length: 2});
});
it('should work for events', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div (click)="han~{handleClick}"></div>
\`,
})
export class FooComponent {
handleClick() {}
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'handleClick');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'handleClick') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('method');
expect(completion.replacementSpan).toEqual({start: location.start - 3, length: 3});
});
it('should work for element names', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<di~{div}></div>
\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'div');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'div') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('html element');
expect(completion.replacementSpan).toEqual({start: location.start - 2, length: 2});
});
it('should work for bindings', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<input [(ngMod~{model})] />
\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'model');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'ngModel') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe(CompletionKind.ATTRIBUTE);
expect(completion.replacementSpan).toEqual({start: location.start - 5, length: 5});
});
});
describe('property completions for members of an indexed type', () => {
it('should work with numeric index signatures (arrays)', () => {
mockHost.override(TEST_TEMPLATE, `{{ heroes[0].~{heroes-number-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'heroes-number-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should work with numeric index signatures (tuple arrays)', () => {
mockHost.override(TEST_TEMPLATE, `{{ tupleArray[1].~{tuple-array-number-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'tuple-array-number-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
describe('with string index signatures', () => {
it('should work with index notation', () => {
mockHost.override(TEST_TEMPLATE, `{{ heroesByName['Jacky'].~{heroes-string-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'heroes-string-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should work with dot notation', () => {
mockHost.override(TEST_TEMPLATE, `{{ heroesByName.jacky.~{heroes-string-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'heroes-string-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should work with dot notation if stringIndexType is a primitive type', () => {
mockHost.override(TEST_TEMPLATE, `{{ primitiveIndexType.test.~{string-primitive-type}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'string-primitive-type');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.METHOD, ['substring']);
});
});
});
});
function expectContain(
completions: ts.CompletionInfo | undefined, kind: CompletionKind, names: string[]) {
expect(completions).toBeDefined();
for (const name of names) {
expect(completions !.entries).toContain(jasmine.objectContaining({ name, kind } as any));
}
}
| packages/language-service/test/completions_spec.ts | 1 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.0047570825554430485,
0.0006807242752984166,
0.0001641256531002,
0.0002887764130719006,
0.000914798176381737
] |
{
"id": 0,
"code_window": [
" for (const s of symbols) {\n",
" if (s.name.startsWith('__') || !s.public || this.completions.has(s.name)) {\n",
" continue;\n",
" }\n",
" this.completions.set(s.name, {\n",
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" // The pipe method should not include parentheses.\n",
" // e.g. {{ value_expression | slice : start [ : end ] }}\n",
" const shouldInsertParentheses = s.callable && s.kind !== ng.CompletionKind.PIPE;\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "add",
"edit_start_line_idx": 471
} | {
"e2e": [
{
"cmd": "yarn",
"args": [ "tsc", "--project", "./" ]
}
]
}
| aio/content/examples/observables-in-angular/example-config.json | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.0001741563028190285,
0.0001741563028190285,
0.0001741563028190285,
0.0001741563028190285,
0
] |
{
"id": 0,
"code_window": [
" for (const s of symbols) {\n",
" if (s.name.startsWith('__') || !s.public || this.completions.has(s.name)) {\n",
" continue;\n",
" }\n",
" this.completions.set(s.name, {\n",
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" // The pipe method should not include parentheses.\n",
" // e.g. {{ value_expression | slice : start [ : end ] }}\n",
" const shouldInsertParentheses = s.callable && s.kind !== ng.CompletionKind.PIPE;\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "add",
"edit_start_line_idx": 471
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {InjectionToken} from '../di/injection_token';
import {ViewEncapsulation} from '../metadata/view';
import {injectRenderer2 as render3InjectRenderer2} from '../render3/view_engine_compatibility';
import {noop} from '../util/noop';
export const Renderer2Interceptor = new InjectionToken<Renderer2[]>('Renderer2Interceptor');
/**
* Used by `RendererFactory2` to associate custom rendering data and styles
* with a rendering implementation.
* @publicApi
*/
export interface RendererType2 {
/**
* A unique identifying string for the new renderer, used when creating
* unique styles for encapsulation.
*/
id: string;
/**
* The view encapsulation type, which determines how styles are applied to
* DOM elements. One of
* - `Emulated` (default): Emulate native scoping of styles.
* - `Native`: Use the native encapsulation mechanism of the renderer.
* - `ShadowDom`: Use modern [Shadow
* DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
* create a ShadowRoot for component's host element.
* - `None`: Do not provide any template or style encapsulation.
*/
encapsulation: ViewEncapsulation;
/**
* Defines CSS styles to be stored on a renderer instance.
*/
styles: (string|any[])[];
/**
* Defines arbitrary developer-defined data to be stored on a renderer instance.
* This is useful for renderers that delegate to other renderers.
*/
data: {[kind: string]: any};
}
/**
* Creates and initializes a custom renderer that implements the `Renderer2` base class.
*
* @publicApi
*/
export abstract class RendererFactory2 {
/**
* Creates and initializes a custom renderer for a host DOM element.
* @param hostElement The element to render.
* @param type The base class to implement.
* @returns The new custom renderer instance.
*/
abstract createRenderer(hostElement: any, type: RendererType2|null): Renderer2;
/**
* A callback invoked when rendering has begun.
*/
abstract begin?(): void;
/**
* A callback invoked when rendering has completed.
*/
abstract end?(): void;
/**
* Use with animations test-only mode. Notifies the test when rendering has completed.
* @returns The asynchronous result of the developer-defined function.
*/
abstract whenRenderingDone?(): Promise<any>;
}
/**
* Flags for renderer-specific style modifiers.
* @publicApi
*/
export enum RendererStyleFlags2 {
/**
* Marks a style as important.
*/
Important = 1 << 0,
/**
* Marks a style as using dash case naming (this-is-dash-case).
*/
DashCase = 1 << 1
}
/**
* Extend this base class to implement custom rendering. By default, Angular
* renders a template into DOM. You can use custom rendering to intercept
* rendering calls, or to render to something other than DOM.
*
* Create your custom renderer using `RendererFactory2`.
*
* Use a custom renderer to bypass Angular's templating and
* make custom UI changes that can't be expressed declaratively.
* For example if you need to set a property or an attribute whose name is
* not statically known, use the `setProperty()` or
* `setAttribute()` method.
*
* @publicApi
*/
export abstract class Renderer2 {
/**
* Use to store arbitrary developer-defined data on a renderer instance,
* as an object containing key-value pairs.
* This is useful for renderers that delegate to other renderers.
*/
abstract get data(): {[key: string]: any};
/**
* Implement this callback to destroy the renderer or the host element.
*/
abstract destroy(): void;
/**
* Implement this callback to create an instance of the host element.
* @param name An identifying name for the new element, unique within the namespace.
* @param namespace The namespace for the new element.
* @returns The new element.
*/
abstract createElement(name: string, namespace?: string|null): any;
/**
* Implement this callback to add a comment to the DOM of the host element.
* @param value The comment text.
* @returns The modified element.
*/
abstract createComment(value: string): any;
/**
* Implement this callback to add text to the DOM of the host element.
* @param value The text string.
* @returns The modified element.
*/
abstract createText(value: string): any;
/**
* If null or undefined, the view engine won't call it.
* This is used as a performance optimization for production mode.
*/
// TODO(issue/24571): remove '!'.
destroyNode !: ((node: any) => void) | null;
/**
* Appends a child to a given parent node in the host element DOM.
* @param parent The parent node.
* @param newChild The new child node.
*/
abstract appendChild(parent: any, newChild: any): void;
/**
* Implement this callback to insert a child node at a given position in a parent node
* in the host element DOM.
* @param parent The parent node.
* @param newChild The new child nodes.
* @param refChild The existing child node that should precede the new node.
*/
abstract insertBefore(parent: any, newChild: any, refChild: any): void;
/**
* Implement this callback to remove a child node from the host element's DOM.
* @param parent The parent node.
* @param oldChild The child node to remove.
* @param isHostElement Optionally signal to the renderer whether this element is a host element
* or not
*/
abstract removeChild(parent: any, oldChild: any, isHostElement?: boolean): void;
/**
* Implement this callback to prepare an element to be bootstrapped
* as a root element, and return the element instance.
* @param selectorOrNode The DOM element.
* @param preserveContent Whether the contents of the root element
* should be preserved, or cleared upon bootstrap (default behavior).
* Use with `ViewEncapsulation.ShadowDom` to allow simple native
* content projection via `<slot>` elements.
* @returns The root element.
*/
abstract selectRootElement(selectorOrNode: string|any, preserveContent?: boolean): any;
/**
* Implement this callback to get the parent of a given node
* in the host element's DOM.
* @param node The child node to query.
* @returns The parent node, or null if there is no parent.
* For WebWorkers, always returns true.
* This is because the check is synchronous,
* and the caller can't rely on checking for null.
*/
abstract parentNode(node: any): any;
/**
* Implement this callback to get the next sibling node of a given node
* in the host element's DOM.
* @returns The sibling node, or null if there is no sibling.
* For WebWorkers, always returns a value.
* This is because the check is synchronous,
* and the caller can't rely on checking for null.
*/
abstract nextSibling(node: any): any;
/**
* Implement this callback to set an attribute value for an element in the DOM.
* @param el The element.
* @param name The attribute name.
* @param value The new value.
* @param namespace The namespace.
*/
abstract setAttribute(el: any, name: string, value: string, namespace?: string|null): void;
/**
* Implement this callback to remove an attribute from an element in the DOM.
* @param el The element.
* @param name The attribute name.
* @param namespace The namespace.
*/
abstract removeAttribute(el: any, name: string, namespace?: string|null): void;
/**
* Implement this callback to add a class to an element in the DOM.
* @param el The element.
* @param name The class name.
*/
abstract addClass(el: any, name: string): void;
/**
* Implement this callback to remove a class from an element in the DOM.
* @param el The element.
* @param name The class name.
*/
abstract removeClass(el: any, name: string): void;
/**
* Implement this callback to set a CSS style for an element in the DOM.
* @param el The element.
* @param style The name of the style.
* @param value The new value.
* @param flags Flags for style variations. No flags are set by default.
*/
abstract setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void;
/**
* Implement this callback to remove the value from a CSS style for an element in the DOM.
* @param el The element.
* @param style The name of the style.
* @param flags Flags for style variations to remove, if set. ???
*/
abstract removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void;
/**
* Implement this callback to set the value of a property of an element in the DOM.
* @param el The element.
* @param name The property name.
* @param value The new value.
*/
abstract setProperty(el: any, name: string, value: any): void;
/**
* Implement this callback to set the value of a node in the host element.
* @param node The node.
* @param value The new value.
*/
abstract setValue(node: any, value: string): void;
/**
* Implement this callback to start an event listener.
* @param target The context in which to listen for events. Can be
* the entire window or document, the body of the document, or a specific
* DOM element.
* @param eventName The event to listen for.
* @param callback A handler function to invoke when the event occurs.
* @returns An "unlisten" function for disposing of this handler.
*/
abstract listen(
target: 'window'|'document'|'body'|any, eventName: string,
callback: (event: any) => boolean | void): () => void;
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => Renderer2 = () => SWITCH_RENDERER2_FACTORY();
}
export const SWITCH_RENDERER2_FACTORY__POST_R3__ = render3InjectRenderer2;
const SWITCH_RENDERER2_FACTORY__PRE_R3__ = noop;
const SWITCH_RENDERER2_FACTORY: typeof render3InjectRenderer2 = SWITCH_RENDERER2_FACTORY__PRE_R3__;
| packages/core/src/render/api.ts | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.00033783959224820137,
0.00017877093341667205,
0.00016132737800944597,
0.00016747538757044822,
0.00003400516652618535
] |
{
"id": 0,
"code_window": [
" for (const s of symbols) {\n",
" if (s.name.startsWith('__') || !s.public || this.completions.has(s.name)) {\n",
" continue;\n",
" }\n",
" this.completions.set(s.name, {\n",
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" // The pipe method should not include parentheses.\n",
" // e.g. {{ value_expression | slice : start [ : end ] }}\n",
" const shouldInsertParentheses = s.callable && s.kind !== ng.CompletionKind.PIPE;\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "add",
"edit_start_line_idx": 471
} | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ts_library(
name = "init",
srcs = glob(
[
"**/*.ts",
],
),
module_name = "@angular/localize/init",
deps = [
"//packages/localize/src/localize",
"@npm//@types/node",
],
)
| packages/localize/init/BUILD.bazel | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.0001738944702083245,
0.00017309129179921,
0.00017228811339009553,
0.00017309129179921,
8.0317840911448e-7
] |
{
"id": 1,
"code_window": [
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n",
" sortText: s.name,\n",
" insertText: s.callable ? `${s.name}()` : s.name,\n",
" });\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" insertText: shouldInsertParentheses ? `${s.name}()` : s.name,\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "replace",
"edit_start_line_idx": 475
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {createLanguageService} from '../src/language_service';
import {CompletionKind} from '../src/types';
import {TypeScriptServiceHost} from '../src/typescript_host';
import {MockTypescriptHost} from './test_utils';
const APP_COMPONENT = '/app/app.component.ts';
const PARSING_CASES = '/app/parsing-cases.ts';
const TEST_TEMPLATE = '/app/test.ng';
const EXPRESSION_CASES = '/app/expression-cases.ts';
describe('completions', () => {
const mockHost = new MockTypescriptHost(['/app/main.ts']);
const tsLS = ts.createLanguageService(mockHost);
const ngHost = new TypeScriptServiceHost(mockHost, tsLS);
const ngLS = createLanguageService(ngHost);
beforeEach(() => { mockHost.reset(); });
it('should be able to get entity completions', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'entity-amp');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);
});
it('should be able to return html elements', () => {
const locations = ['empty', 'start-tag-h1', 'h1-content', 'start-tag', 'start-tag-after-h'];
for (const location of locations) {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, location);
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.HTML_ELEMENT, ['div', 'h1', 'h2', 'span']);
}
});
it('should be able to return component directives', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'empty');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.COMPONENT, [
'ng-form',
'my-app',
'ng-component',
'test-comp',
]);
});
it('should be able to return attribute directives', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h1-after-space');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, ['string-model', 'number-model']);
});
it('should be able to return angular pseudo elements', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'empty');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ANGULAR_ELEMENT, [
'ng-container',
'ng-content',
'ng-template',
]);
});
it('should be able to return h1 attributes', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h1-after-space');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.HTML_ATTRIBUTE, [
'class',
'id',
'onclick',
'onmouseup',
]);
});
it('should be able to find common Angular attributes', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'div-attributes');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, [
'ngClass',
'ngForm',
'ngModel',
'string-model',
'number-model',
]);
});
it('should be able to get the completions at the beginning of an interpolation', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h2-hero');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'hero']);
});
it('should not include private members of a class', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h2-hero');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expect(completions).toBeDefined();
const internal = completions !.entries.find(e => e.name === 'internal');
expect(internal).toBeUndefined();
});
it('should be able to get the completions at the end of an interpolation', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'sub-end');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'hero']);
});
it('should be able to get the completions in a property', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'h2-name');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should suggest template references', () => {
mockHost.override(TEST_TEMPLATE, `<div *~{cursor}></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, [
'ngFor',
'ngForOf',
'ngIf',
'ngSwitchCase',
'ngSwitchDefault',
'ngPluralCase',
]);
});
it('should be able to return attribute names with an incomplete attribute', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'no-value-attribute');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.HTML_ATTRIBUTE, ['id', 'class', 'dir', 'lang']);
});
it('should be able to return attributes of an incomplete element', () => {
const m1 = mockHost.getLocationMarkerFor(PARSING_CASES, 'incomplete-open-lt');
const c1 = ngLS.getCompletionsAt(PARSING_CASES, m1.start);
expectContain(c1, CompletionKind.HTML_ELEMENT, ['a', 'div', 'p', 'span']);
const m2 = mockHost.getLocationMarkerFor(PARSING_CASES, 'incomplete-open-a');
const c2 = ngLS.getCompletionsAt(PARSING_CASES, m2.start);
expectContain(c2, CompletionKind.HTML_ELEMENT, ['a', 'div', 'p', 'span']);
const m3 = mockHost.getLocationMarkerFor(PARSING_CASES, 'incomplete-open-attr');
const c3 = ngLS.getCompletionsAt(PARSING_CASES, m3.start);
expectContain(c3, CompletionKind.HTML_ATTRIBUTE, ['id', 'class', 'href', 'name']);
});
it('should be able to return completions with a missing closing tag', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'missing-closing');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.HTML_ELEMENT, ['a', 'div', 'p', 'span', 'h1', 'h2']);
});
it('should be able to return common attributes of an unknown tag', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'unknown-element');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.HTML_ATTRIBUTE, ['id', 'dir', 'lang']);
});
it('should be able to get completions in an empty interpolation', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'empty-interpolation');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'subTitle']);
});
it('should suggest $any() type cast function in an interpolation', () => {
const marker = mockHost.getLocationMarkerFor(APP_COMPONENT, 'sub-start');
const completions = ngLS.getCompletionsAt(APP_COMPONENT, marker.start);
expectContain(completions, CompletionKind.METHOD, ['$any']);
});
it('should suggest attribute values', () => {
mockHost.override(TEST_TEMPLATE, `<div [id]="~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, [
'title',
'hero',
'heroes',
'league',
'anyValue',
]);
});
it('should suggest event handlers', () => {
mockHost.override(TEST_TEMPLATE, `<div (click)="~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.METHOD, ['myClick']);
});
it('for methods should include parentheses', () => {
mockHost.override(TEST_TEMPLATE, `<div (click)="~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeDefined();
expect(completions !.entries).toContain(jasmine.objectContaining({
name: 'myClick',
kind: CompletionKind.METHOD as any,
insertText: 'myClick()',
}));
});
describe('in external template', () => {
it('should be able to get entity completions in external template', () => {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'entity-amp');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);
});
it('should not return html elements', () => {
const locations = ['empty', 'start-tag-h1', 'h1-content', 'start-tag', 'start-tag-after-h'];
for (const location of locations) {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, location);
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeDefined();
const {entries} = completions !;
expect(entries).not.toContain(jasmine.objectContaining({name: 'div'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'h1'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'h2'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'span'}));
}
});
it('should be able to return element directives', () => {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'empty');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.COMPONENT, [
'ng-form',
'my-app',
'ng-component',
'test-comp',
]);
});
it('should not return html attributes', () => {
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'h1-after-space');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeDefined();
const {entries} = completions !;
expect(entries).not.toContain(jasmine.objectContaining({name: 'class'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'id'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'onclick'}));
expect(entries).not.toContain(jasmine.objectContaining({name: 'onmouseup'}));
});
it('should be able to find common Angular attributes', () => {
mockHost.override(TEST_TEMPLATE, `<div ~{cursor}></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, [
'ngClass',
'ngForm',
'ngModel',
'string-model',
'number-model',
]);
});
});
describe('with a *ngIf', () => {
it('should be able to get completions for exported *ngIf variable', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'promised-person-name');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['name', 'age', 'street']);
});
});
describe('with a *ngFor', () => {
it('should suggest NgForRow members for let initialization expression', () => {
mockHost.override(TEST_TEMPLATE, `<div *ngFor="let i=~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, [
'$implicit',
'ngForOf',
'index',
'count',
'first',
'last',
'even',
'odd',
]);
});
it('should not provide suggestion before the = sign', () => {
mockHost.override(TEST_TEMPLATE, `<div *ngFor="let i~{cursor}="></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expect(completions).toBeUndefined();
});
it('should include field reference', () => {
mockHost.override(TEST_TEMPLATE, `<div *ngFor="let x of ~{cursor}"></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['title', 'heroes', 'league']);
// the symbol 'x' declared in *ngFor is also in scope. This asserts that
// we are actually taking the AST into account and not just referring to
// the symbol table of the Component.
expectContain(completions, CompletionKind.VARIABLE, ['x']);
});
it('should include variable in the let scope in interpolation', () => {
mockHost.override(TEST_TEMPLATE, `
<div *ngFor="let h of heroes">
{{~{cursor}}}
</div>
`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.VARIABLE, ['h']);
});
it('should be able to infer the type of a ngForOf', () => {
mockHost.override(TEST_TEMPLATE, `
<div *ngFor="let h of heroes">
{{ h.~{cursor} }}
</div>
`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should be able to infer the type of a ngForOf with an async pipe', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'async-person-name');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['name', 'age', 'street']);
});
it('should be able to resolve variable in nested loop', () => {
mockHost.override(TEST_TEMPLATE, `
<div *ngFor="let leagueMembers of league">
<div *ngFor="let member of leagueMembers">
{{member.~{position}}}
</div>
</div>
`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'position');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
// member variable of type Hero has properties 'id' and 'name'.
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
});
describe('data binding', () => {
it('should be able to complete property value', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'property-binding-model');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['test']);
});
it('should be able to complete an event', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'event-binding-model');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.METHOD, ['modelChanged']);
});
it('should be able to complete a the LHS of a two-way binding', () => {
mockHost.override(TEST_TEMPLATE, `<div [(~{cursor})]></div>`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.ATTRIBUTE, ['ngModel']);
});
it('should be able to complete a the RHS of a two-way binding', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'two-way-binding-model');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['test']);
});
it('should suggest property binding for input', () => {
// Property binding via []
mockHost.override(TEST_TEMPLATE, `<div number-model [~{cursor}]></div>`);
const m1 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c1 = ngLS.getCompletionsAt(TEST_TEMPLATE, m1.start);
expectContain(c1, CompletionKind.ATTRIBUTE, ['inputAlias']);
// Property binding via bind-
mockHost.override(TEST_TEMPLATE, `<div number-model bind-~{cursor}></div>`);
const m2 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c2 = ngLS.getCompletionsAt(TEST_TEMPLATE, m2.start);
expectContain(c2, CompletionKind.ATTRIBUTE, ['inputAlias']);
});
it('should suggest event binding for output', () => {
// Event binding via ()
mockHost.override(TEST_TEMPLATE, `<div number-model (~{cursor})></div>`);
const m1 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c1 = ngLS.getCompletionsAt(TEST_TEMPLATE, m1.start);
expectContain(c1, CompletionKind.ATTRIBUTE, ['outputAlias']);
// Event binding via on-
mockHost.override(TEST_TEMPLATE, `<div number-mode on-~{cursor}></div>`);
const m2 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c2 = ngLS.getCompletionsAt(TEST_TEMPLATE, m2.start);
expectContain(c2, CompletionKind.ATTRIBUTE, ['outputAlias']);
});
it('should suggest two-way binding for input and output', () => {
// Banana-in-a-box via [()]
mockHost.override(TEST_TEMPLATE, `<div string-model [(~{cursor})]></div>`);
const m1 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c1 = ngLS.getCompletionsAt(TEST_TEMPLATE, m1.start);
expectContain(c1, CompletionKind.ATTRIBUTE, ['model']);
// Banana-in-a-box via bindon-
mockHost.override(TEST_TEMPLATE, `<div string-model bindon-~{cursor}></div>`);
const m2 = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'cursor');
const c2 = ngLS.getCompletionsAt(TEST_TEMPLATE, m2.start);
expectContain(c2, CompletionKind.ATTRIBUTE, ['model']);
});
});
describe('for pipes', () => {
it('should be able to get a list of pipe values', () => {
for (const location of ['before-pipe', 'in-pipe', 'after-pipe']) {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, location);
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PIPE, [
'async',
'uppercase',
'lowercase',
'titlecase',
]);
}
});
it('should be able to resolve lowercase', () => {
const marker = mockHost.getLocationMarkerFor(EXPRESSION_CASES, 'string-pipe');
const completions = ngLS.getCompletionsAt(EXPRESSION_CASES, marker.start);
expectContain(completions, CompletionKind.METHOD, [
'charAt',
'replace',
'substring',
'toLowerCase',
]);
});
});
describe('with references', () => {
it('should list references', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'test-comp-content');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.REFERENCE, ['div', 'test1', 'test2']);
});
it('should reference the component', () => {
const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'test-comp-after-test');
const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['name', 'testEvent']);
});
// TODO: Enable when we have a flag that indicates the project targets the DOM
// it('should reference the element if no component', () => {
// const marker = mockHost.getLocationMarkerFor(PARSING_CASES, 'test-comp-after-div');
// const completions = ngLS.getCompletionsAt(PARSING_CASES, marker.start);
// expectContain(completions, CompletionKind.PROPERTY, ['innerText']);
// });
});
describe('replacement span', () => {
it('should not generate replacement entries for zero-length replacements', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div>{{obj.~{key}}}</div>
\`,
})
export class FooComponent {
obj: {key: 'value'};
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'key');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'key') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('property');
expect(completion.replacementSpan).toBeUndefined();
});
it('should work for start of template', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`~{start}abc\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'start');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'acronym') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('html element');
expect(completion.replacementSpan).toEqual({start: location.start, length: 3});
});
it('should work for end of template', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`acro~{end}\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'end');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'acronym') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('html element');
expect(completion.replacementSpan).toEqual({start: location.start - 4, length: 4});
});
it('should work for middle-word replacements', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div>{{obj.ke~{key}key}}</div>
\`,
})
export class FooComponent {
obj: {key: 'value'};
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'key');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'key') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('property');
expect(completion.replacementSpan).toEqual({start: location.start - 2, length: 5});
});
it('should work for all kinds of identifier characters', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div>{{~{field}$title_1}}</div>
\`,
})
export class FooComponent {
$title_1: string;
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'field');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === '$title_1') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('property');
expect(completion.replacementSpan).toEqual({start: location.start, length: 8});
});
it('should work for attributes', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div (cl~{click})></div>
\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'click');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'click') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe(CompletionKind.ATTRIBUTE);
expect(completion.replacementSpan).toEqual({start: location.start - 2, length: 2});
});
it('should work for events', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<div (click)="han~{handleClick}"></div>
\`,
})
export class FooComponent {
handleClick() {}
}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'handleClick');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'handleClick') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('method');
expect(completion.replacementSpan).toEqual({start: location.start - 3, length: 3});
});
it('should work for element names', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<di~{div}></div>
\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'div');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'div') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe('html element');
expect(completion.replacementSpan).toEqual({start: location.start - 2, length: 2});
});
it('should work for bindings', () => {
const fileName = mockHost.addCode(`
@Component({
selector: 'foo-component',
template: \`
<input [(ngMod~{model})] />
\`,
})
export class FooComponent {}
`);
const location = mockHost.getLocationMarkerFor(fileName, 'model');
const completions = ngLS.getCompletionsAt(fileName, location.start) !;
expect(completions).toBeDefined();
const completion = completions.entries.find(entry => entry.name === 'ngModel') !;
expect(completion).toBeDefined();
expect(completion.kind).toBe(CompletionKind.ATTRIBUTE);
expect(completion.replacementSpan).toEqual({start: location.start - 5, length: 5});
});
});
describe('property completions for members of an indexed type', () => {
it('should work with numeric index signatures (arrays)', () => {
mockHost.override(TEST_TEMPLATE, `{{ heroes[0].~{heroes-number-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'heroes-number-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should work with numeric index signatures (tuple arrays)', () => {
mockHost.override(TEST_TEMPLATE, `{{ tupleArray[1].~{tuple-array-number-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'tuple-array-number-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
describe('with string index signatures', () => {
it('should work with index notation', () => {
mockHost.override(TEST_TEMPLATE, `{{ heroesByName['Jacky'].~{heroes-string-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'heroes-string-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should work with dot notation', () => {
mockHost.override(TEST_TEMPLATE, `{{ heroesByName.jacky.~{heroes-string-index}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'heroes-string-index');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.PROPERTY, ['id', 'name']);
});
it('should work with dot notation if stringIndexType is a primitive type', () => {
mockHost.override(TEST_TEMPLATE, `{{ primitiveIndexType.test.~{string-primitive-type}}}`);
const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'string-primitive-type');
const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);
expectContain(completions, CompletionKind.METHOD, ['substring']);
});
});
});
});
function expectContain(
completions: ts.CompletionInfo | undefined, kind: CompletionKind, names: string[]) {
expect(completions).toBeDefined();
for (const name of names) {
expect(completions !.entries).toContain(jasmine.objectContaining({ name, kind } as any));
}
}
| packages/language-service/test/completions_spec.ts | 1 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.0003700225497595966,
0.00017620172002352774,
0.00016387546202167869,
0.00016973825404420495,
0.00003264507176936604
] |
{
"id": 1,
"code_window": [
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n",
" sortText: s.name,\n",
" insertText: s.callable ? `${s.name}()` : s.name,\n",
" });\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" insertText: shouldInsertParentheses ? `${s.name}()` : s.name,\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "replace",
"edit_start_line_idx": 475
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ɵɵinject, ɵɵinvalidFactoryDep} from '../../di/injector_compatibility';
import {ɵɵdefineInjectable, ɵɵdefineInjector} from '../../di/interface/defs';
import * as sanitization from '../../sanitization/sanitization';
import * as r3 from '../index';
/**
* A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
*
* This should be kept up to date with the public exports of @angular/core.
*/
export const angularCoreEnv: {[name: string]: Function} =
(() => ({
'ɵɵattribute': r3.ɵɵattribute,
'ɵɵattributeInterpolate1': r3.ɵɵattributeInterpolate1,
'ɵɵattributeInterpolate2': r3.ɵɵattributeInterpolate2,
'ɵɵattributeInterpolate3': r3.ɵɵattributeInterpolate3,
'ɵɵattributeInterpolate4': r3.ɵɵattributeInterpolate4,
'ɵɵattributeInterpolate5': r3.ɵɵattributeInterpolate5,
'ɵɵattributeInterpolate6': r3.ɵɵattributeInterpolate6,
'ɵɵattributeInterpolate7': r3.ɵɵattributeInterpolate7,
'ɵɵattributeInterpolate8': r3.ɵɵattributeInterpolate8,
'ɵɵattributeInterpolateV': r3.ɵɵattributeInterpolateV,
'ɵɵdefineComponent': r3.ɵɵdefineComponent,
'ɵɵdefineDirective': r3.ɵɵdefineDirective,
'ɵɵdefineInjectable': ɵɵdefineInjectable,
'ɵɵdefineInjector': ɵɵdefineInjector,
'ɵɵdefineNgModule': r3.ɵɵdefineNgModule,
'ɵɵdefinePipe': r3.ɵɵdefinePipe,
'ɵɵdirectiveInject': r3.ɵɵdirectiveInject,
'ɵɵgetFactoryOf': r3.ɵɵgetFactoryOf,
'ɵɵgetInheritedFactory': r3.ɵɵgetInheritedFactory,
'ɵɵinject': ɵɵinject,
'ɵɵinjectAttribute': r3.ɵɵinjectAttribute,
'ɵɵinvalidFactory': r3.ɵɵinvalidFactory,
'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
'ɵɵinjectPipeChangeDetectorRef': r3.ɵɵinjectPipeChangeDetectorRef,
'ɵɵtemplateRefExtractor': r3.ɵɵtemplateRefExtractor,
'ɵɵNgOnChangesFeature': r3.ɵɵNgOnChangesFeature,
'ɵɵProvidersFeature': r3.ɵɵProvidersFeature,
'ɵɵCopyDefinitionFeature': r3.ɵɵCopyDefinitionFeature,
'ɵɵInheritDefinitionFeature': r3.ɵɵInheritDefinitionFeature,
'ɵɵcontainer': r3.ɵɵcontainer,
'ɵɵnextContext': r3.ɵɵnextContext,
'ɵɵcontainerRefreshStart': r3.ɵɵcontainerRefreshStart,
'ɵɵcontainerRefreshEnd': r3.ɵɵcontainerRefreshEnd,
'ɵɵnamespaceHTML': r3.ɵɵnamespaceHTML,
'ɵɵnamespaceMathML': r3.ɵɵnamespaceMathML,
'ɵɵnamespaceSVG': r3.ɵɵnamespaceSVG,
'ɵɵenableBindings': r3.ɵɵenableBindings,
'ɵɵdisableBindings': r3.ɵɵdisableBindings,
'ɵɵallocHostVars': r3.ɵɵallocHostVars,
'ɵɵelementStart': r3.ɵɵelementStart,
'ɵɵelementEnd': r3.ɵɵelementEnd,
'ɵɵelement': r3.ɵɵelement,
'ɵɵelementContainerStart': r3.ɵɵelementContainerStart,
'ɵɵelementContainerEnd': r3.ɵɵelementContainerEnd,
'ɵɵelementContainer': r3.ɵɵelementContainer,
'ɵɵpureFunction0': r3.ɵɵpureFunction0,
'ɵɵpureFunction1': r3.ɵɵpureFunction1,
'ɵɵpureFunction2': r3.ɵɵpureFunction2,
'ɵɵpureFunction3': r3.ɵɵpureFunction3,
'ɵɵpureFunction4': r3.ɵɵpureFunction4,
'ɵɵpureFunction5': r3.ɵɵpureFunction5,
'ɵɵpureFunction6': r3.ɵɵpureFunction6,
'ɵɵpureFunction7': r3.ɵɵpureFunction7,
'ɵɵpureFunction8': r3.ɵɵpureFunction8,
'ɵɵpureFunctionV': r3.ɵɵpureFunctionV,
'ɵɵgetCurrentView': r3.ɵɵgetCurrentView,
'ɵɵrestoreView': r3.ɵɵrestoreView,
'ɵɵlistener': r3.ɵɵlistener,
'ɵɵprojection': r3.ɵɵprojection,
'ɵɵupdateSyntheticHostBinding': r3.ɵɵupdateSyntheticHostBinding,
'ɵɵcomponentHostSyntheticListener': r3.ɵɵcomponentHostSyntheticListener,
'ɵɵpipeBind1': r3.ɵɵpipeBind1,
'ɵɵpipeBind2': r3.ɵɵpipeBind2,
'ɵɵpipeBind3': r3.ɵɵpipeBind3,
'ɵɵpipeBind4': r3.ɵɵpipeBind4,
'ɵɵpipeBindV': r3.ɵɵpipeBindV,
'ɵɵprojectionDef': r3.ɵɵprojectionDef,
'ɵɵhostProperty': r3.ɵɵhostProperty,
'ɵɵproperty': r3.ɵɵproperty,
'ɵɵpropertyInterpolate': r3.ɵɵpropertyInterpolate,
'ɵɵpropertyInterpolate1': r3.ɵɵpropertyInterpolate1,
'ɵɵpropertyInterpolate2': r3.ɵɵpropertyInterpolate2,
'ɵɵpropertyInterpolate3': r3.ɵɵpropertyInterpolate3,
'ɵɵpropertyInterpolate4': r3.ɵɵpropertyInterpolate4,
'ɵɵpropertyInterpolate5': r3.ɵɵpropertyInterpolate5,
'ɵɵpropertyInterpolate6': r3.ɵɵpropertyInterpolate6,
'ɵɵpropertyInterpolate7': r3.ɵɵpropertyInterpolate7,
'ɵɵpropertyInterpolate8': r3.ɵɵpropertyInterpolate8,
'ɵɵpropertyInterpolateV': r3.ɵɵpropertyInterpolateV,
'ɵɵpipe': r3.ɵɵpipe,
'ɵɵqueryRefresh': r3.ɵɵqueryRefresh,
'ɵɵviewQuery': r3.ɵɵviewQuery,
'ɵɵstaticViewQuery': r3.ɵɵstaticViewQuery,
'ɵɵstaticContentQuery': r3.ɵɵstaticContentQuery,
'ɵɵloadQuery': r3.ɵɵloadQuery,
'ɵɵcontentQuery': r3.ɵɵcontentQuery,
'ɵɵreference': r3.ɵɵreference,
'ɵɵelementHostAttrs': r3.ɵɵelementHostAttrs,
'ɵɵclassMap': r3.ɵɵclassMap,
'ɵɵclassMapInterpolate1': r3.ɵɵclassMapInterpolate1,
'ɵɵclassMapInterpolate2': r3.ɵɵclassMapInterpolate2,
'ɵɵclassMapInterpolate3': r3.ɵɵclassMapInterpolate3,
'ɵɵclassMapInterpolate4': r3.ɵɵclassMapInterpolate4,
'ɵɵclassMapInterpolate5': r3.ɵɵclassMapInterpolate5,
'ɵɵclassMapInterpolate6': r3.ɵɵclassMapInterpolate6,
'ɵɵclassMapInterpolate7': r3.ɵɵclassMapInterpolate7,
'ɵɵclassMapInterpolate8': r3.ɵɵclassMapInterpolate8,
'ɵɵclassMapInterpolateV': r3.ɵɵclassMapInterpolateV,
'ɵɵstyleMap': r3.ɵɵstyleMap,
'ɵɵstyleProp': r3.ɵɵstyleProp,
'ɵɵstylePropInterpolate1': r3.ɵɵstylePropInterpolate1,
'ɵɵstylePropInterpolate2': r3.ɵɵstylePropInterpolate2,
'ɵɵstylePropInterpolate3': r3.ɵɵstylePropInterpolate3,
'ɵɵstylePropInterpolate4': r3.ɵɵstylePropInterpolate4,
'ɵɵstylePropInterpolate5': r3.ɵɵstylePropInterpolate5,
'ɵɵstylePropInterpolate6': r3.ɵɵstylePropInterpolate6,
'ɵɵstylePropInterpolate7': r3.ɵɵstylePropInterpolate7,
'ɵɵstylePropInterpolate8': r3.ɵɵstylePropInterpolate8,
'ɵɵstylePropInterpolateV': r3.ɵɵstylePropInterpolateV,
'ɵɵstyleSanitizer': r3.ɵɵstyleSanitizer,
'ɵɵclassProp': r3.ɵɵclassProp,
'ɵɵselect': r3.ɵɵselect,
'ɵɵadvance': r3.ɵɵadvance,
'ɵɵtemplate': r3.ɵɵtemplate,
'ɵɵtext': r3.ɵɵtext,
'ɵɵtextInterpolate': r3.ɵɵtextInterpolate,
'ɵɵtextInterpolate1': r3.ɵɵtextInterpolate1,
'ɵɵtextInterpolate2': r3.ɵɵtextInterpolate2,
'ɵɵtextInterpolate3': r3.ɵɵtextInterpolate3,
'ɵɵtextInterpolate4': r3.ɵɵtextInterpolate4,
'ɵɵtextInterpolate5': r3.ɵɵtextInterpolate5,
'ɵɵtextInterpolate6': r3.ɵɵtextInterpolate6,
'ɵɵtextInterpolate7': r3.ɵɵtextInterpolate7,
'ɵɵtextInterpolate8': r3.ɵɵtextInterpolate8,
'ɵɵtextInterpolateV': r3.ɵɵtextInterpolateV,
'ɵɵembeddedViewStart': r3.ɵɵembeddedViewStart,
'ɵɵembeddedViewEnd': r3.ɵɵembeddedViewEnd,
'ɵɵi18n': r3.ɵɵi18n,
'ɵɵi18nAttributes': r3.ɵɵi18nAttributes,
'ɵɵi18nExp': r3.ɵɵi18nExp,
'ɵɵi18nStart': r3.ɵɵi18nStart,
'ɵɵi18nEnd': r3.ɵɵi18nEnd,
'ɵɵi18nApply': r3.ɵɵi18nApply,
'ɵɵi18nPostprocess': r3.ɵɵi18nPostprocess,
'ɵɵresolveWindow': r3.ɵɵresolveWindow,
'ɵɵresolveDocument': r3.ɵɵresolveDocument,
'ɵɵresolveBody': r3.ɵɵresolveBody,
'ɵɵsetComponentScope': r3.ɵɵsetComponentScope,
'ɵɵsetNgModuleScope': r3.ɵɵsetNgModuleScope,
'ɵɵsanitizeHtml': sanitization.ɵɵsanitizeHtml,
'ɵɵsanitizeStyle': sanitization.ɵɵsanitizeStyle,
'ɵɵdefaultStyleSanitizer': sanitization.ɵɵdefaultStyleSanitizer,
'ɵɵsanitizeResourceUrl': sanitization.ɵɵsanitizeResourceUrl,
'ɵɵsanitizeScript': sanitization.ɵɵsanitizeScript,
'ɵɵsanitizeUrl': sanitization.ɵɵsanitizeUrl,
'ɵɵsanitizeUrlOrResourceUrl': sanitization.ɵɵsanitizeUrlOrResourceUrl,
}))();
| packages/core/src/render3/jit/environment.ts | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.00017980394477490336,
0.00017411191947758198,
0.00016439099272247404,
0.00017413802561350167,
0.000002936754071924952
] |
{
"id": 1,
"code_window": [
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n",
" sortText: s.name,\n",
" insertText: s.callable ? `${s.name}()` : s.name,\n",
" });\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" insertText: shouldInsertParentheses ? `${s.name}()` : s.name,\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "replace",
"edit_start_line_idx": 475
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
if (n === 1) return 1;
return 5;
}
global.ng.common.locales['es-gq'] = [
'es-GQ',
[['a. m.', 'p. m.'], u, u],
u,
[
['D', 'L', 'M', 'X', 'J', 'V', 'S'],
['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'],
['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA']
],
u,
[
['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sept.', 'oct.', 'nov.',
'dic.'
],
[
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre',
'octubre', 'noviembre', 'diciembre'
]
],
u,
[['a. C.', 'd. C.'], u, ['antes de Cristo', 'después de Cristo']],
1,
[6, 0],
['d/M/yy', 'd MMM y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'],
['H:mm', 'H:mm:ss', 'H:mm:ss z', 'H:mm:ss (zzzz)'],
['{1} {0}', u, '{1}, {0}', u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '¤#,##0.00', '#E0'],
'FCFA',
'franco CFA de África Central',
{
'AUD': [u, '$'],
'BRL': [u, 'R$'],
'CNY': [u, '¥'],
'EGP': [],
'ESP': ['₧'],
'GBP': [u, '£'],
'HKD': [u, '$'],
'ILS': [u, '₪'],
'INR': [u, '₹'],
'JPY': [u, '¥'],
'KRW': [u, '₩'],
'MXN': [u, '$'],
'NZD': [u, '$'],
'RON': [u, 'L'],
'THB': ['฿'],
'TWD': [u, 'NT$'],
'USD': ['US$', '$'],
'XCD': [u, '$'],
'XOF': []
},
'ltr',
plural,
[
[['del mediodía', 'de la madrugada', 'de la mañana', 'de la tarde', 'de la noche'], u, u],
[['mediodía', 'madrugada', 'mañana', 'tarde', 'noche'], u, u],
['12:00', ['00:00', '06:00'], ['06:00', '12:00'], ['12:00', '20:00'], ['20:00', '24:00']]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| packages/common/locales/global/es-GQ.js | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.00017721713811624795,
0.00017486355500295758,
0.00016863120254129171,
0.00017538666725158691,
0.0000025527185698592803
] |
{
"id": 1,
"code_window": [
" name: s.name,\n",
" kind: s.kind as ng.CompletionKind,\n",
" sortText: s.name,\n",
" insertText: s.callable ? `${s.name}()` : s.name,\n",
" });\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" insertText: shouldInsertParentheses ? `${s.name}()` : s.name,\n"
],
"file_path": "packages/language-service/src/completions.ts",
"type": "replace",
"edit_start_line_idx": 475
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
if (n === 1) return 1;
return 5;
}
export default [
'ckb-IR',
[['ب.ن', 'د.ن'], u, u],
u,
[
['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'],
[
'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە',
'پێنجشەممە', 'ھەینی', 'شەممە'
],
u, ['١ش', '٢ش', '٣ش', '٤ش', '٥ش', 'ھ', 'ش']
],
u,
[
['ک', 'ش', 'ئ', 'ن', 'ئ', 'ح', 'ت', 'ئ', 'ئ', 'ت', 'ت', 'ک'],
[
'کانوونی دووەم', 'شوبات', 'ئازار', 'نیسان', 'ئایار',
'حوزەیران', 'تەمووز', 'ئاب', 'ئەیلوول', 'تشرینی یەکەم',
'تشرینی دووەم', 'کانونی یەکەم'
],
u
],
u,
[['پێش زایین', 'زایینی'], u, u],
6,
[5, 5],
['y-MM-dd', 'y MMM d', 'dی MMMMی y', 'y MMMM d, EEEE'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, u, u],
['.', ',', ';', '%', '\u200e+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'],
'IRR',
'IRR',
{'IQD': ['د.ع.\u200f'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']},
'rtl',
plural
];
| packages/common/locales/ckb-IR.ts | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.00017924336134456098,
0.0001742722961353138,
0.0001690591307124123,
0.00017510383622720838,
0.0000038071113976911874
] |
{
"id": 2,
"code_window": [
" kind: CompletionKind.METHOD as any,\n",
" insertText: 'myClick()',\n",
" }));\n",
" });\n",
"\n",
" describe('in external template', () => {\n",
" it('should be able to get entity completions in external template', () => {\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'entity-amp');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('for methods of pipe should not include parentheses', () => {\n",
" mockHost.override(TEST_TEMPLATE, `<h1>{{title | lowe~{pipe-method} }}`);\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'pipe-method');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expect(completions).toBeDefined();\n",
" expect(completions !.entries).toContain(jasmine.objectContaining({\n",
" name: 'lowercase',\n",
" kind: CompletionKind.PIPE as any,\n",
" insertText: 'lowercase',\n",
" }));\n",
" });\n",
"\n"
],
"file_path": "packages/language-service/test/completions_spec.ts",
"type": "add",
"edit_start_line_idx": 210
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AST, AstPath, AttrAst, Attribute, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, Element, ElementAst, ImplicitReceiver, NAMED_ENTITIES, Node as HtmlAst, NullTemplateVisitor, ParseSpan, PropertyRead, TagContentType, TemplateBinding, Text, getHtmlTagDefinition} from '@angular/compiler';
import {$$, $_, isAsciiLetter, isDigit} from '@angular/compiler/src/chars';
import {AstResult} from './common';
import {getExpressionScope} from './expression_diagnostics';
import {getExpressionCompletions} from './expressions';
import {attributeNames, elementNames, eventNames, propertyNames} from './html_info';
import {InlineTemplate} from './template';
import * as ng from './types';
import {diagnosticInfoFromTemplateInfo, findTemplateAstAt, getPathToNodeAtPosition, getSelectors, hasTemplateReference, inSpan, spanOf} from './utils';
const HIDDEN_HTML_ELEMENTS: ReadonlySet<string> =
new Set(['html', 'script', 'noscript', 'base', 'body', 'title', 'head', 'link']);
const HTML_ELEMENTS: ReadonlyArray<ng.CompletionEntry> =
elementNames().filter(name => !HIDDEN_HTML_ELEMENTS.has(name)).map(name => {
return {
name,
kind: ng.CompletionKind.HTML_ELEMENT,
sortText: name,
};
});
const ANGULAR_ELEMENTS: ReadonlyArray<ng.CompletionEntry> = [
{
name: 'ng-container',
kind: ng.CompletionKind.ANGULAR_ELEMENT,
sortText: 'ng-container',
},
{
name: 'ng-content',
kind: ng.CompletionKind.ANGULAR_ELEMENT,
sortText: 'ng-content',
},
{
name: 'ng-template',
kind: ng.CompletionKind.ANGULAR_ELEMENT,
sortText: 'ng-template',
},
];
// This is adapted from packages/compiler/src/render3/r3_template_transform.ts
// to allow empty binding names.
const BIND_NAME_REGEXP =
/^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*))|\[\(([^\)]*)\)\]|\[([^\]]*)\]|\(([^\)]*)\))$/;
enum ATTR {
// Group 1 = "bind-"
KW_BIND_IDX = 1,
// Group 2 = "let-"
KW_LET_IDX = 2,
// Group 3 = "ref-/#"
KW_REF_IDX = 3,
// Group 4 = "on-"
KW_ON_IDX = 4,
// Group 5 = "bindon-"
KW_BINDON_IDX = 5,
// Group 6 = "@"
KW_AT_IDX = 6,
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
IDENT_KW_IDX = 7,
// Group 8 = identifier inside [()]
IDENT_BANANA_BOX_IDX = 8,
// Group 9 = identifier inside []
IDENT_PROPERTY_IDX = 9,
// Group 10 = identifier inside ()
IDENT_EVENT_IDX = 10,
}
function isIdentifierPart(code: number) {
// Identifiers consist of alphanumeric characters, '_', or '$'.
return isAsciiLetter(code) || isDigit(code) || code == $$ || code == $_;
}
/**
* Gets the span of word in a template that surrounds `position`. If there is no word around
* `position`, nothing is returned.
*/
function getBoundedWordSpan(templateInfo: AstResult, position: number): ts.TextSpan|undefined {
const {template} = templateInfo;
const templateSrc = template.source;
if (!templateSrc) return;
// TODO(ayazhafiz): A solution based on word expansion will always be expensive compared to one
// based on ASTs. Whatever penalty we incur is probably manageable for small-length (i.e. the
// majority of) identifiers, but the current solution involes a number of branchings and we can't
// control potentially very long identifiers. Consider moving to an AST-based solution once
// existing difficulties with AST spans are more clearly resolved (see #31898 for discussion of
// known problems, and #33091 for how they affect text replacement).
//
// `templatePosition` represents the right-bound location of a cursor in the template.
// key.ent|ry
// ^---- cursor, at position `r` is at.
// A cursor is not itself a character in the template; it has a left (lower) and right (upper)
// index bound that hugs the cursor itself.
let templatePosition = position - template.span.start;
// To perform word expansion, we want to determine the left and right indices that hug the cursor.
// There are three cases here.
let left, right;
if (templatePosition === 0) {
// 1. Case like
// |rest of template
// the cursor is at the start of the template, hugged only by the right side (0-index).
left = right = 0;
} else if (templatePosition === templateSrc.length) {
// 2. Case like
// rest of template|
// the cursor is at the end of the template, hugged only by the left side (last-index).
left = right = templateSrc.length - 1;
} else {
// 3. Case like
// wo|rd
// there is a clear left and right index.
left = templatePosition - 1;
right = templatePosition;
}
if (!isIdentifierPart(templateSrc.charCodeAt(left)) &&
!isIdentifierPart(templateSrc.charCodeAt(right))) {
// Case like
// .|.
// left ---^ ^--- right
// There is no word here.
return;
}
// Expand on the left and right side until a word boundary is hit. Back up one expansion on both
// side to stay inside the word.
while (left >= 0 && isIdentifierPart(templateSrc.charCodeAt(left))) --left;
++left;
while (right < templateSrc.length && isIdentifierPart(templateSrc.charCodeAt(right))) ++right;
--right;
const absoluteStartPosition = position - (templatePosition - left);
const length = right - left + 1;
return {start: absoluteStartPosition, length};
}
export function getTemplateCompletions(
templateInfo: AstResult, position: number): ng.CompletionEntry[] {
let result: ng.CompletionEntry[] = [];
const {htmlAst, template} = templateInfo;
// The templateNode starts at the delimiter character so we add 1 to skip it.
const templatePosition = position - template.span.start;
const path = getPathToNodeAtPosition(htmlAst, templatePosition);
const mostSpecific = path.tail;
if (path.empty || !mostSpecific) {
result = elementCompletions(templateInfo);
} else {
const astPosition = templatePosition - mostSpecific.sourceSpan.start.offset;
mostSpecific.visit(
{
visitElement(ast) {
const startTagSpan = spanOf(ast.sourceSpan);
const tagLen = ast.name.length;
// + 1 for the opening angle bracket
if (templatePosition <= startTagSpan.start + tagLen + 1) {
// If we are in the tag then return the element completions.
result = elementCompletions(templateInfo);
} else if (templatePosition < startTagSpan.end) {
// We are in the attribute section of the element (but not in an attribute).
// Return the attribute completions.
result = attributeCompletionsForElement(templateInfo, ast.name);
}
},
visitAttribute(ast) {
if (!ast.valueSpan || !inSpan(templatePosition, spanOf(ast.valueSpan))) {
// We are in the name of an attribute. Show attribute completions.
result = attributeCompletions(templateInfo, path);
} else if (ast.valueSpan && inSpan(templatePosition, spanOf(ast.valueSpan))) {
result = attributeValueCompletions(templateInfo, templatePosition, ast);
}
},
visitText(ast) {
// Check if we are in a entity.
result = entityCompletions(getSourceText(template, spanOf(ast)), astPosition);
if (result.length) return result;
result = interpolationCompletions(templateInfo, templatePosition);
if (result.length) return result;
const element = path.first(Element);
if (element) {
const definition = getHtmlTagDefinition(element.name);
if (definition.contentType === TagContentType.PARSABLE_DATA) {
result = voidElementAttributeCompletions(templateInfo, path);
if (!result.length) {
// If the element can hold content, show element completions.
result = elementCompletions(templateInfo);
}
}
} else {
// If no element container, implies parsable data so show elements.
result = voidElementAttributeCompletions(templateInfo, path);
if (!result.length) {
result = elementCompletions(templateInfo);
}
}
},
visitComment(ast) {},
visitExpansion(ast) {},
visitExpansionCase(ast) {}
},
null);
}
const replacementSpan = getBoundedWordSpan(templateInfo, position);
return result.map(entry => {
return {
...entry, replacementSpan,
};
});
}
function attributeCompletions(info: AstResult, path: AstPath<HtmlAst>): ng.CompletionEntry[] {
const attr = path.tail;
const elem = path.parentOf(attr);
if (!(attr instanceof Attribute) || !(elem instanceof Element)) {
return [];
}
// TODO: Consider parsing the attrinute name to a proper AST instead of
// matching using regex. This is because the regexp would incorrectly identify
// bind parts for cases like [()|]
// ^ cursor is here
const bindParts = attr.name.match(BIND_NAME_REGEXP);
// TemplateRef starts with '*'. See https://angular.io/api/core/TemplateRef
const isTemplateRef = attr.name.startsWith('*');
const isBinding = bindParts !== null || isTemplateRef;
if (!isBinding) {
return attributeCompletionsForElement(info, elem.name);
}
const results: string[] = [];
const ngAttrs = angularAttributes(info, elem.name);
if (!bindParts) {
// If bindParts is null then this must be a TemplateRef.
results.push(...ngAttrs.templateRefs);
} else if (
bindParts[ATTR.KW_BIND_IDX] !== undefined ||
bindParts[ATTR.IDENT_PROPERTY_IDX] !== undefined) {
// property binding via bind- or []
results.push(...propertyNames(elem.name), ...ngAttrs.inputs);
} else if (
bindParts[ATTR.KW_ON_IDX] !== undefined || bindParts[ATTR.IDENT_EVENT_IDX] !== undefined) {
// event binding via on- or ()
results.push(...eventNames(elem.name), ...ngAttrs.outputs);
} else if (
bindParts[ATTR.KW_BINDON_IDX] !== undefined ||
bindParts[ATTR.IDENT_BANANA_BOX_IDX] !== undefined) {
// banana-in-a-box binding via bindon- or [()]
results.push(...ngAttrs.bananas);
}
return results.map(name => {
return {
name,
kind: ng.CompletionKind.ATTRIBUTE,
sortText: name,
};
});
}
function attributeCompletionsForElement(
info: AstResult, elementName: string): ng.CompletionEntry[] {
const results: ng.CompletionEntry[] = [];
if (info.template instanceof InlineTemplate) {
// Provide HTML attributes completion only for inline templates
for (const name of attributeNames(elementName)) {
results.push({
name,
kind: ng.CompletionKind.HTML_ATTRIBUTE,
sortText: name,
});
}
}
// Add Angular attributes
const ngAttrs = angularAttributes(info, elementName);
for (const name of ngAttrs.others) {
results.push({
name,
kind: ng.CompletionKind.ATTRIBUTE,
sortText: name,
});
}
return results;
}
function attributeValueCompletions(
info: AstResult, position: number, attr: Attribute): ng.CompletionEntry[] {
const path = findTemplateAstAt(info.templateAst, position);
if (!path.tail) {
return [];
}
// HtmlAst contains the `Attribute` node, however the corresponding `AttrAst`
// node is missing from the TemplateAst. In this case, we have to manually
// append the `AttrAst` node to the path.
if (!(path.tail instanceof AttrAst)) {
// The sourceSpan of an AttrAst is the valueSpan of the HTML Attribute.
path.push(new AttrAst(attr.name, attr.value, attr.valueSpan !));
}
const dinfo = diagnosticInfoFromTemplateInfo(info);
const visitor =
new ExpressionVisitor(info, position, () => getExpressionScope(dinfo, path, false));
path.tail.visit(visitor, null);
return visitor.results;
}
function elementCompletions(info: AstResult): ng.CompletionEntry[] {
const results: ng.CompletionEntry[] = [...ANGULAR_ELEMENTS];
if (info.template instanceof InlineTemplate) {
// Provide HTML elements completion only for inline templates
results.push(...HTML_ELEMENTS);
}
// Collect the elements referenced by the selectors
const components = new Set<string>();
for (const selector of getSelectors(info).selectors) {
const name = selector.element;
if (name && !components.has(name)) {
components.add(name);
results.push({
name,
kind: ng.CompletionKind.COMPONENT,
sortText: name,
});
}
}
return results;
}
function entityCompletions(value: string, position: number): ng.CompletionEntry[] {
// Look for entity completions
const re = /&[A-Za-z]*;?(?!\d)/g;
let found: RegExpExecArray|null;
let result: ng.CompletionEntry[] = [];
while (found = re.exec(value)) {
let len = found[0].length;
if (position >= found.index && position < (found.index + len)) {
result = Object.keys(NAMED_ENTITIES).map(name => {
return {
name: `&${name};`,
kind: ng.CompletionKind.ENTITY,
sortText: name,
};
});
break;
}
}
return result;
}
function interpolationCompletions(info: AstResult, position: number): ng.CompletionEntry[] {
// Look for an interpolation in at the position.
const templatePath = findTemplateAstAt(info.templateAst, position);
if (!templatePath.tail) {
return [];
}
const visitor = new ExpressionVisitor(
info, position,
() => getExpressionScope(diagnosticInfoFromTemplateInfo(info), templatePath, false));
templatePath.tail.visit(visitor, null);
return visitor.results;
}
// There is a special case of HTML where text that contains a unclosed tag is treated as
// text. For exaple '<h1> Some <a text </h1>' produces a text nodes inside of the H1
// element "Some <a text". We, however, want to treat this as if the user was requesting
// the attributes of an "a" element, not requesting completion in the a text element. This
// code checks for this case and returns element completions if it is detected or undefined
// if it is not.
function voidElementAttributeCompletions(
info: AstResult, path: AstPath<HtmlAst>): ng.CompletionEntry[] {
const tail = path.tail;
if (tail instanceof Text) {
const match = tail.value.match(/<(\w(\w|\d|-)*:)?(\w(\w|\d|-)*)\s/);
// The position must be after the match, otherwise we are still in a place where elements
// are expected (such as `<|a` or `<a|`; we only want attributes for `<a |` or after).
if (match &&
path.position >= (match.index || 0) + match[0].length + tail.sourceSpan.start.offset) {
return attributeCompletionsForElement(info, match[3]);
}
}
return [];
}
class ExpressionVisitor extends NullTemplateVisitor {
private readonly completions = new Map<string, ng.CompletionEntry>();
constructor(
private readonly info: AstResult, private readonly position: number,
private readonly getExpressionScope: () => ng.SymbolTable) {
super();
}
get results(): ng.CompletionEntry[] { return Array.from(this.completions.values()); }
visitDirectiveProperty(ast: BoundDirectivePropertyAst): void {
this.addAttributeValuesToCompletions(ast.value);
}
visitElementProperty(ast: BoundElementPropertyAst): void {
this.addAttributeValuesToCompletions(ast.value);
}
visitEvent(ast: BoundEventAst): void { this.addAttributeValuesToCompletions(ast.handler); }
visitElement(ast: ElementAst): void {
// no-op for now
}
visitAttr(ast: AttrAst) {
// The attribute value is a template expression but the expression AST
// was not produced when the TemplateAst was produced so do that here.
const {templateBindings} = this.info.expressionParser.parseTemplateBindings(
ast.name, ast.value, ast.sourceSpan.toString(), ast.sourceSpan.start.offset);
// Find where the cursor is relative to the start of the attribute value.
const valueRelativePosition = this.position - ast.sourceSpan.start.offset;
// Find the template binding that contains the position
const binding = templateBindings.find(b => inSpan(valueRelativePosition, b.span));
if (!binding) {
return;
}
if (ast.name.startsWith('*')) {
this.microSyntaxInAttributeValue(ast, binding);
} else {
// If the position is in the expression or after the key or there is no key,
// return the expression completions
const span = new ParseSpan(0, ast.value.length);
const offset = ast.sourceSpan.start.offset;
const receiver = new ImplicitReceiver(span, span.toAbsolute(offset));
const expressionAst = new PropertyRead(span, span.toAbsolute(offset), receiver, '');
this.addAttributeValuesToCompletions(expressionAst);
}
}
visitBoundText(ast: BoundTextAst) {
if (inSpan(this.position, ast.value.sourceSpan)) {
const completions = getExpressionCompletions(
this.getExpressionScope(), ast.value, this.position, this.info.template.query);
if (completions) {
this.addSymbolsToCompletions(completions);
}
}
}
private addAttributeValuesToCompletions(value: AST) {
const symbols = getExpressionCompletions(
this.getExpressionScope(), value, this.position, this.info.template.query);
if (symbols) {
this.addSymbolsToCompletions(symbols);
}
}
private addSymbolsToCompletions(symbols: ng.Symbol[]) {
for (const s of symbols) {
if (s.name.startsWith('__') || !s.public || this.completions.has(s.name)) {
continue;
}
this.completions.set(s.name, {
name: s.name,
kind: s.kind as ng.CompletionKind,
sortText: s.name,
insertText: s.callable ? `${s.name}()` : s.name,
});
}
}
/**
* This method handles the completions of attribute values for directives that
* support the microsyntax format. Examples are *ngFor and *ngIf.
* These directives allows declaration of "let" variables, adds context-specific
* symbols like $implicit, index, count, among other behaviors.
* For a complete description of such format, see
* https://angular.io/guide/structural-directives#the-asterisk--prefix
*
* @param attr descriptor for attribute name and value pair
* @param binding template binding for the expression in the attribute
*/
private microSyntaxInAttributeValue(attr: AttrAst, binding: TemplateBinding) {
const key = attr.name.substring(1); // remove leading asterisk
// Find the selector - eg ngFor, ngIf, etc
const selectorInfo = getSelectors(this.info);
const selector = selectorInfo.selectors.find(s => {
// attributes are listed in (attribute, value) pairs
for (let i = 0; i < s.attrs.length; i += 2) {
if (s.attrs[i] === key) {
return true;
}
}
});
if (!selector) {
return;
}
const valueRelativePosition = this.position - attr.sourceSpan.start.offset;
if (binding.keyIsVar) {
const equalLocation = attr.value.indexOf('=');
if (equalLocation > 0 && valueRelativePosition > equalLocation) {
// We are after the '=' in a let clause. The valid values here are the members of the
// template reference's type parameter.
const directiveMetadata = selectorInfo.map.get(selector);
if (directiveMetadata) {
const contextTable =
this.info.template.query.getTemplateContext(directiveMetadata.type.reference);
if (contextTable) {
// This adds symbols like $implicit, index, count, etc.
this.addSymbolsToCompletions(contextTable.values());
return;
}
}
}
}
if (binding.expression && inSpan(valueRelativePosition, binding.expression.ast.span)) {
this.addAttributeValuesToCompletions(binding.expression.ast);
return;
}
// If the expression is incomplete, for example *ngFor="let x of |"
// binding.expression is null. We could still try to provide suggestions
// by looking for symbols that are in scope.
const KW_OF = ' of ';
const ofLocation = attr.value.indexOf(KW_OF);
if (ofLocation > 0 && valueRelativePosition >= ofLocation + KW_OF.length) {
const span = new ParseSpan(0, attr.value.length);
const offset = attr.sourceSpan.start.offset;
const receiver = new ImplicitReceiver(span, span.toAbsolute(offset));
const expressionAst = new PropertyRead(span, span.toAbsolute(offset), receiver, '');
this.addAttributeValuesToCompletions(expressionAst);
}
}
}
function getSourceText(template: ng.TemplateSource, span: ng.Span): string {
return template.source.substring(span.start, span.end);
}
interface AngularAttributes {
/**
* Attributes that support the * syntax. See https://angular.io/api/core/TemplateRef
*/
templateRefs: Set<string>;
/**
* Attributes with the @Input annotation.
*/
inputs: Set<string>;
/**
* Attributes with the @Output annotation.
*/
outputs: Set<string>;
/**
* Attributes that support the [()] or bindon- syntax.
*/
bananas: Set<string>;
/**
* General attributes that match the specified element.
*/
others: Set<string>;
}
/**
* Return all Angular-specific attributes for the element with `elementName`.
* @param info
* @param elementName
*/
function angularAttributes(info: AstResult, elementName: string): AngularAttributes {
const {selectors, map: selectorMap} = getSelectors(info);
const templateRefs = new Set<string>();
const inputs = new Set<string>();
const outputs = new Set<string>();
const bananas = new Set<string>();
const others = new Set<string>();
for (const selector of selectors) {
if (selector.element && selector.element !== elementName) {
continue;
}
const summary = selectorMap.get(selector) !;
const isTemplateRef = hasTemplateReference(summary.type);
// attributes are listed in (attribute, value) pairs
for (let i = 0; i < selector.attrs.length; i += 2) {
const attr = selector.attrs[i];
if (isTemplateRef) {
templateRefs.add(attr);
} else {
others.add(attr);
}
}
for (const input of Object.values(summary.inputs)) {
inputs.add(input);
}
for (const output of Object.values(summary.outputs)) {
outputs.add(output);
}
}
for (const name of inputs) {
// Add banana-in-a-box syntax
// https://angular.io/guide/template-syntax#two-way-binding-
if (outputs.has(`${name}Change`)) {
bananas.add(name);
}
}
return {templateRefs, inputs, outputs, bananas, others};
}
| packages/language-service/src/completions.ts | 1 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.1427294909954071,
0.0032001470681279898,
0.00016394187696278095,
0.00017114426009356976,
0.018482394516468048
] |
{
"id": 2,
"code_window": [
" kind: CompletionKind.METHOD as any,\n",
" insertText: 'myClick()',\n",
" }));\n",
" });\n",
"\n",
" describe('in external template', () => {\n",
" it('should be able to get entity completions in external template', () => {\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'entity-amp');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('for methods of pipe should not include parentheses', () => {\n",
" mockHost.override(TEST_TEMPLATE, `<h1>{{title | lowe~{pipe-method} }}`);\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'pipe-method');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expect(completions).toBeDefined();\n",
" expect(completions !.entries).toContain(jasmine.objectContaining({\n",
" name: 'lowercase',\n",
" kind: CompletionKind.PIPE as any,\n",
" insertText: 'lowercase',\n",
" }));\n",
" });\n",
"\n"
],
"file_path": "packages/language-service/test/completions_spec.ts",
"type": "add",
"edit_start_line_idx": 210
} | README.md
arbitrary-npm-package-main.js
arbitrary_bin.txt
arbitrary_genfiles.txt
bundles
bundles/waffels-secondary.umd.js
bundles/waffels-secondary.umd.js.map
bundles/waffels-secondary.umd.min.js
bundles/waffels-secondary.umd.min.js.map
bundles/waffels.umd.js
bundles/waffels.umd.js.map
bundles/waffels.umd.min.js
bundles/waffels.umd.min.js.map
esm2015
esm2015/example.externs.js
esm2015/example.js
esm2015/index.js
esm2015/mymodule.js
esm2015/secondary
esm2015/secondary/index.js
esm2015/secondary/secondary.externs.js
esm2015/secondary/secondary.js
esm2015/secondary/secondarymodule.js
esm5
esm5/example.js
esm5/index.js
esm5/mymodule.js
esm5/secondary
esm5/secondary/index.js
esm5/secondary/secondary.js
esm5/secondary/secondarymodule.js
example.d.ts
example.metadata.json
extra-styles.css
fesm2015
fesm2015/secondary.js
fesm2015/secondary.js.map
fesm2015/waffels.js
fesm2015/waffels.js.map
fesm5
fesm5/secondary.js
fesm5/secondary.js.map
fesm5/waffels.js
fesm5/waffels.js.map
logo.png
package.json
secondary
secondary/package.json
secondary/secondary.d.ts
secondary/secondary.metadata.json
secondary.d.ts
secondary.metadata.json
some-file.txt
--- README.md ---
Angular
=======
The sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.
Usage information and reference details can be found in [Angular documentation](https://angular.io/docs).
License: MIT
--- arbitrary-npm-package-main.js ---
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const x = 1;
--- arbitrary_bin.txt ---
World
--- arbitrary_genfiles.txt ---
Hello
--- bundles/waffels-secondary.umd.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) :
typeof define === 'function' && define.amd ? define('example/secondary', ['exports', '@angular/core'], factory) :
(global = global || self, factory((global.example = global.example || {}, global.example.secondary = {}), global.ng.core));
}(this, (function (exports, core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var SecondaryModule = /** @class */ (function () {
function SecondaryModule() {
}
SecondaryModule = __decorate([
core.NgModule({})
], SecondaryModule);
return SecondaryModule;
}());
var a = 1;
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generated bundle index. Do not edit.
*/
exports.SecondaryModule = SecondaryModule;
exports.a = a;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=waffels-secondary.umd.js.map
--- bundles/waffels-secondary.umd.min.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core")):"function"==typeof define&&define.amd?define("example/secondary",["exports","@angular/core"],t):t(((e=e||self).example=e.example||{},e.example.secondary={}),e.ng.core)}(this,(function(e,t){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var o=function n(e,t,o,r){var c,f=arguments.length,l=f<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,o):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)l=Reflect.decorate(e,t,o,r);else for(var a=e.length-1;a>=0;a--)(c=e[a])&&(l=(f<3?c(l):f>3?c(t,o,l):c(t,o))||l);return f>3&&l&&Object.defineProperty(t,o,l),l}([t.NgModule({})],(function o(){}));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
e.SecondaryModule=o,e.a=1,Object.defineProperty(e,"__esModule",{value:!0})}));
--- bundles/waffels.umd.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) :
typeof define === 'function' && define.amd ? define('example', ['exports', '@angular/core'], factory) :
(global = global || self, factory(global.example = {}, global.ng.core));
}(this, (function (exports, core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var MyModule = /** @class */ (function () {
function MyModule() {
}
MyModule = __decorate([
core.NgModule({})
], MyModule);
return MyModule;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generated bundle index. Do not edit.
*/
exports.MyModule = MyModule;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=waffels.umd.js.map
--- bundles/waffels.umd.min.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core")):"function"==typeof define&&define.amd?define("example",["exports","@angular/core"],t):t((e=e||self).example={},e.ng.core)}(this,(function(e,t){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var o=function n(e,t,o,r){var f,c=arguments.length,l=c<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,o):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)l=Reflect.decorate(e,t,o,r);else for(var u=e.length-1;u>=0;u--)(f=e[u])&&(l=(c<3?f(l):c>3?f(t,o,l):f(t,o))||l);return c>3&&l&&Object.defineProperty(t,o,l),l}([t.NgModule({})],(function o(){}));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/e.MyModule=o,Object.defineProperty(e,"__esModule",{value:!0})}));
--- esm2015/example.externs.js ---
/** @externs */
/**
* @externs
* @suppress {duplicate,checkTypes}
*/
// NOTE: generated by tsickle, do not edit.
--- esm2015/example.js ---
/**
* Generated bundle index. Do not edit.
*/
export * from './index';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXhhbXBsZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2JhemVsL3Rlc3QvbmdfcGFja2FnZS9leGFtcGxlL2V4YW1wbGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7O0dBRUc7QUFFSCxjQUFjLFNBQVMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogR2VuZXJhdGVkIGJ1bmRsZSBpbmRleC4gRG8gbm90IGVkaXQuXG4gKi9cblxuZXhwb3J0ICogZnJvbSAnLi9pbmRleCc7XG4iXX0=
--- esm2015/index.js ---
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { MyModule } from './mymodule';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9iYXplbC90ZXN0L25nX3BhY2thZ2UvZXhhbXBsZS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFRQSx5QkFBYyxZQUFZLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbmV4cG9ydCAqIGZyb20gJy4vbXltb2R1bGUnOyJdfQ==
--- esm2015/mymodule.js ---
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/mymodule.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { NgModule } from '@angular/core';
export class MyModule {
}
MyModule.decorators = [
{ type: NgModule, args: [{},] }
];
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXltb2R1bGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9iYXplbC90ZXN0L25nX3BhY2thZ2UvZXhhbXBsZS9teW1vZHVsZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFRQSxPQUFPLEVBQUMsUUFBUSxFQUFDLE1BQU0sZUFBZSxDQUFDO0FBSXZDLE1BQU0sT0FBTyxRQUFROzs7WUFEcEIsUUFBUSxTQUFDLEVBQUUiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbmltcG9ydCB7TmdNb2R1bGV9IGZyb20gJ0Bhbmd1bGFyL2NvcmUnO1xuaW1wb3J0IHthfSBmcm9tICcuL3NlY29uZGFyeS9zZWNvbmRhcnltb2R1bGUnO1xuXG5ATmdNb2R1bGUoe30pXG5leHBvcnQgY2xhc3MgTXlNb2R1bGUge1xufSJdfQ==
--- esm2015/secondary/index.js ---
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/secondary/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { SecondaryModule, a } from './secondarymodule';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9iYXplbC90ZXN0L25nX3BhY2thZ2UvZXhhbXBsZS9zZWNvbmRhcnkvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7O0FBUUEsbUNBQWMsbUJBQW1CLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbmV4cG9ydCAqIGZyb20gJy4vc2Vjb25kYXJ5bW9kdWxlJztcbiJdfQ==
--- esm2015/secondary/secondary.externs.js ---
/** @externs */
/**
* @externs
* @suppress {duplicate,checkTypes}
*/
// NOTE: generated by tsickle, do not edit.
--- esm2015/secondary/secondary.js ---
/**
* Generated bundle index. Do not edit.
*/
export * from './index';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2Vjb25kYXJ5LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vcGFja2FnZXMvYmF6ZWwvdGVzdC9uZ19wYWNrYWdlL2V4YW1wbGUvc2Vjb25kYXJ5L3NlY29uZGFyeS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7R0FFRztBQUVILGNBQWMsU0FBUyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBHZW5lcmF0ZWQgYnVuZGxlIGluZGV4LiBEbyBub3QgZWRpdC5cbiAqL1xuXG5leHBvcnQgKiBmcm9tICcuL2luZGV4JztcbiJdfQ==
--- esm2015/secondary/secondarymodule.js ---
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/secondary/secondarymodule.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { NgModule } from '@angular/core';
export class SecondaryModule {
}
SecondaryModule.decorators = [
{ type: NgModule, args: [{},] }
];
/** @type {?} */
export const a = 1;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2Vjb25kYXJ5bW9kdWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vcGFja2FnZXMvYmF6ZWwvdGVzdC9uZ19wYWNrYWdlL2V4YW1wbGUvc2Vjb25kYXJ5L3NlY29uZGFyeW1vZHVsZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFRQSxPQUFPLEVBQUMsUUFBUSxFQUFDLE1BQU0sZUFBZSxDQUFDO0FBR3ZDLE1BQU0sT0FBTyxlQUFlOzs7WUFEM0IsUUFBUSxTQUFDLEVBQUU7OztBQUlaLE1BQU0sT0FBTyxDQUFDLEdBQUcsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuaW1wb3J0IHtOZ01vZHVsZX0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XG5cbkBOZ01vZHVsZSh7fSlcbmV4cG9ydCBjbGFzcyBTZWNvbmRhcnlNb2R1bGUge1xufVxuXG5leHBvcnQgY29uc3QgYSA9IDE7XG4iXX0=
--- esm5/example.js ---
/**
* Generated bundle index. Do not edit.
*/
export * from './index';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXhhbXBsZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2JhemVsL3Rlc3QvbmdfcGFja2FnZS9leGFtcGxlL2V4YW1wbGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7O0dBRUc7QUFFSCxjQUFjLFNBQVMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogR2VuZXJhdGVkIGJ1bmRsZSBpbmRleC4gRG8gbm90IGVkaXQuXG4gKi9cblxuZXhwb3J0ICogZnJvbSAnLi9pbmRleCc7XG4iXX0=
--- esm5/index.js ---
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export * from './mymodule';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9iYXplbC90ZXN0L25nX3BhY2thZ2UvZXhhbXBsZS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0dBTUc7QUFFSCxjQUFjLFlBQVksQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuZXhwb3J0ICogZnJvbSAnLi9teW1vZHVsZSc7Il19
--- esm5/mymodule.js ---
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { __decorate } from "tslib";
import { NgModule } from '@angular/core';
var MyModule = /** @class */ (function () {
function MyModule() {
}
MyModule = __decorate([
NgModule({})
], MyModule);
return MyModule;
}());
export { MyModule };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXltb2R1bGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9iYXplbC90ZXN0L25nX3BhY2thZ2UvZXhhbXBsZS9teW1vZHVsZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0dBTUc7O0FBRUgsT0FBTyxFQUFDLFFBQVEsRUFBQyxNQUFNLGVBQWUsQ0FBQztBQUl2QztJQUFBO0lBQ0EsQ0FBQztJQURZLFFBQVE7UUFEcEIsUUFBUSxDQUFDLEVBQUUsQ0FBQztPQUNBLFFBQVEsQ0FDcEI7SUFBRCxlQUFDO0NBQUEsQUFERCxJQUNDO1NBRFksUUFBUSIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuaW1wb3J0IHtOZ01vZHVsZX0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XG5pbXBvcnQge2F9IGZyb20gJy4vc2Vjb25kYXJ5L3NlY29uZGFyeW1vZHVsZSc7XG5cbkBOZ01vZHVsZSh7fSlcbmV4cG9ydCBjbGFzcyBNeU1vZHVsZSB7XG59Il19
--- esm5/secondary/index.js ---
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export * from './secondarymodule';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi8uLi9wYWNrYWdlcy9iYXplbC90ZXN0L25nX3BhY2thZ2UvZXhhbXBsZS9zZWNvbmRhcnkvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7OztHQU1HO0FBRUgsY0FBYyxtQkFBbUIsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuZXhwb3J0ICogZnJvbSAnLi9zZWNvbmRhcnltb2R1bGUnO1xuIl19
--- esm5/secondary/secondary.js ---
/**
* Generated bundle index. Do not edit.
*/
export * from './index';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2Vjb25kYXJ5LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vcGFja2FnZXMvYmF6ZWwvdGVzdC9uZ19wYWNrYWdlL2V4YW1wbGUvc2Vjb25kYXJ5L3NlY29uZGFyeS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7R0FFRztBQUVILGNBQWMsU0FBUyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBHZW5lcmF0ZWQgYnVuZGxlIGluZGV4LiBEbyBub3QgZWRpdC5cbiAqL1xuXG5leHBvcnQgKiBmcm9tICcuL2luZGV4JztcbiJdfQ==
--- esm5/secondary/secondarymodule.js ---
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { __decorate } from "tslib";
import { NgModule } from '@angular/core';
var SecondaryModule = /** @class */ (function () {
function SecondaryModule() {
}
SecondaryModule = __decorate([
NgModule({})
], SecondaryModule);
return SecondaryModule;
}());
export { SecondaryModule };
export var a = 1;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2Vjb25kYXJ5bW9kdWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vcGFja2FnZXMvYmF6ZWwvdGVzdC9uZ19wYWNrYWdlL2V4YW1wbGUvc2Vjb25kYXJ5L3NlY29uZGFyeW1vZHVsZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0dBTUc7O0FBRUgsT0FBTyxFQUFDLFFBQVEsRUFBQyxNQUFNLGVBQWUsQ0FBQztBQUd2QztJQUFBO0lBQ0EsQ0FBQztJQURZLGVBQWU7UUFEM0IsUUFBUSxDQUFDLEVBQUUsQ0FBQztPQUNBLGVBQWUsQ0FDM0I7SUFBRCxzQkFBQztDQUFBLEFBREQsSUFDQztTQURZLGVBQWU7QUFHNUIsTUFBTSxDQUFDLElBQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cblxuaW1wb3J0IHtOZ01vZHVsZX0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XG5cbkBOZ01vZHVsZSh7fSlcbmV4cG9ydCBjbGFzcyBTZWNvbmRhcnlNb2R1bGUge1xufVxuXG5leHBvcnQgY29uc3QgYSA9IDE7XG4iXX0=
--- example.d.ts ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
export declare class MyModule {
}
export { }
--- example.metadata.json ---
{"__symbolic":"module","version":4,"metadata":{"MyModule":{"__symbolic":"class","decorators":[{"__symbolic":"call","expression":{"__symbolic":"reference","module":"@angular/core","name":"NgModule","line":11,"character":1},"arguments":[{}]}],"members":{}}},"origins":{"MyModule":"./example"},"importAs":"example"}
--- extra-styles.css ---
.special {
color: goldenrod;
}
--- fesm2015/secondary.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
import { NgModule } from '@angular/core';
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/secondary/secondarymodule.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class SecondaryModule {
}
SecondaryModule.decorators = [
{ type: NgModule, args: [{},] }
];
/** @type {?} */
const a = 1;
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/secondary/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
export { SecondaryModule, a };
//# sourceMappingURL=secondary.js.map
--- fesm2015/waffels.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
import { NgModule } from '@angular/core';
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/mymodule.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class MyModule {
}
MyModule.decorators = [
{ type: NgModule, args: [{},] }
];
/**
* @fileoverview added by tsickle
* Generated from: packages/bazel/test/ng_package/example/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
export { MyModule };
//# sourceMappingURL=waffels.js.map
--- fesm5/secondary.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var SecondaryModule = /** @class */ (function () {
function SecondaryModule() {
}
SecondaryModule = __decorate([
NgModule({})
], SecondaryModule);
return SecondaryModule;
}());
var a = 1;
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generated bundle index. Do not edit.
*/
export { SecondaryModule, a };
//# sourceMappingURL=secondary.js.map
--- fesm5/waffels.js ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var MyModule = /** @class */ (function () {
function MyModule() {
}
MyModule = __decorate([
NgModule({})
], MyModule);
return MyModule;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generated bundle index. Do not edit.
*/
export { MyModule };
//# sourceMappingURL=waffels.js.map
--- logo.png ---
9db278d630f5fabd8e7ba16c2e329a3a
--- package.json ---
{
"name": "example",
"version": "0.0.0",
"main": "./bundles/example.umd.js",
"fesm5": "./fesm5/example.js",
"fesm2015": "./fesm2015/example.js",
"esm5": "./esm5/example.js",
"esm2015": "./esm2015/example.js",
"typings": "./example.d.ts",
"module": "./fesm5/example.js",
"es2015": "./fesm2015/example.js"
}
--- secondary/package.json ---
{
"name": "example/secondary",
"main": "../bundles/example-secondary.umd.js",
"fesm5": "../fesm5/secondary.js",
"fesm2015": "../fesm2015/secondary.js",
"esm5": "../esm5/secondary/secondary.js",
"esm2015": "../esm2015/secondary/secondary.js",
"typings": "./secondary.d.ts",
"module": "../fesm5/secondary.js",
"es2015": "../fesm2015/secondary.js"
}
--- secondary/secondary.d.ts ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
export declare const a = 1;
export declare class SecondaryModule {
}
export { }
--- secondary/secondary.metadata.json ---
{"__symbolic":"module","version":4,"metadata":{"SecondaryModule":{"__symbolic":"class","decorators":[{"__symbolic":"call","expression":{"__symbolic":"reference","module":"@angular/core","name":"NgModule","line":10,"character":1},"arguments":[{}]}],"members":{}},"a":1},"origins":{"SecondaryModule":"./secondary","a":"./secondary"},"importAs":"example/secondary"}
--- secondary.d.ts ---
/**
* @license Angular v0.0.0
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
export * from './secondary/secondary';
--- secondary.metadata.json ---
{"__symbolic":"module","version":3,"metadata":{},"exports":[{"from":"./secondary/secondary"}],"flatModuleIndexRedirect":true,"importAs":"example/secondary"}
--- some-file.txt ---
This file is just copied into the package.
| packages/bazel/test/ng_package/example_package.golden | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.0007447695825248957,
0.00017794423911254853,
0.00016204765415750444,
0.0001724412722978741,
0.00005429207521956414
] |
{
"id": 2,
"code_window": [
" kind: CompletionKind.METHOD as any,\n",
" insertText: 'myClick()',\n",
" }));\n",
" });\n",
"\n",
" describe('in external template', () => {\n",
" it('should be able to get entity completions in external template', () => {\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'entity-amp');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('for methods of pipe should not include parentheses', () => {\n",
" mockHost.override(TEST_TEMPLATE, `<h1>{{title | lowe~{pipe-method} }}`);\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'pipe-method');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expect(completions).toBeDefined();\n",
" expect(completions !.entries).toContain(jasmine.objectContaining({\n",
" name: 'lowercase',\n",
" kind: CompletionKind.PIPE as any,\n",
" insertText: 'lowercase',\n",
" }));\n",
" });\n",
"\n"
],
"file_path": "packages/language-service/test/completions_spec.ts",
"type": "add",
"edit_start_line_idx": 210
} | import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
// a real app should make a common bundle for libraries instead of bundling them
// in both the main module & the lazy module, but we don't care about size here
export default {
input: 'dist/src/lazy.module.js',
output: {
sourceMap: true,
},
treeshake: true,
plugins: [
nodeResolve()
]
};
| integration/dynamic-compiler/rollup.lazy.config.js | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.0001743736647767946,
0.00017261075845453888,
0.00017084785213228315,
0.00017261075845453888,
0.0000017629063222557306
] |
{
"id": 2,
"code_window": [
" kind: CompletionKind.METHOD as any,\n",
" insertText: 'myClick()',\n",
" }));\n",
" });\n",
"\n",
" describe('in external template', () => {\n",
" it('should be able to get entity completions in external template', () => {\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'entity-amp');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expectContain(completions, CompletionKind.ENTITY, ['&', '>', '<', 'ι']);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('for methods of pipe should not include parentheses', () => {\n",
" mockHost.override(TEST_TEMPLATE, `<h1>{{title | lowe~{pipe-method} }}`);\n",
" const marker = mockHost.getLocationMarkerFor(TEST_TEMPLATE, 'pipe-method');\n",
" const completions = ngLS.getCompletionsAt(TEST_TEMPLATE, marker.start);\n",
" expect(completions).toBeDefined();\n",
" expect(completions !.entries).toContain(jasmine.objectContaining({\n",
" name: 'lowercase',\n",
" kind: CompletionKind.PIPE as any,\n",
" insertText: 'lowercase',\n",
" }));\n",
" });\n",
"\n"
],
"file_path": "packages/language-service/test/completions_spec.ts",
"type": "add",
"edit_start_line_idx": 210
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function(_global) {
var allTasks = _global['__zone_symbol__performance_tasks'];
if (!allTasks) {
allTasks = _global['__zone_symbol__performance_tasks'] = [];
}
var mark = _global['__zone_symbol__mark'] = function(name) {
performance && performance['mark'] && performance['mark'](name);
};
var measure = _global['__zone_symbol__measure'] = function(name, label) {
performance && performance['measure'] && performance['measure'](name, label);
};
var getEntries = _global['__zone_symbol__getEntries'] = function() {
performance && performance['getEntries'] && performance['getEntries']();
};
var getEntriesByName = _global['__zone_symbol__getEntriesByName'] = function(name) {
return performance && performance['getEntriesByName'] && performance['getEntriesByName'](name);
};
var clearMarks = _global['__zone_symbol__clearMarks'] = function(name) {
return performance && performance['clearMarks'] && performance['clearMarks'](name);
};
var clearMeasures = _global['__zone_symbol__clearMeasures'] = function(name) {
return performance && performance['clearMeasures'] && performance['clearMeasures'](name);
};
var averageMeasures = _global['__zone_symbol__averageMeasures'] = function(name, times) {
var sum = _global['__zone_symbol__getEntriesByName'](name)
.filter(function(m) { return m.entryType === 'measure'; })
.map(function(m) { return m.duration })
.reduce(function(sum, d) { return sum + d; });
return sum / times;
};
var serialPromise = _global['__zone_symbol__serialPromise'] =
function(promiseFactories) {
let lastPromise;
for (var i = 0; i < promiseFactories.length; i++) {
var promiseFactory = promiseFactories[i];
if (!lastPromise) {
lastPromise = promiseFactory.factory(promiseFactory.context).then(function(value) {
return {value, idx: 0};
});
} else {
lastPromise = lastPromise.then(function(ctx) {
var idx = ctx.idx + 1;
var promiseFactory = promiseFactories[idx];
return promiseFactory.factory(promiseFactory.context).then(function(value) {
return {value, idx};
});
});
}
}
return lastPromise;
}
var callbackContext = _global['__zone_symbol__callbackContext'] = {};
var zone = _global['__zone_symbol__callbackZone'] = Zone.current.fork({
name: 'callback',
onScheduleTask: function(delegate, curr, target, task) {
delegate.scheduleTask(target, task);
if (task.type === callbackContext.type &&
task.source.indexOf(callbackContext.source) !== -1) {
if (task.type === 'macroTask' || task.type === 'eventTask') {
var invoke = task.invoke;
task.invoke = function() {
mark(callbackContext.measureName);
var result = invoke.apply(this, arguments);
measure(callbackContext.measureName, callbackContext.measureName);
return result;
};
} else if (task.type === 'microTask') {
var callback = task.callback;
task.callback = function() {
mark(callbackContext.measureName);
var result = callback.apply(this, arguments);
measure(callbackContext.measureName, callbackContext.measureName);
return result;
};
}
}
return task;
}
});
var runAsync = _global['__zone_symbol__runAsync'] = function(testFn, times, _delay) {
var delay = _delay | 100;
const fnPromise = function() {
return new Promise(function(res, rej) {
// run test with a setTimeout
// several times to decrease measurement error
setTimeout(function() { testFn().then(function() { res(); }); }, delay);
});
};
var promiseFactories = [];
for (var i = 0; i < times; i++) {
promiseFactories.push({factory: fnPromise, context: {}});
}
return serialPromise(promiseFactories);
};
var getNativeMethodName = function(nativeWithSymbol) {
return nativeWithSymbol.replace('__zone_symbol__', 'native_');
};
function testAddRemove(api, count) {
var timerId = [];
var name = api.method;
mark(name);
for (var i = 0; i < count; i++) {
timerId.push(api.run());
}
measure(name, name);
if (api.supportClear) {
var clearName = api.clearMethod;
mark(clearName);
for (var i = 0; i < count; i++) {
api.runClear(timerId[i]);
}
measure(clearName, clearName);
}
timerId = [];
var nativeName = getNativeMethodName(api.nativeMethod);
mark(nativeName);
for (var i = 0; i < count; i++) {
timerId.push(api.nativeRun());
}
measure(nativeName, nativeName);
if (api.supportClear) {
var nativeClearName = getNativeMethodName(api.nativeClearMethod);
mark(nativeClearName);
for (var i = 0; i < count; i++) {
api.nativeRunClear(timerId[i]);
}
measure(nativeClearName, nativeClearName);
}
return Promise.resolve(1);
}
function testCallback(api, count) {
var promises = [Promise.resolve(1)];
for (var i = 0; i < count; i++) {
var r = api.run();
if (api.isAsync) {
promises.push(r);
}
}
for (var i = 0; i < count; i++) {
var r = api.nativeRun();
if (api.isAsync) {
promises.push(r);
}
}
return Promise.all(promises);
}
function measureCallback(api, ops) {
var times = ops.times;
var displayText = ops.displayText;
var rawData = ops.rawData;
var summary = ops.summary;
var name = api.method;
var nativeName = getNativeMethodName(api.nativeMethod);
var measure = averageMeasures(name, times);
var nativeMeasure = averageMeasures(nativeName, times);
displayText += `- ${name} costs ${measure} ms\n`;
displayText += `- ${nativeName} costs ${nativeMeasure} ms\n`;
var absolute = Math.floor(1000 * (measure - nativeMeasure)) / 1000;
displayText += `# ${name} is ${absolute}ms slower than ${nativeName}\n`;
rawData[name + '_measure'] = measure;
rawData[nativeName + '_measure'] = nativeMeasure;
summary[name] = absolute + 'ms';
}
function measureAddRemove(api, ops) {
var times = ops.times;
var displayText = ops.displayText;
var rawData = ops.rawData;
var summary = ops.summary;
var name = api.method;
var nativeName = getNativeMethodName(api.nativeMethod);
var measure = averageMeasures(name, times);
var nativeMeasure = averageMeasures(nativeName, times);
displayText += `- ${name} costs ${measure} ms\n`;
displayText += `- ${nativeName} costs ${nativeMeasure} ms\n`;
var percent = Math.floor(100 * (measure - nativeMeasure) / nativeMeasure);
displayText += `# ${name} is ${percent}% slower than ${nativeName}\n`;
rawData[name + '_measure'] = measure;
rawData[nativeName + '_measure'] = nativeMeasure;
summary[name] = percent + '%';
if (api.supportClear) {
var clearName = api.clearMethod;
var nativeClearName = getNativeMethodName(api.nativeClearMethod);
var clearMeasure = averageMeasures(clearName, times);
var nativeClearMeasure = averageMeasures(nativeClearName, times);
var clearPercent = Math.floor(100 * (clearMeasure - nativeClearMeasure) / nativeClearMeasure);
displayText += `- ${clearName} costs ${clearMeasure} ms\n`;
displayText += `- ${nativeClearName} costs ${nativeClearMeasure} ms\n`;
displayText += `# ${clearName} is ${clearPercent}% slower than ${nativeClearName}\n`;
rawData[clearName + '_measure'] = clearMeasure;
rawData[nativeClearName + '_measure'] = nativeClearMeasure;
summary[clearName] = clearPercent + '%';
}
}
var testRunner = _global['__zone_symbol__testRunner'] = function(testTarget) {
var title = testTarget.title;
var apis = testTarget.apis;
var methods = apis.reduce(function(acc, api) {
return acc.concat([
api.method, api.nativeMethod
].concat(api.supportClear ? [api.clearMethod, api.nativeClearMethod] : [])
.concat[api.method + '_callback', api.nativeMethod + '_callback']);
}, []);
var times = testTarget.times;
allTasks.push({
title: title,
cleanFn: function() {
methods.forEach(function(m) {
clearMarks(m);
clearMeasures(m);
});
},
before: function() { testTarget.before && testTarget.before(); },
after: function() { testTarget.after && testTarget.after(); },
testFn: function() {
var count = typeof testTarget.count === 'number' ? testTarget.count : 10000;
var times = typeof testTarget.times === 'number' ? testTarget.times : 5;
var testFunction = function() {
var promises = [];
apis.forEach(function(api) {
if (api.isCallback) {
var r = testCallback(api, count / 100);
promises.push(api.isAsync ? r : Promise.resolve(1));
} else {
var r = testAddRemove(api, count);
promises.push[api.isAsync ? r : Promise.resolve(1)];
}
});
return Promise.all(promises);
};
return runAsync(testFunction, times).then(function() {
var displayText = `running ${count} times\n`;
var rawData = {};
var summary = {};
apis.forEach(function(api) {
if (api.isCallback) {
measureCallback(api, {times, displayText, rawData, summary});
} else {
measureAddRemove(api, {times, displayText, rawData, summary});
}
});
return Promise.resolve({displayText: displayText, rawData: rawData, summary: summary});
});
}
});
};
}(typeof window === 'undefined' ? global : window));
| packages/zone.js/test/performance/performance_setup.js | 0 | https://github.com/angular/angular/commit/ba2fd31e62cdbe4a22941fa4c26ff7f84f3a1d64 | [
0.00017652669339440763,
0.00017162891163025051,
0.0001650268823141232,
0.0001716201368253678,
0.000002229586925750482
] |
{
"id": 0,
"code_window": [
" query += ' WHERE ' + whereConditions.join(' ');\n",
" }\n",
" }\n",
"\n",
" return query;\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (type === 'MEASUREMENTS')\n",
" {\n",
" query += ' LIMIT 100';\n",
" //Solve issue #2524 by limiting the number of measurements returned\n",
" //LIMIT must be after WITH MEASUREMENT and WHERE clauses\n",
" //This also could be used for TAG KEYS and TAG VALUES, if desired\n",
" }\n"
],
"file_path": "public/app/plugins/datasource/influxdb/query_builder.js",
"type": "replace",
"edit_start_line_idx": 93
} | import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import InfluxQueryBuilder from '../query_builder';
describe('InfluxQueryBuilder', function() {
describe('when building explore queries', function() {
it('should only have measurement condition in tag keys query given query with measurement', function() {
var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM "cpu"');
});
it('should handle regex measurement in tag keys query', function() {
var builder = new InfluxQueryBuilder({
measurement: '/.*/', tags: []
});
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM /.*/');
});
it('should have no conditions in tags keys query given query with no measurement or tag', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS');
});
it('should have where condition in tag keys query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'host', value: 'se1'}] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be("SHOW TAG KEYS WHERE \"host\" = 'se1'");
});
it('should have no conditions in measurement query for query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have no conditions in measurement query for query with no tags and empty query', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');
});
it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be("SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \"app\" = 'email'");
});
it('should have where condition in measurement query for query with tags', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be("SHOW MEASUREMENTS WHERE \"app\" = 'email'");
});
it('should have where tag name IN filter in tag values query for query with one tag', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'asdsadsad'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES WITH KEY = "app"');
});
it('should have measurement tag condition and tag name IN filter in tag values query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" = \'server1\'');
});
it('should switch to regex operator in tag condition', function() {
var builder = new InfluxQueryBuilder({
measurement: 'cpu',
tags: [{key: 'host', value: '/server.*/'}]
});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" =~ /server.*/');
});
it('should build show field query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM "cpu"');
});
it('should build show field query with regexp', function() {
var builder = new InfluxQueryBuilder({measurement: '/$var/', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM /$var/');
});
it('should build show retention policies query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: []}, 'site');
var query = builder.buildExploreQuery('RETENTION POLICIES');
expect(query).to.be('SHOW RETENTION POLICIES on "site"');
});
});
});
| public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts | 1 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.006953966338187456,
0.003931202460080385,
0.0001732648815959692,
0.004142280202358961,
0.0018060507718473673
] |
{
"id": 0,
"code_window": [
" query += ' WHERE ' + whereConditions.join(' ');\n",
" }\n",
" }\n",
"\n",
" return query;\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (type === 'MEASUREMENTS')\n",
" {\n",
" query += ' LIMIT 100';\n",
" //Solve issue #2524 by limiting the number of measurements returned\n",
" //LIMIT must be after WITH MEASUREMENT and WHERE clauses\n",
" //This also could be used for TAG KEYS and TAG VALUES, if desired\n",
" }\n"
],
"file_path": "public/app/plugins/datasource/influxdb/query_builder.js",
"type": "replace",
"edit_start_line_idx": 93
} | ///<amd-dependency path="test/specs/helpers" name="helpers" />
import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import moment from 'moment';
import IndexPattern from '../index_pattern';
describe('IndexPattern', function() {
describe('when getting index for today', function() {
it('should return correct index name', function() {
var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily');
var expected = 'asd-' + moment.utc().format('YYYY.MM.DD');
expect(pattern.getIndexForToday()).to.be(expected);
});
});
describe('when getting index list for time range', function() {
describe('no interval', function() {
it('should return correct index', function() {
var pattern = new IndexPattern('my-metrics');
var from = new Date(2015, 4, 30, 1, 2, 3);
var to = new Date(2015, 5, 1, 12, 5 , 6);
expect(pattern.getIndexList(from, to)).to.eql('my-metrics');
});
});
describe('daily', function() {
it('should return correct index list', function() {
var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily');
var from = new Date(1432940523000);
var to = new Date(1433153106000);
var expected = [
'asd-2015.05.29',
'asd-2015.05.30',
'asd-2015.05.31',
'asd-2015.06.01',
];
expect(pattern.getIndexList(from, to)).to.eql(expected);
});
});
});
});
| public/app/plugins/datasource/elasticsearch/specs/index_pattern_specs.ts | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00017439029761590064,
0.00017225209739990532,
0.0001686073956079781,
0.0001731771626509726,
0.0000021710088731197175
] |
{
"id": 0,
"code_window": [
" query += ' WHERE ' + whereConditions.join(' ');\n",
" }\n",
" }\n",
"\n",
" return query;\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (type === 'MEASUREMENTS')\n",
" {\n",
" query += ' LIMIT 100';\n",
" //Solve issue #2524 by limiting the number of measurements returned\n",
" //LIMIT must be after WITH MEASUREMENT and WHERE clauses\n",
" //This also could be used for TAG KEYS and TAG VALUES, if desired\n",
" }\n"
],
"file_path": "public/app/plugins/datasource/influxdb/query_builder.js",
"type": "replace",
"edit_start_line_idx": 93
} | // +build go1.3
// Copyright 2014 The Macaron Authors
//
// 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.
// Package macaron is a high productive and modular web framework in Go.
package macaron
import (
"io"
"log"
"net/http"
"os"
"reflect"
"strings"
"github.com/Unknwon/com"
"gopkg.in/ini.v1"
"github.com/go-macaron/inject"
)
const _VERSION = "0.8.0.1013"
func Version() string {
return _VERSION
}
// Handler can be any callable function.
// Macaron attempts to inject services into the handler's argument list,
// and panics if an argument could not be fullfilled via dependency injection.
type Handler interface{}
// validateHandler makes sure a handler is a callable function,
// and panics if it is not.
func validateHandler(h Handler) {
if reflect.TypeOf(h).Kind() != reflect.Func {
panic("Macaron handler must be a callable function")
}
}
// validateHandlers makes sure handlers are callable functions,
// and panics if any of them is not.
func validateHandlers(handlers []Handler) {
for _, h := range handlers {
validateHandler(h)
}
}
// Macaron represents the top level web application.
// inject.Injector methods can be invoked to map services on a global level.
type Macaron struct {
inject.Injector
befores []BeforeHandler
handlers []Handler
action Handler
hasURLPrefix bool
urlPrefix string // For suburl support.
*Router
logger *log.Logger
}
// NewWithLogger creates a bare bones Macaron instance.
// Use this method if you want to have full control over the middleware that is used.
// You can specify logger output writer with this function.
func NewWithLogger(out io.Writer) *Macaron {
m := &Macaron{
Injector: inject.New(),
action: func() {},
Router: NewRouter(),
logger: log.New(out, "[Macaron] ", 0),
}
m.Router.m = m
m.Map(m.logger)
m.Map(defaultReturnHandler())
m.NotFound(http.NotFound)
m.InternalServerError(func(rw http.ResponseWriter, err error) {
http.Error(rw, err.Error(), 500)
})
return m
}
// New creates a bare bones Macaron instance.
// Use this method if you want to have full control over the middleware that is used.
func New() *Macaron {
return NewWithLogger(os.Stdout)
}
// Classic creates a classic Macaron with some basic default middleware:
// mocaron.Logger, mocaron.Recovery and mocaron.Static.
func Classic() *Macaron {
m := New()
m.Use(Logger())
m.Use(Recovery())
m.Use(Static("public"))
return m
}
// Handlers sets the entire middleware stack with the given Handlers.
// This will clear any current middleware handlers,
// and panics if any of the handlers is not a callable function
func (m *Macaron) Handlers(handlers ...Handler) {
m.handlers = make([]Handler, 0)
for _, handler := range handlers {
m.Use(handler)
}
}
// Action sets the handler that will be called after all the middleware has been invoked.
// This is set to macaron.Router in a macaron.Classic().
func (m *Macaron) Action(handler Handler) {
validateHandler(handler)
m.action = handler
}
// BeforeHandler represents a handler executes at beginning of every request.
// Macaron stops future process when it returns true.
type BeforeHandler func(rw http.ResponseWriter, req *http.Request) bool
func (m *Macaron) Before(handler BeforeHandler) {
m.befores = append(m.befores, handler)
}
// Use adds a middleware Handler to the stack,
// and panics if the handler is not a callable func.
// Middleware Handlers are invoked in the order that they are added.
func (m *Macaron) Use(handler Handler) {
validateHandler(handler)
m.handlers = append(m.handlers, handler)
}
func (m *Macaron) createContext(rw http.ResponseWriter, req *http.Request) *Context {
c := &Context{
Injector: inject.New(),
handlers: m.handlers,
action: m.action,
index: 0,
Router: m.Router,
Req: Request{req},
Resp: NewResponseWriter(rw),
Data: make(map[string]interface{}),
}
c.SetParent(m)
c.Map(c)
c.MapTo(c.Resp, (*http.ResponseWriter)(nil))
c.Map(req)
return c
}
// ServeHTTP is the HTTP Entry point for a Macaron instance.
// Useful if you want to control your own HTTP server.
// Be aware that none of middleware will run without registering any router.
func (m *Macaron) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if m.hasURLPrefix {
req.URL.Path = strings.TrimPrefix(req.URL.Path, m.urlPrefix)
}
for _, h := range m.befores {
if h(rw, req) {
return
}
}
m.Router.ServeHTTP(rw, req)
}
func GetDefaultListenInfo() (string, int) {
host := os.Getenv("HOST")
if len(host) == 0 {
host = "0.0.0.0"
}
port := com.StrTo(os.Getenv("PORT")).MustInt()
if port == 0 {
port = 4000
}
return host, port
}
// Run the http server. Listening on os.GetEnv("PORT") or 4000 by default.
func (m *Macaron) Run(args ...interface{}) {
host, port := GetDefaultListenInfo()
if len(args) == 1 {
switch arg := args[0].(type) {
case string:
host = arg
case int:
port = arg
}
} else if len(args) >= 2 {
if arg, ok := args[0].(string); ok {
host = arg
}
if arg, ok := args[1].(int); ok {
port = arg
}
}
addr := host + ":" + com.ToStr(port)
logger := m.GetVal(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s (%s)\n", addr, Env)
logger.Fatalln(http.ListenAndServe(addr, m))
}
// SetURLPrefix sets URL prefix of router layer, so that it support suburl.
func (m *Macaron) SetURLPrefix(prefix string) {
m.urlPrefix = prefix
m.hasURLPrefix = len(m.urlPrefix) > 0
}
// ____ ____ .__ ___. .__
// \ \ / /____ _______|__|____ \_ |__ | | ____ ______
// \ Y /\__ \\_ __ \ \__ \ | __ \| | _/ __ \ / ___/
// \ / / __ \| | \/ |/ __ \| \_\ \ |_\ ___/ \___ \
// \___/ (____ /__| |__(____ /___ /____/\___ >____ >
// \/ \/ \/ \/ \/
const (
DEV = "development"
PROD = "production"
TEST = "test"
)
var (
// Env is the environment that Macaron is executing in.
// The MACARON_ENV is read on initialization to set this variable.
Env = DEV
// Path of work directory.
Root string
// Flash applies to current request.
FlashNow bool
// Configuration convention object.
cfg *ini.File
)
func setENV(e string) {
if len(e) > 0 {
Env = e
}
}
func init() {
setENV(os.Getenv("MACARON_ENV"))
var err error
Root, err = os.Getwd()
if err != nil {
panic("error getting work directory: " + err.Error())
}
}
// SetConfig sets data sources for configuration.
func SetConfig(source interface{}, others ...interface{}) (_ *ini.File, err error) {
cfg, err = ini.Load(source, others...)
return Config(), err
}
// Config returns configuration convention object.
// It returns an empty object if there is no one available.
func Config() *ini.File {
if cfg == nil {
return ini.Empty()
}
return cfg
}
| vendor/gopkg.in/macaron.v1/macaron.go | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0007020804332569242,
0.00022871528926771134,
0.00016309431521221995,
0.0001702726585790515,
0.00014149547496344894
] |
{
"id": 0,
"code_window": [
" query += ' WHERE ' + whereConditions.join(' ');\n",
" }\n",
" }\n",
"\n",
" return query;\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (type === 'MEASUREMENTS')\n",
" {\n",
" query += ' LIMIT 100';\n",
" //Solve issue #2524 by limiting the number of measurements returned\n",
" //LIMIT must be after WITH MEASUREMENT and WHERE clauses\n",
" //This also could be used for TAG KEYS and TAG VALUES, if desired\n",
" }\n"
],
"file_path": "public/app/plugins/datasource/influxdb/query_builder.js",
"type": "replace",
"edit_start_line_idx": 93
} | # This source code refers to The Go Authors for copyright purposes.
# The master list of authors is in the main Go distribution,
# visible at http://tip.golang.org/AUTHORS.
| vendor/golang.org/x/oauth2/AUTHORS | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00017548902542330325,
0.00017548902542330325,
0.00017548902542330325,
0.00017548902542330325,
0
] |
{
"id": 1,
"code_window": [
"\n",
" it('should have no conditions in measurement query for query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 36
} | define([
'lodash'
],
function (_) {
'use strict';
function InfluxQueryBuilder(target, database) {
this.target = target;
this.database = database;
}
function renderTagCondition (tag, index) {
var str = "";
var operator = tag.operator;
var value = tag.value;
if (index > 0) {
str = (tag.condition || 'AND') + ' ';
}
if (!operator) {
if (/^\/.*\/$/.test(tag.value)) {
operator = '=~';
} else {
operator = '=';
}
}
// quote value unless regex or number
if (operator !== '=~' && operator !== '!~' && isNaN(+value)) {
value = "'" + value + "'";
}
return str + '"' + tag.key + '" ' + operator + ' ' + value;
}
var p = InfluxQueryBuilder.prototype;
p.build = function() {
return this.target.rawQuery ? this._modifyRawQuery() : this._buildQuery();
};
p.buildExploreQuery = function(type, withKey, withMeasurementFilter) {
var query;
var measurement;
if (type === 'TAG_KEYS') {
query = 'SHOW TAG KEYS';
measurement = this.target.measurement;
} else if (type === 'TAG_VALUES') {
query = 'SHOW TAG VALUES';
measurement = this.target.measurement;
} else if (type === 'MEASUREMENTS') {
query = 'SHOW MEASUREMENTS';
if (withMeasurementFilter)
{
query += ' WITH MEASUREMENT =~ /' + withMeasurementFilter +'/';
}
} else if (type === 'FIELDS') {
if (!this.target.measurement.match('^/.*/')) {
return 'SHOW FIELD KEYS FROM "' + this.target.measurement + '"';
} else {
return 'SHOW FIELD KEYS FROM ' + this.target.measurement;
}
} else if (type === 'RETENTION POLICIES') {
query = 'SHOW RETENTION POLICIES on "' + this.database + '"';
return query;
}
if (measurement) {
if (!measurement.match('^/.*/') && !measurement.match(/^merge\(.*\)/)) {
measurement = '"' + measurement+ '"';
}
query += ' FROM ' + measurement;
}
if (withKey) {
query += ' WITH KEY = "' + withKey + '"';
}
if (this.target.tags && this.target.tags.length > 0) {
var whereConditions = _.reduce(this.target.tags, function(memo, tag) {
// do not add a condition for the key we want to explore for
if (tag.key === withKey) {
return memo;
}
memo.push(renderTagCondition(tag, memo.length));
return memo;
}, []);
if (whereConditions.length > 0) {
query += ' WHERE ' + whereConditions.join(' ');
}
}
return query;
};
return InfluxQueryBuilder;
});
| public/app/plugins/datasource/influxdb/query_builder.js | 1 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.9921660423278809,
0.39633283019065857,
0.00017398734053131193,
0.004594678059220314,
0.48262691497802734
] |
{
"id": 1,
"code_window": [
"\n",
" it('should have no conditions in measurement query for query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 36
} | [
{
"given": {
"foo": [{"name": "a"}, {"name": "b"}],
"bar": {"baz": "qux"}
},
"cases": [
{
"expression": "@",
"result": {
"foo": [{"name": "a"}, {"name": "b"}],
"bar": {"baz": "qux"}
}
},
{
"expression": "@.bar",
"result": {"baz": "qux"}
},
{
"expression": "@.foo[0]",
"result": {"name": "a"}
}
]
}
]
| vendor/github.com/jmespath/go-jmespath/compliance/current.json | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00017179761198349297,
0.0001706806942820549,
0.00016955861065071076,
0.00017068584566004574,
9.140757128989208e-7
] |
{
"id": 1,
"code_window": [
"\n",
" it('should have no conditions in measurement query for query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 36
} | // +build codegen
package endpoints
import (
"fmt"
"io"
"reflect"
"strings"
"text/template"
"unicode"
)
// A CodeGenOptions are the options for code generating the endpoints into
// Go code from the endpoints model definition.
type CodeGenOptions struct {
// Options for how the model will be decoded.
DecodeModelOptions DecodeModelOptions
}
// Set combines all of the option functions together
func (d *CodeGenOptions) Set(optFns ...func(*CodeGenOptions)) {
for _, fn := range optFns {
fn(d)
}
}
// CodeGenModel given a endpoints model file will decode it and attempt to
// generate Go code from the model definition. Error will be returned if
// the code is unable to be generated, or decoded.
func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGenOptions)) error {
var opts CodeGenOptions
opts.Set(optFns...)
resolver, err := DecodeModel(modelFile, func(d *DecodeModelOptions) {
*d = opts.DecodeModelOptions
})
if err != nil {
return err
}
tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl))
if err := tmpl.ExecuteTemplate(outFile, "defaults", resolver); err != nil {
return fmt.Errorf("failed to execute template, %v", err)
}
return nil
}
func toSymbol(v string) string {
out := []rune{}
for _, c := range strings.Title(v) {
if !(unicode.IsNumber(c) || unicode.IsLetter(c)) {
continue
}
out = append(out, c)
}
return string(out)
}
func quoteString(v string) string {
return fmt.Sprintf("%q", v)
}
func regionConstName(p, r string) string {
return toSymbol(p) + toSymbol(r)
}
func partitionGetter(id string) string {
return fmt.Sprintf("%sPartition", toSymbol(id))
}
func partitionVarName(id string) string {
return fmt.Sprintf("%sPartition", strings.ToLower(toSymbol(id)))
}
func listPartitionNames(ps partitions) string {
names := []string{}
switch len(ps) {
case 1:
return ps[0].Name
case 2:
return fmt.Sprintf("%s and %s", ps[0].Name, ps[1].Name)
default:
for i, p := range ps {
if i == len(ps)-1 {
names = append(names, "and "+p.Name)
} else {
names = append(names, p.Name)
}
}
return strings.Join(names, ", ")
}
}
func boxedBoolIfSet(msg string, v boxedBool) string {
switch v {
case boxedTrue:
return fmt.Sprintf(msg, "boxedTrue")
case boxedFalse:
return fmt.Sprintf(msg, "boxedFalse")
default:
return ""
}
}
func stringIfSet(msg, v string) string {
if len(v) == 0 {
return ""
}
return fmt.Sprintf(msg, v)
}
func stringSliceIfSet(msg string, vs []string) string {
if len(vs) == 0 {
return ""
}
names := []string{}
for _, v := range vs {
names = append(names, `"`+v+`"`)
}
return fmt.Sprintf(msg, strings.Join(names, ","))
}
func endpointIsSet(v endpoint) bool {
return !reflect.DeepEqual(v, endpoint{})
}
func serviceSet(ps partitions) map[string]struct{} {
set := map[string]struct{}{}
for _, p := range ps {
for id := range p.Services {
set[id] = struct{}{}
}
}
return set
}
var funcMap = template.FuncMap{
"ToSymbol": toSymbol,
"QuoteString": quoteString,
"RegionConst": regionConstName,
"PartitionGetter": partitionGetter,
"PartitionVarName": partitionVarName,
"ListPartitionNames": listPartitionNames,
"BoxedBoolIfSet": boxedBoolIfSet,
"StringIfSet": stringIfSet,
"StringSliceIfSet": stringSliceIfSet,
"EndpointIsSet": endpointIsSet,
"ServicesSet": serviceSet,
}
const v3Tmpl = `
{{ define "defaults" -}}
// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT.
package endpoints
import (
"regexp"
)
{{ template "partition consts" . }}
{{ range $_, $partition := . }}
{{ template "partition region consts" $partition }}
{{ end }}
{{ template "service consts" . }}
{{ template "endpoint resolvers" . }}
{{- end }}
{{ define "partition consts" }}
// Partition identifiers
const (
{{ range $_, $p := . -}}
{{ ToSymbol $p.ID }}PartitionID = {{ QuoteString $p.ID }} // {{ $p.Name }} partition.
{{ end -}}
)
{{- end }}
{{ define "partition region consts" }}
// {{ .Name }} partition's regions.
const (
{{ range $id, $region := .Regions -}}
{{ ToSymbol $id }}RegionID = {{ QuoteString $id }} // {{ $region.Description }}.
{{ end -}}
)
{{- end }}
{{ define "service consts" }}
// Service identifiers
const (
{{ $serviceSet := ServicesSet . -}}
{{ range $id, $_ := $serviceSet -}}
{{ ToSymbol $id }}ServiceID = {{ QuoteString $id }} // {{ ToSymbol $id }}.
{{ end -}}
)
{{- end }}
{{ define "endpoint resolvers" }}
// DefaultResolver returns an Endpoint resolver that will be able
// to resolve endpoints for: {{ ListPartitionNames . }}.
//
// Casting the return value of this func to a EnumPartitions will
// allow you to get a list of the partitions in the order the endpoints
// will be resolved in.
//
// resolver := endpoints.DefaultResolver()
// partitions := resolver.(endpoints.EnumPartitions).Partitions()
// for _, p := range partitions {
// // ... inspect partitions
// }
func DefaultResolver() Resolver {
return defaultPartitions
}
var defaultPartitions = partitions{
{{ range $_, $partition := . -}}
{{ PartitionVarName $partition.ID }},
{{ end }}
}
{{ range $_, $partition := . -}}
{{ $name := PartitionGetter $partition.ID -}}
// {{ $name }} returns the Resolver for {{ $partition.Name }}.
func {{ $name }}() Partition {
return {{ PartitionVarName $partition.ID }}.Partition()
}
var {{ PartitionVarName $partition.ID }} = {{ template "gocode Partition" $partition }}
{{ end }}
{{ end }}
{{ define "default partitions" }}
func DefaultPartitions() []Partition {
return []partition{
{{ range $_, $partition := . -}}
// {{ ToSymbol $partition.ID}}Partition(),
{{ end }}
}
}
{{ end }}
{{ define "gocode Partition" -}}
partition{
{{ StringIfSet "ID: %q,\n" .ID -}}
{{ StringIfSet "Name: %q,\n" .Name -}}
{{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}}
RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }},
{{ if EndpointIsSet .Defaults -}}
Defaults: {{ template "gocode Endpoint" .Defaults }},
{{- end }}
Regions: {{ template "gocode Regions" .Regions }},
Services: {{ template "gocode Services" .Services }},
}
{{- end }}
{{ define "gocode RegionRegex" -}}
regionRegex{
Regexp: func() *regexp.Regexp{
reg, _ := regexp.Compile({{ QuoteString .Regexp.String }})
return reg
}(),
}
{{- end }}
{{ define "gocode Regions" -}}
regions{
{{ range $id, $region := . -}}
"{{ $id }}": {{ template "gocode Region" $region }},
{{ end -}}
}
{{- end }}
{{ define "gocode Region" -}}
region{
{{ StringIfSet "Description: %q,\n" .Description -}}
}
{{- end }}
{{ define "gocode Services" -}}
services{
{{ range $id, $service := . -}}
"{{ $id }}": {{ template "gocode Service" $service }},
{{ end }}
}
{{- end }}
{{ define "gocode Service" -}}
service{
{{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}}
{{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}}
{{ if EndpointIsSet .Defaults -}}
Defaults: {{ template "gocode Endpoint" .Defaults -}},
{{- end }}
{{ if .Endpoints -}}
Endpoints: {{ template "gocode Endpoints" .Endpoints }},
{{- end }}
}
{{- end }}
{{ define "gocode Endpoints" -}}
endpoints{
{{ range $id, $endpoint := . -}}
"{{ $id }}": {{ template "gocode Endpoint" $endpoint }},
{{ end }}
}
{{- end }}
{{ define "gocode Endpoint" -}}
endpoint{
{{ StringIfSet "Hostname: %q,\n" .Hostname -}}
{{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}}
{{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}}
{{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}}
{{ if or .CredentialScope.Region .CredentialScope.Service -}}
CredentialScope: credentialScope{
{{ StringIfSet "Region: %q,\n" .CredentialScope.Region -}}
{{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}}
},
{{- end }}
{{ BoxedBoolIfSet "HasDualStack: %s,\n" .HasDualStack -}}
{{ StringIfSet "DualStackHostname: %q,\n" .DualStackHostname -}}
}
{{- end }}
`
| vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00023454091569874436,
0.00017364037921652198,
0.00016464636428281665,
0.00017166230827569962,
0.000011344418453518301
] |
{
"id": 1,
"code_window": [
"\n",
" it('should have no conditions in measurement query for query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 36
} | define([
'angular',
'jquery',
'../core_module',
'bootstrap-tagsinput',
],
function (angular, $, coreModule) {
'use strict';
function djb2(str) {
var hash = 5381;
for (var i = 0; i < str.length; i++) {
hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */
}
return hash;
}
function setColor(name, element) {
var hash = djb2(name.toLowerCase());
var colors = [
"#E24D42","#1F78C1","#BA43A9","#705DA0","#466803",
"#508642","#447EBC","#C15C17","#890F02","#757575",
"#0A437C","#6D1F62","#584477","#629E51","#2F4F4F",
"#BF1B00","#806EB7","#8a2eb8", "#699e00","#000000",
"#3F6833","#2F575E","#99440A","#E0752D","#0E4AB4",
"#58140C","#052B51","#511749","#3F2B5B",
];
var borderColors = [
"#FF7368","#459EE7","#E069CF","#9683C6","#6C8E29",
"#76AC68","#6AA4E2","#E7823D","#AF3528","#9B9B9B",
"#3069A2","#934588","#7E6A9D","#88C477","#557575",
"#E54126","#A694DD","#B054DE", "#8FC426","#262626",
"#658E59","#557D84","#BF6A30","#FF9B53","#3470DA",
"#7E3A32","#2B5177","#773D6F","#655181",
];
var color = colors[Math.abs(hash % colors.length)];
var borderColor = borderColors[Math.abs(hash % borderColors.length)];
element.css("background-color", color);
element.css("border-color", borderColor);
}
coreModule.default.directive('tagColorFromName', function() {
return {
scope: { tagColorFromName: "=" },
link: function (scope, element) {
setColor(scope.tagColorFromName, element);
}
};
});
coreModule.default.directive('bootstrapTagsinput', function() {
function getItemProperty(scope, property) {
if (!property) {
return undefined;
}
if (angular.isFunction(scope.$parent[property])) {
return scope.$parent[property];
}
return function(item) {
return item[property];
};
}
return {
restrict: 'EA',
scope: {
model: '=ngModel',
onTagsUpdated: "&",
},
template: '<select multiple></select>',
replace: false,
link: function(scope, element, attrs) {
if (!angular.isArray(scope.model)) {
scope.model = [];
}
var select = $('select', element);
if (attrs.placeholder) {
select.attr('placeholder', attrs.placeholder);
}
select.tagsinput({
typeahead: {
source: angular.isFunction(scope.$parent[attrs.typeaheadSource]) ? scope.$parent[attrs.typeaheadSource] : null
},
itemValue: getItemProperty(scope, attrs.itemvalue),
itemText : getItemProperty(scope, attrs.itemtext),
tagClass : angular.isFunction(scope.$parent[attrs.tagclass]) ?
scope.$parent[attrs.tagclass] : function() { return attrs.tagclass; }
});
select.on('itemAdded', function(event) {
if (scope.model.indexOf(event.item) === -1) {
scope.model.push(event.item);
if (scope.onTagsUpdated) {
scope.onTagsUpdated();
}
}
var tagElement = select.next().children("span").filter(function() { return $(this).text() === event.item; });
setColor(event.item, tagElement);
});
select.on('itemRemoved', function(event) {
var idx = scope.model.indexOf(event.item);
if (idx !== -1) {
scope.model.splice(idx, 1);
if (scope.onTagsUpdated) {
scope.onTagsUpdated();
}
}
});
scope.$watch("model", function() {
if (!angular.isArray(scope.model)) {
scope.model = [];
}
select.tagsinput('removeAll');
for (var i = 0; i < scope.model.length; i++) {
select.tagsinput('add', scope.model[i]);
}
}, true);
}
};
});
});
| public/app/core/directives/tags.js | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001981014502234757,
0.0001696122344583273,
0.00016398003208450973,
0.00016739917919039726,
0.000008170394721673802
] |
{
"id": 2,
"code_window": [
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import InfluxQueryBuilder from '../query_builder';
describe('InfluxQueryBuilder', function() {
describe('when building explore queries', function() {
it('should only have measurement condition in tag keys query given query with measurement', function() {
var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM "cpu"');
});
it('should handle regex measurement in tag keys query', function() {
var builder = new InfluxQueryBuilder({
measurement: '/.*/', tags: []
});
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM /.*/');
});
it('should have no conditions in tags keys query given query with no measurement or tag', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS');
});
it('should have where condition in tag keys query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'host', value: 'se1'}] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be("SHOW TAG KEYS WHERE \"host\" = 'se1'");
});
it('should have no conditions in measurement query for query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have no conditions in measurement query for query with no tags and empty query', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');
});
it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be("SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \"app\" = 'email'");
});
it('should have where condition in measurement query for query with tags', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be("SHOW MEASUREMENTS WHERE \"app\" = 'email'");
});
it('should have where tag name IN filter in tag values query for query with one tag', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'asdsadsad'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES WITH KEY = "app"');
});
it('should have measurement tag condition and tag name IN filter in tag values query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" = \'server1\'');
});
it('should switch to regex operator in tag condition', function() {
var builder = new InfluxQueryBuilder({
measurement: 'cpu',
tags: [{key: 'host', value: '/server.*/'}]
});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" =~ /server.*/');
});
it('should build show field query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM "cpu"');
});
it('should build show field query with regexp', function() {
var builder = new InfluxQueryBuilder({measurement: '/$var/', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM /$var/');
});
it('should build show retention policies query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: []}, 'site');
var query = builder.buildExploreQuery('RETENTION POLICIES');
expect(query).to.be('SHOW RETENTION POLICIES on "site"');
});
});
});
| public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts | 1 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.9981846213340759,
0.8745879530906677,
0.00021582179761026055,
0.9923200011253357,
0.2889934182167053
] |
{
"id": 2,
"code_window": [
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 42
} | ' [foo] ' | vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-416 | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00016806712665129453,
0.00016806712665129453,
0.00016806712665129453,
0.00016806712665129453,
0
] |
{
"id": 2,
"code_window": [
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 42
} | foo[?`{"a":2}` != key] | vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-75 | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001715622202027589,
0.0001715622202027589,
0.0001715622202027589,
0.0001715622202027589,
0
] |
{
"id": 2,
"code_window": [
" it('should have no conditions in measurement query for query with no tags and empty query', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');\n",
" expect(query).to.be('SHOW MEASUREMENTS');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 42
} | join('|', decimals[].to_string(@)) | vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-144 | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001742167805787176,
0.0001742167805787176,
0.0001742167805787176,
0.0001742167805787176,
0
] |
{
"id": 3,
"code_window": [
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 48
} | import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import InfluxQueryBuilder from '../query_builder';
describe('InfluxQueryBuilder', function() {
describe('when building explore queries', function() {
it('should only have measurement condition in tag keys query given query with measurement', function() {
var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM "cpu"');
});
it('should handle regex measurement in tag keys query', function() {
var builder = new InfluxQueryBuilder({
measurement: '/.*/', tags: []
});
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM /.*/');
});
it('should have no conditions in tags keys query given query with no measurement or tag', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS');
});
it('should have where condition in tag keys query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'host', value: 'se1'}] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be("SHOW TAG KEYS WHERE \"host\" = 'se1'");
});
it('should have no conditions in measurement query for query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have no conditions in measurement query for query with no tags and empty query', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');
});
it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be("SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \"app\" = 'email'");
});
it('should have where condition in measurement query for query with tags', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be("SHOW MEASUREMENTS WHERE \"app\" = 'email'");
});
it('should have where tag name IN filter in tag values query for query with one tag', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'asdsadsad'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES WITH KEY = "app"');
});
it('should have measurement tag condition and tag name IN filter in tag values query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" = \'server1\'');
});
it('should switch to regex operator in tag condition', function() {
var builder = new InfluxQueryBuilder({
measurement: 'cpu',
tags: [{key: 'host', value: '/server.*/'}]
});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" =~ /server.*/');
});
it('should build show field query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM "cpu"');
});
it('should build show field query with regexp', function() {
var builder = new InfluxQueryBuilder({measurement: '/$var/', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM /$var/');
});
it('should build show retention policies query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: []}, 'site');
var query = builder.buildExploreQuery('RETENTION POLICIES');
expect(query).to.be('SHOW RETENTION POLICIES on "site"');
});
});
});
| public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts | 1 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.998214840888977,
0.7943460941314697,
0.00016859214520081878,
0.9864501357078552,
0.36483269929885864
] |
{
"id": 3,
"code_window": [
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 48
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Grafana</title>
<link rel="stylesheet" href="[[.AppSubUrl]]/css/grafana.dark.min.css" title="Dark">
<link rel="icon" type="image/png" href="[[.AppSubUrl]]/img/fav32.png">
</head>
<body>
<div class="gf-box" style="margin: 200px auto 0 auto; width: 500px;">
<div class="gf-box-header">
<span class="gf-box-title">
Proxy authentication required
</span>
</div>
<div class="gf-box-body">
<h4>Proxy authenticaion required</h4>
</div>
</div>
</body>
</html>
| public/views/407.html | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00017085860599763691,
0.00017010292503982782,
0.00016892232815735042,
0.0001705278700683266,
8.456636351183988e-7
] |
{
"id": 3,
"code_window": [
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 48
} | // +build ppc64le,linux
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs types_linux.go
package unix
const (
sizeofPtr = 0x8
sizeofShort = 0x2
sizeofInt = 0x4
sizeofLong = 0x8
sizeofLongLong = 0x8
PathMax = 0x1000
)
type (
_C_short int16
_C_int int32
_C_long int64
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int64
}
type Timeval struct {
Sec int64
Usec int64
}
type Timex struct {
Modes uint32
Pad_cgo_0 [4]byte
Offset int64
Freq int64
Maxerror int64
Esterror int64
Status int32
Pad_cgo_1 [4]byte
Constant int64
Precision int64
Tolerance int64
Time Timeval
Tick int64
Ppsfreq int64
Jitter int64
Shift int32
Pad_cgo_2 [4]byte
Stabil int64
Jitcnt int64
Calcnt int64
Errcnt int64
Stbcnt int64
Tai int32
Pad_cgo_3 [44]byte
}
type Time_t int64
type Tms struct {
Utime int64
Stime int64
Cutime int64
Cstime int64
}
type Utimbuf struct {
Actime int64
Modtime int64
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int64
Ixrss int64
Idrss int64
Isrss int64
Minflt int64
Majflt int64
Nswap int64
Inblock int64
Oublock int64
Msgsnd int64
Msgrcv int64
Nsignals int64
Nvcsw int64
Nivcsw int64
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev uint64
Ino uint64
Nlink uint64
Mode uint32
Uid uint32
Gid uint32
X__pad2 int32
Rdev uint64
Size int64
Blksize int64
Blocks int64
Atim Timespec
Mtim Timespec
Ctim Timespec
X__glibc_reserved4 uint64
X__glibc_reserved5 uint64
X__glibc_reserved6 uint64
}
type Statfs_t struct {
Type int64
Bsize int64
Blocks uint64
Bfree uint64
Bavail uint64
Files uint64
Ffree uint64
Fsid Fsid
Namelen int64
Frsize int64
Flags int64
Spare [4]int64
}
type Dirent struct {
Ino uint64
Off int64
Reclen uint16
Type uint8
Name [256]uint8
Pad_cgo_0 [5]byte
}
type Fsid struct {
X__val [2]int32
}
type Flock_t struct {
Type int16
Whence int16
Pad_cgo_0 [4]byte
Start int64
Len int64
Pid int32
Pad_cgo_1 [4]byte
}
const (
FADV_NORMAL = 0x0
FADV_RANDOM = 0x1
FADV_SEQUENTIAL = 0x2
FADV_WILLNEED = 0x3
FADV_DONTNEED = 0x4
FADV_NOREUSE = 0x5
)
type RawSockaddrInet4 struct {
Family uint16
Port uint16
Addr [4]byte /* in_addr */
Zero [8]uint8
}
type RawSockaddrInet6 struct {
Family uint16
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Family uint16
Path [108]int8
}
type RawSockaddrLinklayer struct {
Family uint16
Protocol uint16
Ifindex int32
Hatype uint16
Pkttype uint8
Halen uint8
Addr [8]uint8
}
type RawSockaddrNetlink struct {
Family uint16
Pad uint16
Pid uint32
Groups uint32
}
type RawSockaddr struct {
Family uint16
Data [14]uint8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [96]uint8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint64
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPMreqn struct {
Multiaddr [4]byte /* in_addr */
Address [4]byte /* in_addr */
Ifindex int32
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
Pad_cgo_0 [4]byte
Iov *Iovec
Iovlen uint64
Control *byte
Controllen uint64
Flags int32
Pad_cgo_1 [4]byte
}
type Cmsghdr struct {
Len uint64
Level int32
Type int32
X__cmsg_data [0]uint8
}
type Inet4Pktinfo struct {
Ifindex int32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Data [8]uint32
}
type Ucred struct {
Pid int32
Uid uint32
Gid uint32
}
type TCPInfo struct {
State uint8
Ca_state uint8
Retransmits uint8
Probes uint8
Backoff uint8
Options uint8
Pad_cgo_0 [2]byte
Rto uint32
Ato uint32
Snd_mss uint32
Rcv_mss uint32
Unacked uint32
Sacked uint32
Lost uint32
Retrans uint32
Fackets uint32
Last_data_sent uint32
Last_ack_sent uint32
Last_data_recv uint32
Last_ack_recv uint32
Pmtu uint32
Rcv_ssthresh uint32
Rtt uint32
Rttvar uint32
Snd_ssthresh uint32
Snd_cwnd uint32
Advmss uint32
Reordering uint32
Rcv_rtt uint32
Rcv_space uint32
Total_retrans uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x70
SizeofSockaddrUnix = 0x6e
SizeofSockaddrLinklayer = 0x14
SizeofSockaddrNetlink = 0xc
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPMreqn = 0xc
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x38
SizeofCmsghdr = 0x10
SizeofInet4Pktinfo = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
SizeofUcred = 0xc
SizeofTCPInfo = 0x68
)
const (
IFA_UNSPEC = 0x0
IFA_ADDRESS = 0x1
IFA_LOCAL = 0x2
IFA_LABEL = 0x3
IFA_BROADCAST = 0x4
IFA_ANYCAST = 0x5
IFA_CACHEINFO = 0x6
IFA_MULTICAST = 0x7
IFLA_UNSPEC = 0x0
IFLA_ADDRESS = 0x1
IFLA_BROADCAST = 0x2
IFLA_IFNAME = 0x3
IFLA_MTU = 0x4
IFLA_LINK = 0x5
IFLA_QDISC = 0x6
IFLA_STATS = 0x7
IFLA_COST = 0x8
IFLA_PRIORITY = 0x9
IFLA_MASTER = 0xa
IFLA_WIRELESS = 0xb
IFLA_PROTINFO = 0xc
IFLA_TXQLEN = 0xd
IFLA_MAP = 0xe
IFLA_WEIGHT = 0xf
IFLA_OPERSTATE = 0x10
IFLA_LINKMODE = 0x11
IFLA_LINKINFO = 0x12
IFLA_NET_NS_PID = 0x13
IFLA_IFALIAS = 0x14
IFLA_MAX = 0x22
RT_SCOPE_UNIVERSE = 0x0
RT_SCOPE_SITE = 0xc8
RT_SCOPE_LINK = 0xfd
RT_SCOPE_HOST = 0xfe
RT_SCOPE_NOWHERE = 0xff
RT_TABLE_UNSPEC = 0x0
RT_TABLE_COMPAT = 0xfc
RT_TABLE_DEFAULT = 0xfd
RT_TABLE_MAIN = 0xfe
RT_TABLE_LOCAL = 0xff
RT_TABLE_MAX = 0xffffffff
RTA_UNSPEC = 0x0
RTA_DST = 0x1
RTA_SRC = 0x2
RTA_IIF = 0x3
RTA_OIF = 0x4
RTA_GATEWAY = 0x5
RTA_PRIORITY = 0x6
RTA_PREFSRC = 0x7
RTA_METRICS = 0x8
RTA_MULTIPATH = 0x9
RTA_FLOW = 0xb
RTA_CACHEINFO = 0xc
RTA_TABLE = 0xf
RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1
RTN_LOCAL = 0x2
RTN_BROADCAST = 0x3
RTN_ANYCAST = 0x4
RTN_MULTICAST = 0x5
RTN_BLACKHOLE = 0x6
RTN_UNREACHABLE = 0x7
RTN_PROHIBIT = 0x8
RTN_THROW = 0x9
RTN_NAT = 0xa
RTN_XRESOLVE = 0xb
RTNLGRP_NONE = 0x0
RTNLGRP_LINK = 0x1
RTNLGRP_NOTIFY = 0x2
RTNLGRP_NEIGH = 0x3
RTNLGRP_TC = 0x4
RTNLGRP_IPV4_IFADDR = 0x5
RTNLGRP_IPV4_MROUTE = 0x6
RTNLGRP_IPV4_ROUTE = 0x7
RTNLGRP_IPV4_RULE = 0x8
RTNLGRP_IPV6_IFADDR = 0x9
RTNLGRP_IPV6_MROUTE = 0xa
RTNLGRP_IPV6_ROUTE = 0xb
RTNLGRP_IPV6_IFINFO = 0xc
RTNLGRP_IPV6_PREFIX = 0x12
RTNLGRP_IPV6_RULE = 0x13
RTNLGRP_ND_USEROPT = 0x14
SizeofNlMsghdr = 0x10
SizeofNlMsgerr = 0x14
SizeofRtGenmsg = 0x1
SizeofNlAttr = 0x4
SizeofRtAttr = 0x4
SizeofIfInfomsg = 0x10
SizeofIfAddrmsg = 0x8
SizeofRtMsg = 0xc
SizeofRtNexthop = 0x8
)
type NlMsghdr struct {
Len uint32
Type uint16
Flags uint16
Seq uint32
Pid uint32
}
type NlMsgerr struct {
Error int32
Msg NlMsghdr
}
type RtGenmsg struct {
Family uint8
}
type NlAttr struct {
Len uint16
Type uint16
}
type RtAttr struct {
Len uint16
Type uint16
}
type IfInfomsg struct {
Family uint8
X__ifi_pad uint8
Type uint16
Index int32
Flags uint32
Change uint32
}
type IfAddrmsg struct {
Family uint8
Prefixlen uint8
Flags uint8
Scope uint8
Index uint32
}
type RtMsg struct {
Family uint8
Dst_len uint8
Src_len uint8
Tos uint8
Table uint8
Protocol uint8
Scope uint8
Type uint8
Flags uint32
}
type RtNexthop struct {
Len uint16
Flags uint8
Hops uint8
Ifindex int32
}
const (
SizeofSockFilter = 0x8
SizeofSockFprog = 0x10
)
type SockFilter struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type SockFprog struct {
Len uint16
Pad_cgo_0 [6]byte
Filter *SockFilter
}
type InotifyEvent struct {
Wd int32
Mask uint32
Cookie uint32
Len uint32
Name [0]uint8
}
const SizeofInotifyEvent = 0x10
type PtraceRegs struct {
Gpr [32]uint64
Nip uint64
Msr uint64
Orig_gpr3 uint64
Ctr uint64
Link uint64
Xer uint64
Ccr uint64
Softe uint64
Trap uint64
Dar uint64
Dsisr uint64
Result uint64
}
type FdSet struct {
Bits [16]int64
}
type Sysinfo_t struct {
Uptime int64
Loads [3]uint64
Totalram uint64
Freeram uint64
Sharedram uint64
Bufferram uint64
Totalswap uint64
Freeswap uint64
Procs uint16
Pad uint16
Pad_cgo_0 [4]byte
Totalhigh uint64
Freehigh uint64
Unit uint32
X_f [0]uint8
Pad_cgo_1 [4]byte
}
type Utsname struct {
Sysname [65]uint8
Nodename [65]uint8
Release [65]uint8
Version [65]uint8
Machine [65]uint8
Domainname [65]uint8
}
type Ustat_t struct {
Tfree int32
Pad_cgo_0 [4]byte
Tinode uint64
Fname [6]uint8
Fpack [6]uint8
Pad_cgo_1 [4]byte
}
type EpollEvent struct {
Events uint32
Fd int32
Pad int32
}
const (
AT_FDCWD = -0x64
AT_REMOVEDIR = 0x200
AT_SYMLINK_NOFOLLOW = 0x100
)
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [19]uint8
Line uint8
Ispeed uint32
Ospeed uint32
}
| vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00017415483307559043,
0.00016868617967702448,
0.0001626565062906593,
0.0001695634564384818,
0.0000031724732707516523
] |
{
"id": 3,
"code_window": [
"\n",
" it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');\n",
" });\n",
"\n",
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ LIMIT 100');\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 48
} | Copyright (c) 2010-2016 Jeremy Ashkenas, DocumentCloud
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
| public/vendor/lodash/vendor/backbone/LICENSE | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001766733475960791,
0.00017306744121015072,
0.00016730812785681337,
0.0001752208627294749,
0.000004115397132409271
] |
{
"id": 4,
"code_window": [
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 54
} | import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import InfluxQueryBuilder from '../query_builder';
describe('InfluxQueryBuilder', function() {
describe('when building explore queries', function() {
it('should only have measurement condition in tag keys query given query with measurement', function() {
var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM "cpu"');
});
it('should handle regex measurement in tag keys query', function() {
var builder = new InfluxQueryBuilder({
measurement: '/.*/', tags: []
});
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM /.*/');
});
it('should have no conditions in tags keys query given query with no measurement or tag', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS');
});
it('should have where condition in tag keys query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'host', value: 'se1'}] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be("SHOW TAG KEYS WHERE \"host\" = 'se1'");
});
it('should have no conditions in measurement query for query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have no conditions in measurement query for query with no tags and empty query', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');
});
it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be("SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \"app\" = 'email'");
});
it('should have where condition in measurement query for query with tags', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be("SHOW MEASUREMENTS WHERE \"app\" = 'email'");
});
it('should have where tag name IN filter in tag values query for query with one tag', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'asdsadsad'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES WITH KEY = "app"');
});
it('should have measurement tag condition and tag name IN filter in tag values query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" = \'server1\'');
});
it('should switch to regex operator in tag condition', function() {
var builder = new InfluxQueryBuilder({
measurement: 'cpu',
tags: [{key: 'host', value: '/server.*/'}]
});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" =~ /server.*/');
});
it('should build show field query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM "cpu"');
});
it('should build show field query with regexp', function() {
var builder = new InfluxQueryBuilder({measurement: '/$var/', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM /$var/');
});
it('should build show retention policies query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: []}, 'site');
var query = builder.buildExploreQuery('RETENTION POLICIES');
expect(query).to.be('SHOW RETENTION POLICIES on "site"');
});
});
});
| public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts | 1 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.9984356760978699,
0.49992844462394714,
0.0002258502645418048,
0.4062073826789856,
0.4217694401741028
] |
{
"id": 4,
"code_window": [
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 54
} | /**
* @license
* lodash lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE
*/
;(function(){function t(t,n){return t.set(n[0],n[1]),t}function n(t,n){return t.add(n),t}function r(t,n,r){switch(r.length){case 0:return t.call(n);case 1:return t.call(n,r[0]);case 2:return t.call(n,r[0],r[1]);case 3:return t.call(n,r[0],r[1],r[2])}return t.apply(n,r)}function e(t,n,r,e){for(var u=-1,o=t?t.length:0;++u<o;){var i=t[u];n(e,i,r(i),t)}return e}function u(t,n){for(var r=-1,e=t?t.length:0;++r<e&&false!==n(t[r],r,t););return t}function o(t,n){for(var r=t?t.length:0;r--&&false!==n(t[r],r,t););
return t}function i(t,n){for(var r=-1,e=t?t.length:0;++r<e;)if(!n(t[r],r,t))return false;return true}function f(t,n){for(var r=-1,e=t?t.length:0,u=0,o=[];++r<e;){var i=t[r];n(i,r,t)&&(o[u++]=i)}return o}function c(t,n){return!(!t||!t.length)&&-1<d(t,n,0)}function a(t,n,r){for(var e=-1,u=t?t.length:0;++e<u;)if(r(n,t[e]))return true;return false}function l(t,n){for(var r=-1,e=t?t.length:0,u=Array(e);++r<e;)u[r]=n(t[r],r,t);return u}function s(t,n){for(var r=-1,e=n.length,u=t.length;++r<e;)t[u+r]=n[r];return t}function h(t,n,r,e){
var u=-1,o=t?t.length:0;for(e&&o&&(r=t[++u]);++u<o;)r=n(r,t[u],u,t);return r}function p(t,n,r,e){var u=t?t.length:0;for(e&&u&&(r=t[--u]);u--;)r=n(r,t[u],u,t);return r}function _(t,n){for(var r=-1,e=t?t.length:0;++r<e;)if(n(t[r],r,t))return true;return false}function v(t,n,r){var e;return r(t,function(t,r,u){if(n(t,r,u))return e=r,false}),e}function g(t,n,r,e){var u=t.length;for(r+=e?1:-1;e?r--:++r<u;)if(n(t[r],r,t))return r;return-1}function d(t,n,r){if(n!==n)return g(t,b,r);--r;for(var e=t.length;++r<e;)if(t[r]===n)return r;
return-1}function y(t,n,r,e){--r;for(var u=t.length;++r<u;)if(e(t[r],n))return r;return-1}function b(t){return t!==t}function x(t,n){var r=t?t.length:0;return r?k(t,n)/r:q}function j(t){return function(n){return null==n?P:n[t]}}function w(t){return function(n){return null==t?P:t[n]}}function m(t,n,r,e,u){return u(t,function(t,u,o){r=e?(e=false,t):n(r,t,u,o)}),r}function A(t,n){var r=t.length;for(t.sort(n);r--;)t[r]=t[r].c;return t}function k(t,n){for(var r,e=-1,u=t.length;++e<u;){var o=n(t[e]);o!==P&&(r=r===P?o:r+o);
}return r}function E(t,n){for(var r=-1,e=Array(t);++r<t;)e[r]=n(r);return e}function O(t,n){return l(n,function(n){return[n,t[n]]})}function S(t){return function(n){return t(n)}}function I(t,n){return l(n,function(n){return t[n]})}function R(t,n){return t.has(n)}function W(t,n){for(var r=-1,e=t.length;++r<e&&-1<d(n,t[r],0););return r}function B(t,n){for(var r=t.length;r--&&-1<d(n,t[r],0););return r}function L(t){return"\\"+Ft[t]}function C(t){var n=false;if(null!=t&&typeof t.toString!="function")try{
n=!!(t+"")}catch(t){}return n}function U(t){var n=-1,r=Array(t.size);return t.forEach(function(t,e){r[++n]=[e,t]}),r}function M(t,n){return function(r){return t(n(r))}}function z(t,n){for(var r=-1,e=t.length,u=0,o=[];++r<e;){var i=t[r];i!==n&&"__lodash_placeholder__"!==i||(t[r]="__lodash_placeholder__",o[u++]=r)}return o}function D(t){var n=-1,r=Array(t.size);return t.forEach(function(t){r[++n]=t}),r}function T(t){var n=-1,r=Array(t.size);return t.forEach(function(t){r[++n]=[t,t]}),r}function $(t){
if(Ut.test(t)){for(var n=Lt.lastIndex=0;Lt.test(t);)n++;t=n}else t=en(t);return t}function F(t){return Ut.test(t)?t.match(Lt)||[]:t.split("")}function N(w){function St(t){return Hu.call(t)}function It(t){if(ou(t)&&!Fi(t)&&!(t instanceof $t)){if(t instanceof Lt)return t;if(Gu.call(t,"__wrapped__"))return Oe(t)}return new Lt(t)}function Rt(){}function Lt(t,n){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!n,this.__index__=0,this.__values__=P}function $t(t){this.__wrapped__=t,this.__actions__=[],
this.__dir__=1,this.__filtered__=false,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}function Ft(t){var n=-1,r=t?t.length:0;for(this.clear();++n<r;){var e=t[n];this.set(e[0],e[1])}}function Zt(t){var n=-1,r=t?t.length:0;for(this.clear();++n<r;){var e=t[n];this.set(e[0],e[1])}}function qt(t){var n=-1,r=t?t.length:0;for(this.clear();++n<r;){var e=t[n];this.set(e[0],e[1])}}function Kt(t){var n=-1,r=t?t.length:0;for(this.__data__=new qt;++n<r;)this.add(t[n])}function Gt(t){this.__data__=new Zt(t);
}function Yt(t,n){var r,e=Fi(t)||He(t)?E(t.length,Fu):[],u=e.length,o=!!u;for(r in t)!n&&!Gu.call(t,r)||o&&("length"==r||ge(r,u))||e.push(r);return e}function en(t,n,r,e){return t===P||Ye(t,Zu[r])&&!Gu.call(e,r)?n:t}function an(t,n,r){(r===P||Ye(t[n],r))&&(typeof n!="number"||r!==P||n in t)||(t[n]=r)}function ln(t,n,r){var e=t[n];Gu.call(t,n)&&Ye(e,r)&&(r!==P||n in t)||(t[n]=r)}function sn(t,n){for(var r=t.length;r--;)if(Ye(t[r][0],n))return r;return-1}function hn(t,n,r,e){return Po(t,function(t,u,o){
n(e,t,r(t),o)}),e}function pn(t,n){return t&&Br(n,bu(n),t)}function _n(t,n){for(var r=-1,e=null==t,u=n.length,o=Cu(u);++r<u;)o[r]=e?P:du(t,n[r]);return o}function vn(t,n,r){return t===t&&(r!==P&&(t=t<=r?t:r),n!==P&&(t=t>=n?t:n)),t}function gn(t,n,r,e,o,i,f){var c;if(e&&(c=i?e(t,o,i,f):e(t)),c!==P)return c;if(!uu(t))return t;if(o=Fi(t)){if(c=he(t),!n)return Wr(t,c)}else{var a=St(t),l="[object Function]"==a||"[object GeneratorFunction]"==a;if(Pi(t))return Er(t,n);if("[object Object]"==a||"[object Arguments]"==a||l&&!i){
if(C(t))return i?t:{};if(c=pe(l?{}:t),!n)return Lr(t,pn(c,t))}else{if(!Tt[a])return i?t:{};c=_e(t,a,gn,n)}}if(f||(f=new Gt),i=f.get(t))return i;if(f.set(t,c),!o)var s=r?Rn(t,bu,Ho):bu(t);return u(s||t,function(u,o){s&&(o=u,u=t[o]),ln(c,o,gn(u,n,r,e,o,t,f))}),c}function dn(t){var n=bu(t);return function(r){return yn(r,t,n)}}function yn(t,n,r){var e=r.length;if(null==t)return!e;for(t=Tu(t);e--;){var u=r[e],o=n[u],i=t[u];if(i===P&&!(u in t)||!o(i))return false}return true}function bn(t){return uu(t)?oo(t):{};
}function xn(t,n,r){if(typeof t!="function")throw new Nu("Expected a function");return ni(function(){t.apply(P,r)},n)}function jn(t,n,r,e){var u=-1,o=c,i=true,f=t.length,s=[],h=n.length;if(!f)return s;r&&(n=l(n,S(r))),e?(o=a,i=false):200<=n.length&&(o=R,i=false,n=new Kt(n));t:for(;++u<f;){var p=t[u],_=r?r(p):p,p=e||0!==p?p:0;if(i&&_===_){for(var v=h;v--;)if(n[v]===_)continue t;s.push(p)}else o(n,_,e)||s.push(p)}return s}function wn(t,n){var r=true;return Po(t,function(t,e,u){return r=!!n(t,e,u)}),r}function mn(t,n,r){
for(var e=-1,u=t.length;++e<u;){var o=t[e],i=n(o);if(null!=i&&(f===P?i===i&&!au(i):r(i,f)))var f=i,c=o}return c}function An(t,n){var r=[];return Po(t,function(t,e,u){n(t,e,u)&&r.push(t)}),r}function kn(t,n,r,e,u){var o=-1,i=t.length;for(r||(r=ve),u||(u=[]);++o<i;){var f=t[o];0<n&&r(f)?1<n?kn(f,n-1,r,e,u):s(u,f):e||(u[u.length]=f)}return u}function En(t,n){return t&&qo(t,n,bu)}function On(t,n){return t&&Vo(t,n,bu)}function Sn(t,n){return f(n,function(n){return nu(t[n])})}function In(t,n){n=ye(n,t)?[n]:Ar(n);
for(var r=0,e=n.length;null!=t&&r<e;)t=t[Ae(n[r++])];return r&&r==e?t:P}function Rn(t,n,r){return n=n(t),Fi(t)?n:s(n,r(t))}function Wn(t,n){return t>n}function Bn(t,n){return null!=t&&Gu.call(t,n)}function Ln(t,n){return null!=t&&n in Tu(t)}function Cn(t,n,r){for(var e=r?a:c,u=t[0].length,o=t.length,i=o,f=Cu(o),s=1/0,h=[];i--;){var p=t[i];i&&n&&(p=l(p,S(n))),s=jo(p.length,s),f[i]=!r&&(n||120<=u&&120<=p.length)?new Kt(i&&p):P}var p=t[0],_=-1,v=f[0];t:for(;++_<u&&h.length<s;){var g=p[_],d=n?n(g):g,g=r||0!==g?g:0;
if(v?!R(v,d):!e(h,d,r)){for(i=o;--i;){var y=f[i];if(y?!R(y,d):!e(t[i],d,r))continue t}v&&v.push(d),h.push(g)}}return h}function Un(t,n,r){var e={};return En(t,function(t,u,o){n(e,r(t),u,o)}),e}function Mn(t,n,e){return ye(n,t)||(n=Ar(n),t=me(t,n),n=We(n)),n=null==t?t:t[Ae(n)],null==n?P:r(n,t,e)}function zn(t){return ou(t)&&"[object ArrayBuffer]"==Hu.call(t)}function Dn(t){return ou(t)&&"[object Date]"==Hu.call(t)}function Tn(t,n,r,e,u){if(t===n)n=true;else if(null==t||null==n||!uu(t)&&!ou(n))n=t!==t&&n!==n;else t:{
var o=Fi(t),i=Fi(n),f="[object Array]",c="[object Array]";o||(f=St(t),f="[object Arguments]"==f?"[object Object]":f),i||(c=St(n),c="[object Arguments]"==c?"[object Object]":c);var a="[object Object]"==f&&!C(t),i="[object Object]"==c&&!C(n);if((c=f==c)&&!a)u||(u=new Gt),n=o||Gi(t)?ee(t,n,Tn,r,e,u):ue(t,n,f,Tn,r,e,u);else{if(!(2&e)&&(o=a&&Gu.call(t,"__wrapped__"),f=i&&Gu.call(n,"__wrapped__"),o||f)){t=o?t.value():t,n=f?n.value():n,u||(u=new Gt),n=Tn(t,n,r,e,u);break t}if(c)n:if(u||(u=new Gt),o=2&e,
f=bu(t),i=f.length,c=bu(n).length,i==c||o){for(a=i;a--;){var l=f[a];if(!(o?l in n:Gu.call(n,l))){n=false;break n}}if((c=u.get(t))&&u.get(n))n=c==n;else{c=true,u.set(t,n),u.set(n,t);for(var s=o;++a<i;){var l=f[a],h=t[l],p=n[l];if(r)var _=o?r(p,h,l,n,t,u):r(h,p,l,t,n,u);if(_===P?h!==p&&!Tn(h,p,r,e,u):!_){c=false;break}s||(s="constructor"==l)}c&&!s&&(r=t.constructor,e=n.constructor,r!=e&&"constructor"in t&&"constructor"in n&&!(typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)&&(c=false)),
u.delete(t),u.delete(n),n=c}}else n=false;else n=false}}return n}function $n(t){return ou(t)&&"[object Map]"==St(t)}function Fn(t,n,r,e){var u=r.length,o=u,i=!e;if(null==t)return!o;for(t=Tu(t);u--;){var f=r[u];if(i&&f[2]?f[1]!==t[f[0]]:!(f[0]in t))return false}for(;++u<o;){var f=r[u],c=f[0],a=t[c],l=f[1];if(i&&f[2]){if(a===P&&!(c in t))return false}else{if(f=new Gt,e)var s=e(a,l,c,t,n,f);if(s===P?!Tn(l,a,e,3,f):!s)return false}}return true}function Nn(t){return!(!uu(t)||Vu&&Vu in t)&&(nu(t)||C(t)?Xu:wt).test(ke(t))}function Pn(t){
return uu(t)&&"[object RegExp]"==Hu.call(t)}function Zn(t){return ou(t)&&"[object Set]"==St(t)}function qn(t){return ou(t)&&eu(t.length)&&!!Dt[Hu.call(t)]}function Vn(t){return typeof t=="function"?t:null==t?Ou:typeof t=="object"?Fi(t)?Qn(t[0],t[1]):Hn(t):Wu(t)}function Kn(t){if(!xe(t))return bo(t);var n,r=[];for(n in Tu(t))Gu.call(t,n)&&"constructor"!=n&&r.push(n);return r}function Gn(t){if(!uu(t)){var n=[];if(null!=t)for(var r in Tu(t))n.push(r);return n}r=xe(t);var e=[];for(n in t)("constructor"!=n||!r&&Gu.call(t,n))&&e.push(n);
return e}function Jn(t,n){return t<n}function Yn(t,n){var r=-1,e=Qe(t)?Cu(t.length):[];return Po(t,function(t,u,o){e[++r]=n(t,u,o)}),e}function Hn(t){var n=ae(t);return 1==n.length&&n[0][2]?je(n[0][0],n[0][1]):function(r){return r===t||Fn(r,t,n)}}function Qn(t,n){return ye(t)&&n===n&&!uu(n)?je(Ae(t),n):function(r){var e=du(r,t);return e===P&&e===n?yu(r,t):Tn(n,e,P,3)}}function Xn(t,n,r,e,o){if(t!==n){if(!Fi(n)&&!Gi(n))var i=Gn(n);u(i||n,function(u,f){if(i&&(f=u,u=n[f]),uu(u)){o||(o=new Gt);var c=f,a=o,l=t[c],s=n[c],h=a.get(s);
if(h)an(t,c,h);else{var h=e?e(l,s,c+"",t,n,a):P,p=h===P;p&&(h=s,Fi(s)||Gi(s)?Fi(l)?h=l:Xe(l)?h=Wr(l):(p=false,h=gn(s,true)):fu(s)||He(s)?He(l)?h=vu(l):!uu(l)||r&&nu(l)?(p=false,h=gn(s,true)):h=l:p=false),p&&(a.set(s,h),Xn(h,s,r,e,a),a.delete(s)),an(t,c,h)}}else c=e?e(t[f],u,f+"",t,n,o):P,c===P&&(c=u),an(t,f,c)})}}function tr(t,n){var r=t.length;if(r)return n+=0>n?r:0,ge(n,r)?t[n]:P}function nr(t,n,r){var e=-1;return n=l(n.length?n:[Ou],S(fe())),t=Yn(t,function(t){return{a:l(n,function(n){return n(t)}),b:++e,c:t
}}),A(t,function(t,n){var e;t:{e=-1;for(var u=t.a,o=n.a,i=u.length,f=r.length;++e<i;){var c=Sr(u[e],o[e]);if(c){e=e>=f?c:c*("desc"==r[e]?-1:1);break t}}e=t.b-n.b}return e})}function rr(t,n){return t=Tu(t),er(t,n,function(n,r){return r in t})}function er(t,n,r){for(var e=-1,u=n.length,o={};++e<u;){var i=n[e],f=t[i];r(f,i)&&(o[i]=f)}return o}function ur(t){return function(n){return In(n,t)}}function or(t,n,r,e){var u=e?y:d,o=-1,i=n.length,f=t;for(t===n&&(n=Wr(n)),r&&(f=l(t,S(r)));++o<i;)for(var c=0,a=n[o],a=r?r(a):a;-1<(c=u(f,a,c,e));)f!==t&&fo.call(f,c,1),
fo.call(t,c,1);return t}function ir(t,n){for(var r=t?n.length:0,e=r-1;r--;){var u=n[r];if(r==e||u!==o){var o=u;if(ge(u))fo.call(t,u,1);else if(ye(u,t))delete t[Ae(u)];else{var u=Ar(u),i=me(t,u);null!=i&&delete i[Ae(We(u))]}}}}function fr(t,n){return t+po(mo()*(n-t+1))}function cr(t,n){var r="";if(!t||1>n||9007199254740991<n)return r;do n%2&&(r+=t),(n=po(n/2))&&(t+=t);while(n);return r}function ar(t,n){return n=xo(n===P?t.length-1:n,0),function(){for(var e=arguments,u=-1,o=xo(e.length-n,0),i=Cu(o);++u<o;)i[u]=e[n+u];
for(u=-1,o=Cu(n+1);++u<n;)o[u]=e[u];return o[n]=i,r(t,this,o)}}function lr(t,n,r,e){if(!uu(t))return t;n=ye(n,t)?[n]:Ar(n);for(var u=-1,o=n.length,i=o-1,f=t;null!=f&&++u<o;){var c=Ae(n[u]),a=r;if(u!=i){var l=f[c],a=e?e(l,c,f):P;a===P&&(a=uu(l)?l:ge(n[u+1])?[]:{})}ln(f,c,a),f=f[c]}return t}function sr(t,n,r){var e=-1,u=t.length;for(0>n&&(n=-n>u?0:u+n),r=r>u?u:r,0>r&&(r+=u),u=n>r?0:r-n>>>0,n>>>=0,r=Cu(u);++e<u;)r[e]=t[e+n];return r}function hr(t,n){var r;return Po(t,function(t,e,u){return r=n(t,e,u),
!r}),!!r}function pr(t,n,r){var e=0,u=t?t.length:e;if(typeof n=="number"&&n===n&&2147483647>=u){for(;e<u;){var o=e+u>>>1,i=t[o];null!==i&&!au(i)&&(r?i<=n:i<n)?e=o+1:u=o}return u}return _r(t,n,Ou,r)}function _r(t,n,r,e){n=r(n);for(var u=0,o=t?t.length:0,i=n!==n,f=null===n,c=au(n),a=n===P;u<o;){var l=po((u+o)/2),s=r(t[l]),h=s!==P,p=null===s,_=s===s,v=au(s);(i?e||_:a?_&&(e||h):f?_&&h&&(e||!p):c?_&&h&&!p&&(e||!v):p||v?0:e?s<=n:s<n)?u=l+1:o=l}return jo(o,4294967294)}function vr(t,n){for(var r=-1,e=t.length,u=0,o=[];++r<e;){
var i=t[r],f=n?n(i):i;if(!r||!Ye(f,c)){var c=f;o[u++]=0===i?0:i}}return o}function gr(t){return typeof t=="number"?t:au(t)?q:+t}function dr(t){if(typeof t=="string")return t;if(au(t))return No?No.call(t):"";var n=t+"";return"0"==n&&1/t==-Z?"-0":n}function yr(t,n,r){var e=-1,u=c,o=t.length,i=true,f=[],l=f;if(r)i=false,u=a;else if(200<=o){if(u=n?null:Jo(t))return D(u);i=false,u=R,l=new Kt}else l=n?[]:f;t:for(;++e<o;){var s=t[e],h=n?n(s):s,s=r||0!==s?s:0;if(i&&h===h){for(var p=l.length;p--;)if(l[p]===h)continue t;
n&&l.push(h),f.push(s)}else u(l,h,r)||(l!==f&&l.push(h),f.push(s))}return f}function br(t,n,r,e){for(var u=t.length,o=e?u:-1;(e?o--:++o<u)&&n(t[o],o,t););return r?sr(t,e?0:o,e?o+1:u):sr(t,e?o+1:0,e?u:o)}function xr(t,n){var r=t;return r instanceof $t&&(r=r.value()),h(n,function(t,n){return n.func.apply(n.thisArg,s([t],n.args))},r)}function jr(t,n,r){for(var e=-1,u=t.length;++e<u;)var o=o?s(jn(o,t[e],n,r),jn(t[e],o,n,r)):t[e];return o&&o.length?yr(o,n,r):[]}function wr(t,n,r){for(var e=-1,u=t.length,o=n.length,i={};++e<u;)r(i,t[e],e<o?n[e]:P);
return i}function mr(t){return Xe(t)?t:[]}function Ar(t){return Fi(t)?t:ei(t)}function kr(t,n,r){var e=t.length;return r=r===P?e:r,!n&&r>=e?t:sr(t,n,r)}function Er(t,n){if(n)return t.slice();var r=new t.constructor(t.length);return t.copy(r),r}function Or(t){var n=new t.constructor(t.byteLength);return new ro(n).set(new ro(t)),n}function Sr(t,n){if(t!==n){var r=t!==P,e=null===t,u=t===t,o=au(t),i=n!==P,f=null===n,c=n===n,a=au(n);if(!f&&!a&&!o&&t>n||o&&i&&c&&!f&&!a||e&&i&&c||!r&&c||!u)return 1;if(!e&&!o&&!a&&t<n||a&&r&&u&&!e&&!o||f&&r&&u||!i&&u||!c)return-1;
}return 0}function Ir(t,n,r,e){var u=-1,o=t.length,i=r.length,f=-1,c=n.length,a=xo(o-i,0),l=Cu(c+a);for(e=!e;++f<c;)l[f]=n[f];for(;++u<i;)(e||u<o)&&(l[r[u]]=t[u]);for(;a--;)l[f++]=t[u++];return l}function Rr(t,n,r,e){var u=-1,o=t.length,i=-1,f=r.length,c=-1,a=n.length,l=xo(o-f,0),s=Cu(l+a);for(e=!e;++u<l;)s[u]=t[u];for(l=u;++c<a;)s[l+c]=n[c];for(;++i<f;)(e||u<o)&&(s[l+r[i]]=t[u++]);return s}function Wr(t,n){var r=-1,e=t.length;for(n||(n=Cu(e));++r<e;)n[r]=t[r];return n}function Br(t,n,r,e){r||(r={});
for(var u=-1,o=n.length;++u<o;){var i=n[u],f=e?e(r[i],t[i],i,r,t):P;ln(r,i,f===P?t[i]:f)}return r}function Lr(t,n){return Br(t,Ho(t),n)}function Cr(t,n){return function(r,u){var o=Fi(r)?e:hn,i=n?n():{};return o(r,t,fe(u,2),i)}}function Ur(t){return ar(function(n,r){var e=-1,u=r.length,o=1<u?r[u-1]:P,i=2<u?r[2]:P,o=3<t.length&&typeof o=="function"?(u--,o):P;for(i&&de(r[0],r[1],i)&&(o=3>u?P:o,u=1),n=Tu(n);++e<u;)(i=r[e])&&t(n,i,e,o);return n})}function Mr(t,n){return function(r,e){if(null==r)return r;
if(!Qe(r))return t(r,e);for(var u=r.length,o=n?u:-1,i=Tu(r);(n?o--:++o<u)&&false!==e(i[o],o,i););return r}}function zr(t){return function(n,r,e){var u=-1,o=Tu(n);e=e(n);for(var i=e.length;i--;){var f=e[t?i:++u];if(false===r(o[f],f,o))break}return n}}function Dr(t,n,r){function e(){return(this&&this!==Vt&&this instanceof e?o:t).apply(u?r:this,arguments)}var u=1&n,o=Fr(t);return e}function Tr(t){return function(n){n=gu(n);var r=Ut.test(n)?F(n):P,e=r?r[0]:n.charAt(0);return n=r?kr(r,1).join(""):n.slice(1),
e[t]()+n}}function $r(t){return function(n){return h(ku(Au(n).replace(Wt,"")),t,"")}}function Fr(t){return function(){var n=arguments;switch(n.length){case 0:return new t;case 1:return new t(n[0]);case 2:return new t(n[0],n[1]);case 3:return new t(n[0],n[1],n[2]);case 4:return new t(n[0],n[1],n[2],n[3]);case 5:return new t(n[0],n[1],n[2],n[3],n[4]);case 6:return new t(n[0],n[1],n[2],n[3],n[4],n[5]);case 7:return new t(n[0],n[1],n[2],n[3],n[4],n[5],n[6])}var r=bn(t.prototype),n=t.apply(r,n);return uu(n)?n:r;
}}function Nr(t,n,e){function u(){for(var i=arguments.length,f=Cu(i),c=i,a=ie(u);c--;)f[c]=arguments[c];return c=3>i&&f[0]!==a&&f[i-1]!==a?[]:z(f,a),i-=c.length,i<e?Xr(t,n,qr,u.placeholder,P,f,c,P,P,e-i):r(this&&this!==Vt&&this instanceof u?o:t,this,f)}var o=Fr(t);return u}function Pr(t){return function(n,r,e){var u=Tu(n);if(!Qe(n)){var o=fe(r,3);n=bu(n),r=function(t){return o(u[t],t,u)}}return r=t(n,r,e),-1<r?u[o?n[r]:r]:P}}function Zr(t){return ar(function(n){n=kn(n,1);var r=n.length,e=r,u=Lt.prototype.thru;
for(t&&n.reverse();e--;){var o=n[e];if(typeof o!="function")throw new Nu("Expected a function");if(u&&!i&&"wrapper"==oe(o))var i=new Lt([],(true))}for(e=i?e:r;++e<r;)var o=n[e],u=oe(o),f="wrapper"==u?Yo(o):P,i=f&&be(f[0])&&424==f[1]&&!f[4].length&&1==f[9]?i[oe(f[0])].apply(i,f[3]):1==o.length&&be(o)?i[u]():i.thru(o);return function(){var t=arguments,e=t[0];if(i&&1==t.length&&Fi(e)&&200<=e.length)return i.plant(e).value();for(var u=0,t=r?n[u].apply(this,t):e;++u<r;)t=n[u].call(this,t);return t}})}function qr(t,n,r,e,u,o,i,f,c,a){
function l(){for(var d=arguments.length,y=Cu(d),b=d;b--;)y[b]=arguments[b];if(_){var x,j=ie(l),b=y.length;for(x=0;b--;)y[b]===j&&x++}if(e&&(y=Ir(y,e,u,_)),o&&(y=Rr(y,o,i,_)),d-=x,_&&d<a)return j=z(y,j),Xr(t,n,qr,l.placeholder,r,y,j,f,c,a-d);if(j=h?r:this,b=p?j[t]:t,d=y.length,f){x=y.length;for(var w=jo(f.length,x),m=Wr(y);w--;){var A=f[w];y[w]=ge(A,x)?m[A]:P}}else v&&1<d&&y.reverse();return s&&c<d&&(y.length=c),this&&this!==Vt&&this instanceof l&&(b=g||Fr(b)),b.apply(j,y)}var s=128&n,h=1&n,p=2&n,_=24&n,v=512&n,g=p?P:Fr(t);
return l}function Vr(t,n){return function(r,e){return Un(r,t,n(e))}}function Kr(t,n){return function(r,e){var u;if(r===P&&e===P)return n;if(r!==P&&(u=r),e!==P){if(u===P)return e;typeof r=="string"||typeof e=="string"?(r=dr(r),e=dr(e)):(r=gr(r),e=gr(e)),u=t(r,e)}return u}}function Gr(t){return ar(function(n){return n=1==n.length&&Fi(n[0])?l(n[0],S(fe())):l(kn(n,1),S(fe())),ar(function(e){var u=this;return t(n,function(t){return r(t,u,e)})})})}function Jr(t,n){n=n===P?" ":dr(n);var r=n.length;return 2>r?r?cr(n,t):n:(r=cr(n,ho(t/$(n))),
Ut.test(n)?kr(F(r),0,t).join(""):r.slice(0,t))}function Yr(t,n,e,u){function o(){for(var n=-1,c=arguments.length,a=-1,l=u.length,s=Cu(l+c),h=this&&this!==Vt&&this instanceof o?f:t;++a<l;)s[a]=u[a];for(;c--;)s[a++]=arguments[++n];return r(h,i?e:this,s)}var i=1&n,f=Fr(t);return o}function Hr(t){return function(n,r,e){e&&typeof e!="number"&&de(n,r,e)&&(r=e=P),n=su(n),r===P?(r=n,n=0):r=su(r),e=e===P?n<r?1:-1:su(e);var u=-1;r=xo(ho((r-n)/(e||1)),0);for(var o=Cu(r);r--;)o[t?r:++u]=n,n+=e;return o}}function Qr(t){
return function(n,r){return typeof n=="string"&&typeof r=="string"||(n=_u(n),r=_u(r)),t(n,r)}}function Xr(t,n,r,e,u,o,i,f,c,a){var l=8&n,s=l?i:P;i=l?P:i;var h=l?o:P;return o=l?P:o,n=(n|(l?32:64))&~(l?64:32),4&n||(n&=-4),u=[t,n,u,h,s,o,i,f,c,a],r=r.apply(P,u),be(t)&&ti(r,u),r.placeholder=e,ri(r,t,n)}function te(t){var n=Du[t];return function(t,r){if(t=_u(t),r=jo(hu(r),292)){var e=(gu(t)+"e").split("e"),e=n(e[0]+"e"+(+e[1]+r)),e=(gu(e)+"e").split("e");return+(e[0]+"e"+(+e[1]-r))}return n(t)}}function ne(t){
return function(n){var r=St(n);return"[object Map]"==r?U(n):"[object Set]"==r?T(n):O(n,t(n))}}function re(t,n,r,e,u,o,i,f){var c=2&n;if(!c&&typeof t!="function")throw new Nu("Expected a function");var a=e?e.length:0;if(a||(n&=-97,e=u=P),i=i===P?i:xo(hu(i),0),f=f===P?f:hu(f),a-=u?u.length:0,64&n){var l=e,s=u;e=u=P}var h=c?P:Yo(t);return o=[t,n,r,e,u,l,s,o,i,f],h&&(r=o[1],t=h[1],n=r|t,e=128==t&&8==r||128==t&&256==r&&o[7].length<=h[8]||384==t&&h[7].length<=h[8]&&8==r,131>n||e)&&(1&t&&(o[2]=h[2],n|=1&r?0:4),
(r=h[3])&&(e=o[3],o[3]=e?Ir(e,r,h[4]):r,o[4]=e?z(o[3],"__lodash_placeholder__"):h[4]),(r=h[5])&&(e=o[5],o[5]=e?Rr(e,r,h[6]):r,o[6]=e?z(o[5],"__lodash_placeholder__"):h[6]),(r=h[7])&&(o[7]=r),128&t&&(o[8]=null==o[8]?h[8]:jo(o[8],h[8])),null==o[9]&&(o[9]=h[9]),o[0]=h[0],o[1]=n),t=o[0],n=o[1],r=o[2],e=o[3],u=o[4],f=o[9]=null==o[9]?c?0:t.length:xo(o[9]-a,0),!f&&24&n&&(n&=-25),ri((h?Ko:ti)(n&&1!=n?8==n||16==n?Nr(t,n,f):32!=n&&33!=n||u.length?qr.apply(P,o):Yr(t,n,r,e):Dr(t,n,r),o),t,n)}function ee(t,n,r,e,u,o){
var i=2&u,f=t.length,c=n.length;if(f!=c&&!(i&&c>f))return false;if((c=o.get(t))&&o.get(n))return c==n;var c=-1,a=true,l=1&u?new Kt:P;for(o.set(t,n),o.set(n,t);++c<f;){var s=t[c],h=n[c];if(e)var p=i?e(h,s,c,n,t,o):e(s,h,c,t,n,o);if(p!==P){if(p)continue;a=false;break}if(l){if(!_(n,function(t,n){if(!l.has(n)&&(s===t||r(s,t,e,u,o)))return l.add(n)})){a=false;break}}else if(s!==h&&!r(s,h,e,u,o)){a=false;break}}return o.delete(t),o.delete(n),a}function ue(t,n,r,e,u,o,i){switch(r){case"[object DataView]":if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)break;
t=t.buffer,n=n.buffer;case"[object ArrayBuffer]":if(t.byteLength!=n.byteLength||!e(new ro(t),new ro(n)))break;return true;case"[object Boolean]":case"[object Date]":case"[object Number]":return Ye(+t,+n);case"[object Error]":return t.name==n.name&&t.message==n.message;case"[object RegExp]":case"[object String]":return t==n+"";case"[object Map]":var f=U;case"[object Set]":if(f||(f=D),t.size!=n.size&&!(2&o))break;return(r=i.get(t))?r==n:(o|=1,i.set(t,n),n=ee(f(t),f(n),e,u,o,i),i.delete(t),n);case"[object Symbol]":
if(Fo)return Fo.call(t)==Fo.call(n)}return false}function oe(t){for(var n=t.name+"",r=Co[n],e=Gu.call(Co,n)?r.length:0;e--;){var u=r[e],o=u.func;if(null==o||o==t)return u.name}return n}function ie(t){return(Gu.call(It,"placeholder")?It:t).placeholder}function fe(){var t=It.iteratee||Su,t=t===Su?Vn:t;return arguments.length?t(arguments[0],arguments[1]):t}function ce(t,n){var r=t.__data__,e=typeof n;return("string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==n:null===n)?r[typeof n=="string"?"string":"hash"]:r.map;
}function ae(t){for(var n=bu(t),r=n.length;r--;){var e=n[r],u=t[e];n[r]=[e,u,u===u&&!uu(u)]}return n}function le(t,n){var r=null==t?P:t[n];return Nn(r)?r:P}function se(t,n,r){n=ye(n,t)?[n]:Ar(n);for(var e,u=-1,o=n.length;++u<o;){var i=Ae(n[u]);if(!(e=null!=t&&r(t,i)))break;t=t[i]}return e?e:(o=t?t.length:0,!!o&&eu(o)&&ge(i,o)&&(Fi(t)||He(t)))}function he(t){var n=t.length,r=t.constructor(n);return n&&"string"==typeof t[0]&&Gu.call(t,"index")&&(r.index=t.index,r.input=t.input),r}function pe(t){return typeof t.constructor!="function"||xe(t)?{}:bn(eo(t));
}function _e(r,e,u,o){var i=r.constructor;switch(e){case"[object ArrayBuffer]":return Or(r);case"[object Boolean]":case"[object Date]":return new i((+r));case"[object DataView]":return e=o?Or(r.buffer):r.buffer,new r.constructor(e,r.byteOffset,r.byteLength);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":
return e=o?Or(r.buffer):r.buffer,new r.constructor(e,r.byteOffset,r.length);case"[object Map]":return e=o?u(U(r),true):U(r),h(e,t,new r.constructor);case"[object Number]":case"[object String]":return new i(r);case"[object RegExp]":return e=new r.constructor(r.source,yt.exec(r)),e.lastIndex=r.lastIndex,e;case"[object Set]":return e=o?u(D(r),true):D(r),h(e,n,new r.constructor);case"[object Symbol]":return Fo?Tu(Fo.call(r)):{}}}function ve(t){return Fi(t)||He(t)||!!(co&&t&&t[co])}function ge(t,n){return n=null==n?9007199254740991:n,
!!n&&(typeof t=="number"||At.test(t))&&-1<t&&0==t%1&&t<n}function de(t,n,r){if(!uu(r))return false;var e=typeof n;return!!("number"==e?Qe(r)&&ge(n,r.length):"string"==e&&n in r)&&Ye(r[n],t)}function ye(t,n){if(Fi(t))return false;var r=typeof t;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=t&&!au(t))||(ut.test(t)||!et.test(t)||null!=n&&t in Tu(n))}function be(t){var n=oe(t),r=It[n];return typeof r=="function"&&n in $t.prototype&&(t===r||(n=Yo(r),!!n&&t===n[0]))}function xe(t){var n=t&&t.constructor;
return t===(typeof n=="function"&&n.prototype||Zu)}function je(t,n){return function(r){return null!=r&&(r[t]===n&&(n!==P||t in Tu(r)))}}function we(t,n,r,e,u,o){return uu(t)&&uu(n)&&(o.set(n,t),Xn(t,n,P,we,o),o.delete(n)),t}function me(t,n){return 1==n.length?t:In(t,sr(n,0,-1))}function Ae(t){if(typeof t=="string"||au(t))return t;var n=t+"";return"0"==n&&1/t==-Z?"-0":n}function ke(t){if(null!=t){try{return Ku.call(t)}catch(t){}return t+""}return""}function Ee(t,n){return u(V,function(r){var e="_."+r[0];
n&r[1]&&!c(t,e)&&t.push(e)}),t.sort()}function Oe(t){if(t instanceof $t)return t.clone();var n=new Lt(t.__wrapped__,t.__chain__);return n.__actions__=Wr(t.__actions__),n.__index__=t.__index__,n.__values__=t.__values__,n}function Se(t,n,r){var e=t?t.length:0;return e?(r=null==r?0:hu(r),0>r&&(r=xo(e+r,0)),g(t,fe(n,3),r)):-1}function Ie(t,n,r){var e=t?t.length:0;if(!e)return-1;var u=e-1;return r!==P&&(u=hu(r),u=0>r?xo(e+u,0):jo(u,e-1)),g(t,fe(n,3),u,true)}function Re(t){return t&&t.length?t[0]:P}function We(t){
var n=t?t.length:0;return n?t[n-1]:P}function Be(t,n){return t&&t.length&&n&&n.length?or(t,n):t}function Le(t){return t?Ao.call(t):t}function Ce(t){if(!t||!t.length)return[];var n=0;return t=f(t,function(t){if(Xe(t))return n=xo(t.length,n),true}),E(n,function(n){return l(t,j(n))})}function Ue(t,n){if(!t||!t.length)return[];var e=Ce(t);return null==n?e:l(e,function(t){return r(n,P,t)})}function Me(t){return t=It(t),t.__chain__=true,t}function ze(t,n){return n(t)}function De(){return this}function Te(t,n){
return(Fi(t)?u:Po)(t,fe(n,3))}function $e(t,n){return(Fi(t)?o:Zo)(t,fe(n,3))}function Fe(t,n){return(Fi(t)?l:Yn)(t,fe(n,3))}function Ne(t,n,r){var e=-1,u=lu(t),o=u.length,i=o-1;for(n=(r?de(t,n,r):n===P)?1:vn(hu(n),0,o);++e<n;)t=fr(e,i),r=u[t],u[t]=u[e],u[e]=r;return u.length=n,u}function Pe(t,n,r){return n=r?P:n,n=t&&null==n?t.length:n,re(t,128,P,P,P,P,n)}function Ze(t,n){var r;if(typeof n!="function")throw new Nu("Expected a function");return t=hu(t),function(){return 0<--t&&(r=n.apply(this,arguments)),
1>=t&&(n=P),r}}function qe(t,n,r){return n=r?P:n,t=re(t,8,P,P,P,P,P,n),t.placeholder=qe.placeholder,t}function Ve(t,n,r){return n=r?P:n,t=re(t,16,P,P,P,P,P,n),t.placeholder=Ve.placeholder,t}function Ke(t,n,r){function e(n){var r=c,e=a;return c=a=P,_=n,s=t.apply(e,r)}function u(t){var r=t-p;return t-=_,p===P||r>=n||0>r||g&&t>=l}function o(){var t=Ri();if(u(t))return i(t);var r,e=ni;r=t-_,t=n-(t-p),r=g?jo(t,l-r):t,h=e(o,r)}function i(t){return h=P,d&&c?e(t):(c=a=P,s)}function f(){var t=Ri(),r=u(t);if(c=arguments,
a=this,p=t,r){if(h===P)return _=t=p,h=ni(o,n),v?e(t):s;if(g)return h=ni(o,n),e(p)}return h===P&&(h=ni(o,n)),s}var c,a,l,s,h,p,_=0,v=false,g=false,d=true;if(typeof t!="function")throw new Nu("Expected a function");return n=_u(n)||0,uu(r)&&(v=!!r.leading,l=(g="maxWait"in r)?xo(_u(r.maxWait)||0,n):l,d="trailing"in r?!!r.trailing:d),f.cancel=function(){h!==P&&Go(h),_=0,c=p=a=h=P},f.flush=function(){return h===P?s:i(Ri())},f}function Ge(t,n){function r(){var e=arguments,u=n?n.apply(this,e):e[0],o=r.cache;return o.has(u)?o.get(u):(e=t.apply(this,e),
r.cache=o.set(u,e),e)}if(typeof t!="function"||n&&typeof n!="function")throw new Nu("Expected a function");return r.cache=new(Ge.Cache||qt),r}function Je(t){if(typeof t!="function")throw new Nu("Expected a function");return function(){var n=arguments;switch(n.length){case 0:return!t.call(this);case 1:return!t.call(this,n[0]);case 2:return!t.call(this,n[0],n[1]);case 3:return!t.call(this,n[0],n[1],n[2])}return!t.apply(this,n)}}function Ye(t,n){return t===n||t!==t&&n!==n}function He(t){return Xe(t)&&Gu.call(t,"callee")&&(!io.call(t,"callee")||"[object Arguments]"==Hu.call(t));
}function Qe(t){return null!=t&&eu(t.length)&&!nu(t)}function Xe(t){return ou(t)&&Qe(t)}function tu(t){return!!ou(t)&&("[object Error]"==Hu.call(t)||typeof t.message=="string"&&typeof t.name=="string")}function nu(t){return t=uu(t)?Hu.call(t):"","[object Function]"==t||"[object GeneratorFunction]"==t}function ru(t){return typeof t=="number"&&t==hu(t)}function eu(t){return typeof t=="number"&&-1<t&&0==t%1&&9007199254740991>=t}function uu(t){var n=typeof t;return!!t&&("object"==n||"function"==n)}function ou(t){
return!!t&&typeof t=="object"}function iu(t){return typeof t=="number"||ou(t)&&"[object Number]"==Hu.call(t)}function fu(t){return!(!ou(t)||"[object Object]"!=Hu.call(t)||C(t))&&(t=eo(t),null===t||(t=Gu.call(t,"constructor")&&t.constructor,typeof t=="function"&&t instanceof t&&Ku.call(t)==Yu))}function cu(t){return typeof t=="string"||!Fi(t)&&ou(t)&&"[object String]"==Hu.call(t)}function au(t){return typeof t=="symbol"||ou(t)&&"[object Symbol]"==Hu.call(t)}function lu(t){if(!t)return[];if(Qe(t))return cu(t)?F(t):Wr(t);
if(uo&&t[uo]){t=t[uo]();for(var n,r=[];!(n=t.next()).done;)r.push(n.value);return r}return n=St(t),("[object Map]"==n?U:"[object Set]"==n?D:wu)(t)}function su(t){return t?(t=_u(t),t===Z||t===-Z?1.7976931348623157e308*(0>t?-1:1):t===t?t:0):0===t?t:0}function hu(t){t=su(t);var n=t%1;return t===t?n?t-n:t:0}function pu(t){return t?vn(hu(t),0,4294967295):0}function _u(t){if(typeof t=="number")return t;if(au(t))return q;if(uu(t)&&(t=typeof t.valueOf=="function"?t.valueOf():t,t=uu(t)?t+"":t),typeof t!="string")return 0===t?t:+t;
t=t.replace(at,"");var n=jt.test(t);return n||mt.test(t)?Pt(t.slice(2),n?2:8):xt.test(t)?q:+t}function vu(t){return Br(t,xu(t))}function gu(t){return null==t?"":dr(t)}function du(t,n,r){return t=null==t?P:In(t,n),t===P?r:t}function yu(t,n){return null!=t&&se(t,n,Ln)}function bu(t){return Qe(t)?Yt(t):Kn(t)}function xu(t){return Qe(t)?Yt(t,true):Gn(t)}function ju(t,n){return null==t?{}:er(t,Rn(t,xu,Qo),fe(n))}function wu(t){return t?I(t,bu(t)):[]}function mu(t){return jf(gu(t).toLowerCase())}function Au(t){
return(t=gu(t))&&t.replace(kt,un).replace(Bt,"")}function ku(t,n,r){return t=gu(t),n=r?P:n,n===P?Mt.test(t)?t.match(Ct)||[]:t.match(vt)||[]:t.match(n)||[]}function Eu(t){return function(){return t}}function Ou(t){return t}function Su(t){return Vn(typeof t=="function"?t:gn(t,true))}function Iu(t,n,r){var e=bu(n),o=Sn(n,e);null!=r||uu(n)&&(o.length||!e.length)||(r=n,n=t,t=this,o=Sn(n,bu(n)));var i=!(uu(r)&&"chain"in r&&!r.chain),f=nu(t);return u(o,function(r){var e=n[r];t[r]=e,f&&(t.prototype[r]=function(){
var n=this.__chain__;if(i||n){var r=t(this.__wrapped__);return(r.__actions__=Wr(this.__actions__)).push({func:e,args:arguments,thisArg:t}),r.__chain__=n,r}return e.apply(t,s([this.value()],arguments))})}),t}function Ru(){}function Wu(t){return ye(t)?j(Ae(t)):ur(t)}function Bu(){return[]}function Lu(){return false}w=w?cn.defaults(Vt.Object(),w,cn.pick(Vt,zt)):Vt;var Cu=w.Array,Uu=w.Date,Mu=w.Error,zu=w.Function,Du=w.Math,Tu=w.Object,$u=w.RegExp,Fu=w.String,Nu=w.TypeError,Pu=Cu.prototype,Zu=Tu.prototype,qu=w["__core-js_shared__"],Vu=function(){
var t=/[^.]+$/.exec(qu&&qu.keys&&qu.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Ku=zu.prototype.toString,Gu=Zu.hasOwnProperty,Ju=0,Yu=Ku.call(Tu),Hu=Zu.toString,Qu=Vt._,Xu=$u("^"+Ku.call(Gu).replace(ft,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),to=Jt?w.Buffer:P,no=w.Symbol,ro=w.Uint8Array,eo=M(Tu.getPrototypeOf,Tu),uo=no?no.iterator:P,oo=Tu.create,io=Zu.propertyIsEnumerable,fo=Pu.splice,co=no?no.isConcatSpreadable:P,ao=w.clearTimeout!==Vt.clearTimeout&&w.clearTimeout,lo=Uu&&Uu.now!==Vt.Date.now&&Uu.now,so=w.setTimeout!==Vt.setTimeout&&w.setTimeout,ho=Du.ceil,po=Du.floor,_o=Tu.getOwnPropertySymbols,vo=to?to.isBuffer:P,go=w.isFinite,yo=Pu.join,bo=M(Tu.keys,Tu),xo=Du.max,jo=Du.min,wo=w.parseInt,mo=Du.random,Ao=Pu.reverse,ko=le(w,"DataView"),Eo=le(w,"Map"),Oo=le(w,"Promise"),So=le(w,"Set"),Io=le(w,"WeakMap"),Ro=le(Tu,"create"),Wo=function(){
var t=le(Tu,"defineProperty"),n=le.name;return n&&2<n.length?t:P}(),Bo=Io&&new Io,Lo=!io.call({valueOf:1},"valueOf"),Co={},Uo=ke(ko),Mo=ke(Eo),zo=ke(Oo),Do=ke(So),To=ke(Io),$o=no?no.prototype:P,Fo=$o?$o.valueOf:P,No=$o?$o.toString:P;It.templateSettings={escape:tt,evaluate:nt,interpolate:rt,variable:"",imports:{_:It}},It.prototype=Rt.prototype,It.prototype.constructor=It,Lt.prototype=bn(Rt.prototype),Lt.prototype.constructor=Lt,$t.prototype=bn(Rt.prototype),$t.prototype.constructor=$t,Ft.prototype.clear=function(){
this.__data__=Ro?Ro(null):{}},Ft.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},Ft.prototype.get=function(t){var n=this.__data__;return Ro?(t=n[t],"__lodash_hash_undefined__"===t?P:t):Gu.call(n,t)?n[t]:P},Ft.prototype.has=function(t){var n=this.__data__;return Ro?n[t]!==P:Gu.call(n,t)},Ft.prototype.set=function(t,n){return this.__data__[t]=Ro&&n===P?"__lodash_hash_undefined__":n,this},Zt.prototype.clear=function(){this.__data__=[]},Zt.prototype.delete=function(t){var n=this.__data__;
return t=sn(n,t),!(0>t)&&(t==n.length-1?n.pop():fo.call(n,t,1),true)},Zt.prototype.get=function(t){var n=this.__data__;return t=sn(n,t),0>t?P:n[t][1]},Zt.prototype.has=function(t){return-1<sn(this.__data__,t)},Zt.prototype.set=function(t,n){var r=this.__data__,e=sn(r,t);return 0>e?r.push([t,n]):r[e][1]=n,this},qt.prototype.clear=function(){this.__data__={hash:new Ft,map:new(Eo||Zt),string:new Ft}},qt.prototype.delete=function(t){return ce(this,t).delete(t)},qt.prototype.get=function(t){return ce(this,t).get(t);
},qt.prototype.has=function(t){return ce(this,t).has(t)},qt.prototype.set=function(t,n){return ce(this,t).set(t,n),this},Kt.prototype.add=Kt.prototype.push=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this},Kt.prototype.has=function(t){return this.__data__.has(t)},Gt.prototype.clear=function(){this.__data__=new Zt},Gt.prototype.delete=function(t){return this.__data__.delete(t)},Gt.prototype.get=function(t){return this.__data__.get(t)},Gt.prototype.has=function(t){return this.__data__.has(t);
},Gt.prototype.set=function(t,n){var r=this.__data__;if(r instanceof Zt){if(r=r.__data__,!Eo||199>r.length)return r.push([t,n]),this;r=this.__data__=new qt(r)}return r.set(t,n),this};var Po=Mr(En),Zo=Mr(On,true),qo=zr(),Vo=zr(true),Ko=Bo?function(t,n){return Bo.set(t,n),t}:Ou,Go=ao||function(t){return Vt.clearTimeout(t)},Jo=So&&1/D(new So([,-0]))[1]==Z?function(t){return new So(t)}:Ru,Yo=Bo?function(t){return Bo.get(t)}:Ru,Ho=_o?M(_o,Tu):Bu,Qo=_o?function(t){for(var n=[];t;)s(n,Ho(t)),t=eo(t);return n;
}:Bu;(ko&&"[object DataView]"!=St(new ko(new ArrayBuffer(1)))||Eo&&"[object Map]"!=St(new Eo)||Oo&&"[object Promise]"!=St(Oo.resolve())||So&&"[object Set]"!=St(new So)||Io&&"[object WeakMap]"!=St(new Io))&&(St=function(t){var n=Hu.call(t);if(t=(t="[object Object]"==n?t.constructor:P)?ke(t):P)switch(t){case Uo:return"[object DataView]";case Mo:return"[object Map]";case zo:return"[object Promise]";case Do:return"[object Set]";case To:return"[object WeakMap]"}return n});var Xo=qu?nu:Lu,ti=function(){
var t=0,n=0;return function(r,e){var u=Ri(),o=16-(u-n);if(n=u,0<o){if(150<=++t)return r}else t=0;return Ko(r,e)}}(),ni=so||function(t,n){return Vt.setTimeout(t,n)},ri=Wo?function(t,n,r){n+="";var e;e=(e=n.match(pt))?e[1].split(_t):[],r=Ee(e,r),e=r.length;var u=e-1;return r[u]=(1<e?"& ":"")+r[u],r=r.join(2<e?", ":" "),n=n.replace(ht,"{\n/* [wrapped with "+r+"] */\n"),Wo(t,"toString",{configurable:true,enumerable:false,value:Eu(n)})}:Ou,ei=Ge(function(t){t=gu(t);var n=[];return ot.test(t)&&n.push(""),t.replace(it,function(t,r,e,u){
n.push(e?u.replace(gt,"$1"):r||t)}),n}),ui=ar(function(t,n){return Xe(t)?jn(t,kn(n,1,Xe,true)):[]}),oi=ar(function(t,n){var r=We(n);return Xe(r)&&(r=P),Xe(t)?jn(t,kn(n,1,Xe,true),fe(r,2)):[]}),ii=ar(function(t,n){var r=We(n);return Xe(r)&&(r=P),Xe(t)?jn(t,kn(n,1,Xe,true),P,r):[]}),fi=ar(function(t){var n=l(t,mr);return n.length&&n[0]===t[0]?Cn(n):[]}),ci=ar(function(t){var n=We(t),r=l(t,mr);return n===We(r)?n=P:r.pop(),r.length&&r[0]===t[0]?Cn(r,fe(n,2)):[]}),ai=ar(function(t){var n=We(t),r=l(t,mr);return n===We(r)?n=P:r.pop(),
r.length&&r[0]===t[0]?Cn(r,P,n):[]}),li=ar(Be),si=ar(function(t,n){n=kn(n,1);var r=t?t.length:0,e=_n(t,n);return ir(t,l(n,function(t){return ge(t,r)?+t:t}).sort(Sr)),e}),hi=ar(function(t){return yr(kn(t,1,Xe,true))}),pi=ar(function(t){var n=We(t);return Xe(n)&&(n=P),yr(kn(t,1,Xe,true),fe(n,2))}),_i=ar(function(t){var n=We(t);return Xe(n)&&(n=P),yr(kn(t,1,Xe,true),P,n)}),vi=ar(function(t,n){return Xe(t)?jn(t,n):[]}),gi=ar(function(t){return jr(f(t,Xe))}),di=ar(function(t){var n=We(t);return Xe(n)&&(n=P),
jr(f(t,Xe),fe(n,2))}),yi=ar(function(t){var n=We(t);return Xe(n)&&(n=P),jr(f(t,Xe),P,n)}),bi=ar(Ce),xi=ar(function(t){var n=t.length,n=1<n?t[n-1]:P,n=typeof n=="function"?(t.pop(),n):P;return Ue(t,n)}),ji=ar(function(t){function n(n){return _n(n,t)}t=kn(t,1);var r=t.length,e=r?t[0]:0,u=this.__wrapped__;return!(1<r||this.__actions__.length)&&u instanceof $t&&ge(e)?(u=u.slice(e,+e+(r?1:0)),u.__actions__.push({func:ze,args:[n],thisArg:P}),new Lt(u,this.__chain__).thru(function(t){return r&&!t.length&&t.push(P),
t})):this.thru(n)}),wi=Cr(function(t,n,r){Gu.call(t,r)?++t[r]:t[r]=1}),mi=Pr(Se),Ai=Pr(Ie),ki=Cr(function(t,n,r){Gu.call(t,r)?t[r].push(n):t[r]=[n]}),Ei=ar(function(t,n,e){var u=-1,o=typeof n=="function",i=ye(n),f=Qe(t)?Cu(t.length):[];return Po(t,function(t){var c=o?n:i&&null!=t?t[n]:P;f[++u]=c?r(c,t,e):Mn(t,n,e)}),f}),Oi=Cr(function(t,n,r){t[r]=n}),Si=Cr(function(t,n,r){t[r?0:1].push(n)},function(){return[[],[]]}),Ii=ar(function(t,n){if(null==t)return[];var r=n.length;return 1<r&&de(t,n[0],n[1])?n=[]:2<r&&de(n[0],n[1],n[2])&&(n=[n[0]]),
nr(t,kn(n,1),[])}),Ri=lo||function(){return Vt.Date.now()},Wi=ar(function(t,n,r){var e=1;if(r.length)var u=z(r,ie(Wi)),e=32|e;return re(t,e,n,r,u)}),Bi=ar(function(t,n,r){var e=3;if(r.length)var u=z(r,ie(Bi)),e=32|e;return re(n,e,t,r,u)}),Li=ar(function(t,n){return xn(t,1,n)}),Ci=ar(function(t,n,r){return xn(t,_u(n)||0,r)});Ge.Cache=qt;var Ui=ar(function(t,n){n=1==n.length&&Fi(n[0])?l(n[0],S(fe())):l(kn(n,1),S(fe()));var e=n.length;return ar(function(u){for(var o=-1,i=jo(u.length,e);++o<i;)u[o]=n[o].call(this,u[o]);
return r(t,this,u)})}),Mi=ar(function(t,n){var r=z(n,ie(Mi));return re(t,32,P,n,r)}),zi=ar(function(t,n){var r=z(n,ie(zi));return re(t,64,P,n,r)}),Di=ar(function(t,n){return re(t,256,P,P,P,kn(n,1))}),Ti=Qr(Wn),$i=Qr(function(t,n){return t>=n}),Fi=Cu.isArray,Ni=Ht?S(Ht):zn,Pi=vo||Lu,Zi=Qt?S(Qt):Dn,qi=Xt?S(Xt):$n,Vi=tn?S(tn):Pn,Ki=nn?S(nn):Zn,Gi=rn?S(rn):qn,Ji=Qr(Jn),Yi=Qr(function(t,n){return t<=n}),Hi=Ur(function(t,n){if(Lo||xe(n)||Qe(n))Br(n,bu(n),t);else for(var r in n)Gu.call(n,r)&&ln(t,r,n[r]);
}),Qi=Ur(function(t,n){Br(n,xu(n),t)}),Xi=Ur(function(t,n,r,e){Br(n,xu(n),t,e)}),tf=Ur(function(t,n,r,e){Br(n,bu(n),t,e)}),nf=ar(function(t,n){return _n(t,kn(n,1))}),rf=ar(function(t){return t.push(P,en),r(Xi,P,t)}),ef=ar(function(t){return t.push(P,we),r(af,P,t)}),uf=Vr(function(t,n,r){t[n]=r},Eu(Ou)),of=Vr(function(t,n,r){Gu.call(t,n)?t[n].push(r):t[n]=[r]},fe),ff=ar(Mn),cf=Ur(function(t,n,r){Xn(t,n,r)}),af=Ur(function(t,n,r,e){Xn(t,n,r,e)}),lf=ar(function(t,n){return null==t?{}:(n=l(kn(n,1),Ae),
rr(t,jn(Rn(t,xu,Qo),n)))}),sf=ar(function(t,n){return null==t?{}:rr(t,l(kn(n,1),Ae))}),hf=ne(bu),pf=ne(xu),_f=$r(function(t,n,r){return n=n.toLowerCase(),t+(r?mu(n):n)}),vf=$r(function(t,n,r){return t+(r?"-":"")+n.toLowerCase()}),gf=$r(function(t,n,r){return t+(r?" ":"")+n.toLowerCase()}),df=Tr("toLowerCase"),yf=$r(function(t,n,r){return t+(r?"_":"")+n.toLowerCase()}),bf=$r(function(t,n,r){return t+(r?" ":"")+jf(n)}),xf=$r(function(t,n,r){return t+(r?" ":"")+n.toUpperCase()}),jf=Tr("toUpperCase"),wf=ar(function(t,n){
try{return r(t,P,n)}catch(t){return tu(t)?t:new Mu(t)}}),mf=ar(function(t,n){return u(kn(n,1),function(n){n=Ae(n),t[n]=Wi(t[n],t)}),t}),Af=Zr(),kf=Zr(true),Ef=ar(function(t,n){return function(r){return Mn(r,t,n)}}),Of=ar(function(t,n){return function(r){return Mn(t,r,n)}}),Sf=Gr(l),If=Gr(i),Rf=Gr(_),Wf=Hr(),Bf=Hr(true),Lf=Kr(function(t,n){return t+n},0),Cf=te("ceil"),Uf=Kr(function(t,n){return t/n},1),Mf=te("floor"),zf=Kr(function(t,n){return t*n},1),Df=te("round"),Tf=Kr(function(t,n){return t-n},0);return It.after=function(t,n){
if(typeof n!="function")throw new Nu("Expected a function");return t=hu(t),function(){if(1>--t)return n.apply(this,arguments)}},It.ary=Pe,It.assign=Hi,It.assignIn=Qi,It.assignInWith=Xi,It.assignWith=tf,It.at=nf,It.before=Ze,It.bind=Wi,It.bindAll=mf,It.bindKey=Bi,It.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return Fi(t)?t:[t]},It.chain=Me,It.chunk=function(t,n,r){if(n=(r?de(t,n,r):n===P)?1:xo(hu(n),0),r=t?t.length:0,!r||1>n)return[];for(var e=0,u=0,o=Cu(ho(r/n));e<r;)o[u++]=sr(t,e,e+=n);
return o},It.compact=function(t){for(var n=-1,r=t?t.length:0,e=0,u=[];++n<r;){var o=t[n];o&&(u[e++]=o)}return u},It.concat=function(){for(var t=arguments.length,n=Cu(t?t-1:0),r=arguments[0],e=t;e--;)n[e-1]=arguments[e];return t?s(Fi(r)?Wr(r):[r],kn(n,1)):[]},It.cond=function(t){var n=t?t.length:0,e=fe();return t=n?l(t,function(t){if("function"!=typeof t[1])throw new Nu("Expected a function");return[e(t[0]),t[1]]}):[],ar(function(e){for(var u=-1;++u<n;){var o=t[u];if(r(o[0],this,e))return r(o[1],this,e);
}})},It.conforms=function(t){return dn(gn(t,true))},It.constant=Eu,It.countBy=wi,It.create=function(t,n){var r=bn(t);return n?pn(r,n):r},It.curry=qe,It.curryRight=Ve,It.debounce=Ke,It.defaults=rf,It.defaultsDeep=ef,It.defer=Li,It.delay=Ci,It.difference=ui,It.differenceBy=oi,It.differenceWith=ii,It.drop=function(t,n,r){var e=t?t.length:0;return e?(n=r||n===P?1:hu(n),sr(t,0>n?0:n,e)):[]},It.dropRight=function(t,n,r){var e=t?t.length:0;return e?(n=r||n===P?1:hu(n),n=e-n,sr(t,0,0>n?0:n)):[]},It.dropRightWhile=function(t,n){
return t&&t.length?br(t,fe(n,3),true,true):[]},It.dropWhile=function(t,n){return t&&t.length?br(t,fe(n,3),true):[]},It.fill=function(t,n,r,e){var u=t?t.length:0;if(!u)return[];for(r&&typeof r!="number"&&de(t,n,r)&&(r=0,e=u),u=t.length,r=hu(r),0>r&&(r=-r>u?0:u+r),e=e===P||e>u?u:hu(e),0>e&&(e+=u),e=r>e?0:pu(e);r<e;)t[r++]=n;return t},It.filter=function(t,n){return(Fi(t)?f:An)(t,fe(n,3))},It.flatMap=function(t,n){return kn(Fe(t,n),1)},It.flatMapDeep=function(t,n){return kn(Fe(t,n),Z)},It.flatMapDepth=function(t,n,r){
return r=r===P?1:hu(r),kn(Fe(t,n),r)},It.flatten=function(t){return t&&t.length?kn(t,1):[]},It.flattenDeep=function(t){return t&&t.length?kn(t,Z):[]},It.flattenDepth=function(t,n){return t&&t.length?(n=n===P?1:hu(n),kn(t,n)):[]},It.flip=function(t){return re(t,512)},It.flow=Af,It.flowRight=kf,It.fromPairs=function(t){for(var n=-1,r=t?t.length:0,e={};++n<r;){var u=t[n];e[u[0]]=u[1]}return e},It.functions=function(t){return null==t?[]:Sn(t,bu(t))},It.functionsIn=function(t){return null==t?[]:Sn(t,xu(t));
},It.groupBy=ki,It.initial=function(t){return t&&t.length?sr(t,0,-1):[]},It.intersection=fi,It.intersectionBy=ci,It.intersectionWith=ai,It.invert=uf,It.invertBy=of,It.invokeMap=Ei,It.iteratee=Su,It.keyBy=Oi,It.keys=bu,It.keysIn=xu,It.map=Fe,It.mapKeys=function(t,n){var r={};return n=fe(n,3),En(t,function(t,e,u){r[n(t,e,u)]=t}),r},It.mapValues=function(t,n){var r={};return n=fe(n,3),En(t,function(t,e,u){r[e]=n(t,e,u)}),r},It.matches=function(t){return Hn(gn(t,true))},It.matchesProperty=function(t,n){
return Qn(t,gn(n,true))},It.memoize=Ge,It.merge=cf,It.mergeWith=af,It.method=Ef,It.methodOf=Of,It.mixin=Iu,It.negate=Je,It.nthArg=function(t){return t=hu(t),ar(function(n){return tr(n,t)})},It.omit=lf,It.omitBy=function(t,n){return ju(t,Je(fe(n)))},It.once=function(t){return Ze(2,t)},It.orderBy=function(t,n,r,e){return null==t?[]:(Fi(n)||(n=null==n?[]:[n]),r=e?P:r,Fi(r)||(r=null==r?[]:[r]),nr(t,n,r))},It.over=Sf,It.overArgs=Ui,It.overEvery=If,It.overSome=Rf,It.partial=Mi,It.partialRight=zi,It.partition=Si,
It.pick=sf,It.pickBy=ju,It.property=Wu,It.propertyOf=function(t){return function(n){return null==t?P:In(t,n)}},It.pull=li,It.pullAll=Be,It.pullAllBy=function(t,n,r){return t&&t.length&&n&&n.length?or(t,n,fe(r,2)):t},It.pullAllWith=function(t,n,r){return t&&t.length&&n&&n.length?or(t,n,P,r):t},It.pullAt=si,It.range=Wf,It.rangeRight=Bf,It.rearg=Di,It.reject=function(t,n){return(Fi(t)?f:An)(t,Je(fe(n,3)))},It.remove=function(t,n){var r=[];if(!t||!t.length)return r;var e=-1,u=[],o=t.length;for(n=fe(n,3);++e<o;){
var i=t[e];n(i,e,t)&&(r.push(i),u.push(e))}return ir(t,u),r},It.rest=function(t,n){if(typeof t!="function")throw new Nu("Expected a function");return n=n===P?n:hu(n),ar(t,n)},It.reverse=Le,It.sampleSize=Ne,It.set=function(t,n,r){return null==t?t:lr(t,n,r)},It.setWith=function(t,n,r,e){return e=typeof e=="function"?e:P,null==t?t:lr(t,n,r,e)},It.shuffle=function(t){return Ne(t,4294967295)},It.slice=function(t,n,r){var e=t?t.length:0;return e?(r&&typeof r!="number"&&de(t,n,r)?(n=0,r=e):(n=null==n?0:hu(n),
r=r===P?e:hu(r)),sr(t,n,r)):[]},It.sortBy=Ii,It.sortedUniq=function(t){return t&&t.length?vr(t):[]},It.sortedUniqBy=function(t,n){return t&&t.length?vr(t,fe(n,2)):[]},It.split=function(t,n,r){return r&&typeof r!="number"&&de(t,n,r)&&(n=r=P),r=r===P?4294967295:r>>>0,r?(t=gu(t))&&(typeof n=="string"||null!=n&&!Vi(n))&&(n=dr(n),!n&&Ut.test(t))?kr(F(t),0,r):t.split(n,r):[]},It.spread=function(t,n){if(typeof t!="function")throw new Nu("Expected a function");return n=n===P?0:xo(hu(n),0),ar(function(e){
var u=e[n];return e=kr(e,0,n),u&&s(e,u),r(t,this,e)})},It.tail=function(t){var n=t?t.length:0;return n?sr(t,1,n):[]},It.take=function(t,n,r){return t&&t.length?(n=r||n===P?1:hu(n),sr(t,0,0>n?0:n)):[]},It.takeRight=function(t,n,r){var e=t?t.length:0;return e?(n=r||n===P?1:hu(n),n=e-n,sr(t,0>n?0:n,e)):[]},It.takeRightWhile=function(t,n){return t&&t.length?br(t,fe(n,3),false,true):[]},It.takeWhile=function(t,n){return t&&t.length?br(t,fe(n,3)):[]},It.tap=function(t,n){return n(t),t},It.throttle=function(t,n,r){
var e=true,u=true;if(typeof t!="function")throw new Nu("Expected a function");return uu(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),Ke(t,n,{leading:e,maxWait:n,trailing:u})},It.thru=ze,It.toArray=lu,It.toPairs=hf,It.toPairsIn=pf,It.toPath=function(t){return Fi(t)?l(t,Ae):au(t)?[t]:Wr(ei(t))},It.toPlainObject=vu,It.transform=function(t,n,r){var e=Fi(t)||Gi(t);if(n=fe(n,4),null==r)if(e||uu(t)){var o=t.constructor;r=e?Fi(t)?new o:[]:nu(o)?bn(eo(t)):{}}else r={};return(e?u:En)(t,function(t,e,u){
return n(r,t,e,u)}),r},It.unary=function(t){return Pe(t,1)},It.union=hi,It.unionBy=pi,It.unionWith=_i,It.uniq=function(t){return t&&t.length?yr(t):[]},It.uniqBy=function(t,n){return t&&t.length?yr(t,fe(n,2)):[]},It.uniqWith=function(t,n){return t&&t.length?yr(t,P,n):[]},It.unset=function(t,n){var r;if(null==t)r=true;else{r=t;var e=n,e=ye(e,r)?[e]:Ar(e);r=me(r,e),e=Ae(We(e)),r=!(null!=r&&Gu.call(r,e))||delete r[e]}return r},It.unzip=Ce,It.unzipWith=Ue,It.update=function(t,n,r){return null==t?t:lr(t,n,(typeof r=="function"?r:Ou)(In(t,n)),void 0);
},It.updateWith=function(t,n,r,e){return e=typeof e=="function"?e:P,null!=t&&(t=lr(t,n,(typeof r=="function"?r:Ou)(In(t,n)),e)),t},It.values=wu,It.valuesIn=function(t){return null==t?[]:I(t,xu(t))},It.without=vi,It.words=ku,It.wrap=function(t,n){return n=null==n?Ou:n,Mi(n,t)},It.xor=gi,It.xorBy=di,It.xorWith=yi,It.zip=bi,It.zipObject=function(t,n){return wr(t||[],n||[],ln)},It.zipObjectDeep=function(t,n){return wr(t||[],n||[],lr)},It.zipWith=xi,It.entries=hf,It.entriesIn=pf,It.extend=Qi,It.extendWith=Xi,
Iu(It,It),It.add=Lf,It.attempt=wf,It.camelCase=_f,It.capitalize=mu,It.ceil=Cf,It.clamp=function(t,n,r){return r===P&&(r=n,n=P),r!==P&&(r=_u(r),r=r===r?r:0),n!==P&&(n=_u(n),n=n===n?n:0),vn(_u(t),n,r)},It.clone=function(t){return gn(t,false,true)},It.cloneDeep=function(t){return gn(t,true,true)},It.cloneDeepWith=function(t,n){return gn(t,true,true,n)},It.cloneWith=function(t,n){return gn(t,false,true,n)},It.conformsTo=function(t,n){return null==n||yn(t,n,bu(n))},It.deburr=Au,It.defaultTo=function(t,n){return null==t||t!==t?n:t;
},It.divide=Uf,It.endsWith=function(t,n,r){t=gu(t),n=dr(n);var e=t.length,e=r=r===P?e:vn(hu(r),0,e);return r-=n.length,0<=r&&t.slice(r,e)==n},It.eq=Ye,It.escape=function(t){return(t=gu(t))&&X.test(t)?t.replace(H,on):t},It.escapeRegExp=function(t){return(t=gu(t))&&ct.test(t)?t.replace(ft,"\\$&"):t},It.every=function(t,n,r){var e=Fi(t)?i:wn;return r&&de(t,n,r)&&(n=P),e(t,fe(n,3))},It.find=mi,It.findIndex=Se,It.findKey=function(t,n){return v(t,fe(n,3),En)},It.findLast=Ai,It.findLastIndex=Ie,It.findLastKey=function(t,n){
return v(t,fe(n,3),On)},It.floor=Mf,It.forEach=Te,It.forEachRight=$e,It.forIn=function(t,n){return null==t?t:qo(t,fe(n,3),xu)},It.forInRight=function(t,n){return null==t?t:Vo(t,fe(n,3),xu)},It.forOwn=function(t,n){return t&&En(t,fe(n,3))},It.forOwnRight=function(t,n){return t&&On(t,fe(n,3))},It.get=du,It.gt=Ti,It.gte=$i,It.has=function(t,n){return null!=t&&se(t,n,Bn)},It.hasIn=yu,It.head=Re,It.identity=Ou,It.includes=function(t,n,r,e){return t=Qe(t)?t:wu(t),r=r&&!e?hu(r):0,e=t.length,0>r&&(r=xo(e+r,0)),
cu(t)?r<=e&&-1<t.indexOf(n,r):!!e&&-1<d(t,n,r)},It.indexOf=function(t,n,r){var e=t?t.length:0;return e?(r=null==r?0:hu(r),0>r&&(r=xo(e+r,0)),d(t,n,r)):-1},It.inRange=function(t,n,r){return n=su(n),r===P?(r=n,n=0):r=su(r),t=_u(t),t>=jo(n,r)&&t<xo(n,r)},It.invoke=ff,It.isArguments=He,It.isArray=Fi,It.isArrayBuffer=Ni,It.isArrayLike=Qe,It.isArrayLikeObject=Xe,It.isBoolean=function(t){return true===t||false===t||ou(t)&&"[object Boolean]"==Hu.call(t)},It.isBuffer=Pi,It.isDate=Zi,It.isElement=function(t){return!!t&&1===t.nodeType&&ou(t)&&!fu(t);
},It.isEmpty=function(t){if(Qe(t)&&(Fi(t)||typeof t=="string"||typeof t.splice=="function"||Pi(t)||He(t)))return!t.length;var n=St(t);if("[object Map]"==n||"[object Set]"==n)return!t.size;if(Lo||xe(t))return!bo(t).length;for(var r in t)if(Gu.call(t,r))return false;return true},It.isEqual=function(t,n){return Tn(t,n)},It.isEqualWith=function(t,n,r){var e=(r=typeof r=="function"?r:P)?r(t,n):P;return e===P?Tn(t,n,r):!!e},It.isError=tu,It.isFinite=function(t){return typeof t=="number"&&go(t)},It.isFunction=nu,
It.isInteger=ru,It.isLength=eu,It.isMap=qi,It.isMatch=function(t,n){return t===n||Fn(t,n,ae(n))},It.isMatchWith=function(t,n,r){return r=typeof r=="function"?r:P,Fn(t,n,ae(n),r)},It.isNaN=function(t){return iu(t)&&t!=+t},It.isNative=function(t){if(Xo(t))throw new Mu("This method is not supported with core-js. Try https://github.com/es-shims.");return Nn(t)},It.isNil=function(t){return null==t},It.isNull=function(t){return null===t},It.isNumber=iu,It.isObject=uu,It.isObjectLike=ou,It.isPlainObject=fu,
It.isRegExp=Vi,It.isSafeInteger=function(t){return ru(t)&&-9007199254740991<=t&&9007199254740991>=t},It.isSet=Ki,It.isString=cu,It.isSymbol=au,It.isTypedArray=Gi,It.isUndefined=function(t){return t===P},It.isWeakMap=function(t){return ou(t)&&"[object WeakMap]"==St(t)},It.isWeakSet=function(t){return ou(t)&&"[object WeakSet]"==Hu.call(t)},It.join=function(t,n){return t?yo.call(t,n):""},It.kebabCase=vf,It.last=We,It.lastIndexOf=function(t,n,r){var e=t?t.length:0;if(!e)return-1;var u=e;if(r!==P&&(u=hu(r),
u=(0>u?xo(e+u,0):jo(u,e-1))+1),n!==n)return g(t,b,u-1,true);for(;u--;)if(t[u]===n)return u;return-1},It.lowerCase=gf,It.lowerFirst=df,It.lt=Ji,It.lte=Yi,It.max=function(t){return t&&t.length?mn(t,Ou,Wn):P},It.maxBy=function(t,n){return t&&t.length?mn(t,fe(n,2),Wn):P},It.mean=function(t){return x(t,Ou)},It.meanBy=function(t,n){return x(t,fe(n,2))},It.min=function(t){return t&&t.length?mn(t,Ou,Jn):P},It.minBy=function(t,n){return t&&t.length?mn(t,fe(n,2),Jn):P},It.stubArray=Bu,It.stubFalse=Lu,It.stubObject=function(){
return{}},It.stubString=function(){return""},It.stubTrue=function(){return true},It.multiply=zf,It.nth=function(t,n){return t&&t.length?tr(t,hu(n)):P},It.noConflict=function(){return Vt._===this&&(Vt._=Qu),this},It.noop=Ru,It.now=Ri,It.pad=function(t,n,r){t=gu(t);var e=(n=hu(n))?$(t):0;return!n||e>=n?t:(n=(n-e)/2,Jr(po(n),r)+t+Jr(ho(n),r))},It.padEnd=function(t,n,r){t=gu(t);var e=(n=hu(n))?$(t):0;return n&&e<n?t+Jr(n-e,r):t},It.padStart=function(t,n,r){t=gu(t);var e=(n=hu(n))?$(t):0;return n&&e<n?Jr(n-e,r)+t:t;
},It.parseInt=function(t,n,r){return r||null==n?n=0:n&&(n=+n),t=gu(t).replace(at,""),wo(t,n||(bt.test(t)?16:10))},It.random=function(t,n,r){if(r&&typeof r!="boolean"&&de(t,n,r)&&(n=r=P),r===P&&(typeof n=="boolean"?(r=n,n=P):typeof t=="boolean"&&(r=t,t=P)),t===P&&n===P?(t=0,n=1):(t=su(t),n===P?(n=t,t=0):n=su(n)),t>n){var e=t;t=n,n=e}return r||t%1||n%1?(r=mo(),jo(t+r*(n-t+Nt("1e-"+((r+"").length-1))),n)):fr(t,n)},It.reduce=function(t,n,r){var e=Fi(t)?h:m,u=3>arguments.length;return e(t,fe(n,4),r,u,Po);
},It.reduceRight=function(t,n,r){var e=Fi(t)?p:m,u=3>arguments.length;return e(t,fe(n,4),r,u,Zo)},It.repeat=function(t,n,r){return n=(r?de(t,n,r):n===P)?1:hu(n),cr(gu(t),n)},It.replace=function(){var t=arguments,n=gu(t[0]);return 3>t.length?n:n.replace(t[1],t[2])},It.result=function(t,n,r){n=ye(n,t)?[n]:Ar(n);var e=-1,u=n.length;for(u||(t=P,u=1);++e<u;){var o=null==t?P:t[Ae(n[e])];o===P&&(e=u,o=r),t=nu(o)?o.call(t):o}return t},It.round=Df,It.runInContext=N,It.sample=function(t){t=Qe(t)?t:wu(t);var n=t.length;
return 0<n?t[fr(0,n-1)]:P},It.size=function(t){if(null==t)return 0;if(Qe(t))return cu(t)?$(t):t.length;var n=St(t);return"[object Map]"==n||"[object Set]"==n?t.size:Kn(t).length},It.snakeCase=yf,It.some=function(t,n,r){var e=Fi(t)?_:hr;return r&&de(t,n,r)&&(n=P),e(t,fe(n,3))},It.sortedIndex=function(t,n){return pr(t,n)},It.sortedIndexBy=function(t,n,r){return _r(t,n,fe(r,2))},It.sortedIndexOf=function(t,n){var r=t?t.length:0;if(r){var e=pr(t,n);if(e<r&&Ye(t[e],n))return e}return-1},It.sortedLastIndex=function(t,n){
return pr(t,n,true)},It.sortedLastIndexBy=function(t,n,r){return _r(t,n,fe(r,2),true)},It.sortedLastIndexOf=function(t,n){if(t&&t.length){var r=pr(t,n,true)-1;if(Ye(t[r],n))return r}return-1},It.startCase=bf,It.startsWith=function(t,n,r){return t=gu(t),r=vn(hu(r),0,t.length),n=dr(n),t.slice(r,r+n.length)==n},It.subtract=Tf,It.sum=function(t){return t&&t.length?k(t,Ou):0},It.sumBy=function(t,n){return t&&t.length?k(t,fe(n,2)):0},It.template=function(t,n,r){var e=It.templateSettings;r&&de(t,n,r)&&(n=P),t=gu(t),
n=Xi({},n,e,en),r=Xi({},n.imports,e.imports,en);var u,o,i=bu(r),f=I(r,i),c=0;r=n.interpolate||Et;var a="__p+='";r=$u((n.escape||Et).source+"|"+r.source+"|"+(r===rt?dt:Et).source+"|"+(n.evaluate||Et).source+"|$","g");var l="sourceURL"in n?"//# sourceURL="+n.sourceURL+"\n":"";if(t.replace(r,function(n,r,e,i,f,l){return e||(e=i),a+=t.slice(c,l).replace(Ot,L),r&&(u=true,a+="'+__e("+r+")+'"),f&&(o=true,a+="';"+f+";\n__p+='"),e&&(a+="'+((__t=("+e+"))==null?'':__t)+'"),c=l+n.length,n}),a+="';",(n=n.variable)||(a="with(obj){"+a+"}"),
a=(o?a.replace(K,""):a).replace(G,"$1").replace(J,"$1;"),a="function("+(n||"obj")+"){"+(n?"":"obj||(obj={});")+"var __t,__p=''"+(u?",__e=_.escape":"")+(o?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+a+"return __p}",n=wf(function(){return zu(i,l+"return "+a).apply(P,f)}),n.source=a,tu(n))throw n;return n},It.times=function(t,n){if(t=hu(t),1>t||9007199254740991<t)return[];var r=4294967295,e=jo(t,4294967295);for(n=fe(n),t-=4294967295,e=E(e,n);++r<t;)n(r);return e},It.toFinite=su,
It.toInteger=hu,It.toLength=pu,It.toLower=function(t){return gu(t).toLowerCase()},It.toNumber=_u,It.toSafeInteger=function(t){return vn(hu(t),-9007199254740991,9007199254740991)},It.toString=gu,It.toUpper=function(t){return gu(t).toUpperCase()},It.trim=function(t,n,r){return(t=gu(t))&&(r||n===P)?t.replace(at,""):t&&(n=dr(n))?(t=F(t),r=F(n),n=W(t,r),r=B(t,r)+1,kr(t,n,r).join("")):t},It.trimEnd=function(t,n,r){return(t=gu(t))&&(r||n===P)?t.replace(st,""):t&&(n=dr(n))?(t=F(t),n=B(t,F(n))+1,kr(t,0,n).join("")):t;
},It.trimStart=function(t,n,r){return(t=gu(t))&&(r||n===P)?t.replace(lt,""):t&&(n=dr(n))?(t=F(t),n=W(t,F(n)),kr(t,n).join("")):t},It.truncate=function(t,n){var r=30,e="...";if(uu(n))var u="separator"in n?n.separator:u,r="length"in n?hu(n.length):r,e="omission"in n?dr(n.omission):e;t=gu(t);var o=t.length;if(Ut.test(t))var i=F(t),o=i.length;if(r>=o)return t;if(o=r-$(e),1>o)return e;if(r=i?kr(i,0,o).join(""):t.slice(0,o),u===P)return r+e;if(i&&(o+=r.length-o),Vi(u)){if(t.slice(o).search(u)){var f=r;for(u.global||(u=$u(u.source,gu(yt.exec(u))+"g")),
u.lastIndex=0;i=u.exec(f);)var c=i.index;r=r.slice(0,c===P?o:c)}}else t.indexOf(dr(u),o)!=o&&(u=r.lastIndexOf(u),-1<u&&(r=r.slice(0,u)));return r+e},It.unescape=function(t){return(t=gu(t))&&Q.test(t)?t.replace(Y,fn):t},It.uniqueId=function(t){var n=++Ju;return gu(t)+n},It.upperCase=xf,It.upperFirst=jf,It.each=Te,It.eachRight=$e,It.first=Re,Iu(It,function(){var t={};return En(It,function(n,r){Gu.call(It.prototype,r)||(t[r]=n)}),t}(),{chain:false}),It.VERSION="4.15.0",u("bind bindKey curry curryRight partial partialRight".split(" "),function(t){
It[t].placeholder=It}),u(["drop","take"],function(t,n){$t.prototype[t]=function(r){var e=this.__filtered__;if(e&&!n)return new $t(this);r=r===P?1:xo(hu(r),0);var u=this.clone();return e?u.__takeCount__=jo(r,u.__takeCount__):u.__views__.push({size:jo(r,4294967295),type:t+(0>u.__dir__?"Right":"")}),u},$t.prototype[t+"Right"]=function(n){return this.reverse()[t](n).reverse()}}),u(["filter","map","takeWhile"],function(t,n){var r=n+1,e=1==r||3==r;$t.prototype[t]=function(t){var n=this.clone();return n.__iteratees__.push({
iteratee:fe(t,3),type:r}),n.__filtered__=n.__filtered__||e,n}}),u(["head","last"],function(t,n){var r="take"+(n?"Right":"");$t.prototype[t]=function(){return this[r](1).value()[0]}}),u(["initial","tail"],function(t,n){var r="drop"+(n?"":"Right");$t.prototype[t]=function(){return this.__filtered__?new $t(this):this[r](1)}}),$t.prototype.compact=function(){return this.filter(Ou)},$t.prototype.find=function(t){return this.filter(t).head()},$t.prototype.findLast=function(t){return this.reverse().find(t);
},$t.prototype.invokeMap=ar(function(t,n){return typeof t=="function"?new $t(this):this.map(function(r){return Mn(r,t,n)})}),$t.prototype.reject=function(t){return this.filter(Je(fe(t)))},$t.prototype.slice=function(t,n){t=hu(t);var r=this;return r.__filtered__&&(0<t||0>n)?new $t(r):(0>t?r=r.takeRight(-t):t&&(r=r.drop(t)),n!==P&&(n=hu(n),r=0>n?r.dropRight(-n):r.take(n-t)),r)},$t.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},$t.prototype.toArray=function(){return this.take(4294967295);
},En($t.prototype,function(t,n){var r=/^(?:filter|find|map|reject)|While$/.test(n),e=/^(?:head|last)$/.test(n),u=It[e?"take"+("last"==n?"Right":""):n],o=e||/^find/.test(n);u&&(It.prototype[n]=function(){function n(t){return t=u.apply(It,s([t],f)),e&&h?t[0]:t}var i=this.__wrapped__,f=e?[1]:arguments,c=i instanceof $t,a=f[0],l=c||Fi(i);l&&r&&typeof a=="function"&&1!=a.length&&(c=l=false);var h=this.__chain__,p=!!this.__actions__.length,a=o&&!h,c=c&&!p;return!o&&l?(i=c?i:new $t(this),i=t.apply(i,f),i.__actions__.push({
func:ze,args:[n],thisArg:P}),new Lt(i,h)):a&&c?t.apply(this,f):(i=this.thru(n),a?e?i.value()[0]:i.value():i)})}),u("pop push shift sort splice unshift".split(" "),function(t){var n=Pu[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",e=/^(?:pop|shift)$/.test(t);It.prototype[t]=function(){var t=arguments;if(e&&!this.__chain__){var u=this.value();return n.apply(Fi(u)?u:[],t)}return this[r](function(r){return n.apply(Fi(r)?r:[],t)})}}),En($t.prototype,function(t,n){var r=It[n];if(r){var e=r.name+"";
(Co[e]||(Co[e]=[])).push({name:n,func:r})}}),Co[qr(P,2).name]=[{name:"wrapper",func:P}],$t.prototype.clone=function(){var t=new $t(this.__wrapped__);return t.__actions__=Wr(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=Wr(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=Wr(this.__views__),t},$t.prototype.reverse=function(){if(this.__filtered__){var t=new $t(this);t.__dir__=-1,t.__filtered__=true}else t=this.clone(),t.__dir__*=-1;return t;
},$t.prototype.value=function(){var t,n=this.__wrapped__.value(),r=this.__dir__,e=Fi(n),u=0>r,o=e?n.length:0;t=o;for(var i=this.__views__,f=0,c=-1,a=i.length;++c<a;){var l=i[c],s=l.size;switch(l.type){case"drop":f+=s;break;case"dropRight":t-=s;break;case"take":t=jo(t,f+s);break;case"takeRight":f=xo(f,t-s)}}if(t={start:f,end:t},i=t.start,f=t.end,t=f-i,u=u?f:i-1,i=this.__iteratees__,f=i.length,c=0,a=jo(t,this.__takeCount__),!e||200>o||o==t&&a==t)return xr(n,this.__actions__);e=[];t:for(;t--&&c<a;){
for(u+=r,o=-1,l=n[u];++o<f;){var h=i[o],s=h.type,h=(0,h.iteratee)(l);if(2==s)l=h;else if(!h){if(1==s)continue t;break t}}e[c++]=l}return e},It.prototype.at=ji,It.prototype.chain=function(){return Me(this)},It.prototype.commit=function(){return new Lt(this.value(),this.__chain__)},It.prototype.next=function(){this.__values__===P&&(this.__values__=lu(this.value()));var t=this.__index__>=this.__values__.length,n=t?P:this.__values__[this.__index__++];return{done:t,value:n}},It.prototype.plant=function(t){
for(var n,r=this;r instanceof Rt;){var e=Oe(r);e.__index__=0,e.__values__=P,n?u.__wrapped__=e:n=e;var u=e,r=r.__wrapped__}return u.__wrapped__=t,n},It.prototype.reverse=function(){var t=this.__wrapped__;return t instanceof $t?(this.__actions__.length&&(t=new $t(this)),t=t.reverse(),t.__actions__.push({func:ze,args:[Le],thisArg:P}),new Lt(t,this.__chain__)):this.thru(Le)},It.prototype.toJSON=It.prototype.valueOf=It.prototype.value=function(){return xr(this.__wrapped__,this.__actions__)},It.prototype.first=It.prototype.head,
uo&&(It.prototype[uo]=De),It}var P,Z=1/0,q=NaN,V=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],K=/\b__p\+='';/g,G=/\b(__p\+=)''\+/g,J=/(__e\(.*?\)|\b__t\))\+'';/g,Y=/&(?:amp|lt|gt|quot|#39|#96);/g,H=/[&<>"'`]/g,Q=RegExp(Y.source),X=RegExp(H.source),tt=/<%-([\s\S]+?)%>/g,nt=/<%([\s\S]+?)%>/g,rt=/<%=([\s\S]+?)%>/g,et=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ut=/^\w*$/,ot=/^\./,it=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ft=/[\\^$.*+?()[\]{}|]/g,ct=RegExp(ft.source),at=/^\s+|\s+$/g,lt=/^\s+/,st=/\s+$/,ht=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,pt=/\{\n\/\* \[wrapped with (.+)\] \*/,_t=/,? & /,vt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,gt=/\\(\\)?/g,dt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,yt=/\w*$/,bt=/^0x/i,xt=/^[-+]0x[0-9a-f]+$/i,jt=/^0b[01]+$/i,wt=/^\[object .+?Constructor\]$/,mt=/^0o[0-7]+$/i,At=/^(?:0|[1-9]\d*)$/,kt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Et=/($^)/,Ot=/['\n\r\u2028\u2029\\]/g,St="[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?(?:\\u200d(?:[^\\ud800-\\udfff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?)*",It="(?:[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])"+St,Rt="(?:[^\\ud800-\\udfff][\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]?|[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\ud800-\\udfff])",Wt=RegExp("['\u2019]","g"),Bt=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]","g"),Lt=RegExp("\\ud83c[\\udffb-\\udfff](?=\\ud83c[\\udffb-\\udfff])|"+Rt+St,"g"),Ct=RegExp(["[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+(?:['\u2019](?:d|ll|m|re|s|t|ve))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde]|$)|(?:[A-Z\\xc0-\\xd6\\xd8-\\xde]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde](?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])|$)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?(?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:d|ll|m|re|s|t|ve))?|[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?|\\d+",It].join("|"),"g"),Ut=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),Mt=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zt="Array Buffer DataView Date Error Float32Array Float64Array Function Int8Array Int16Array Int32Array Map Math Object Promise RegExp Set String Symbol TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array WeakMap _ clearTimeout isFinite parseInt setTimeout".split(" "),Dt={};
Dt["[object Float32Array]"]=Dt["[object Float64Array]"]=Dt["[object Int8Array]"]=Dt["[object Int16Array]"]=Dt["[object Int32Array]"]=Dt["[object Uint8Array]"]=Dt["[object Uint8ClampedArray]"]=Dt["[object Uint16Array]"]=Dt["[object Uint32Array]"]=true,Dt["[object Arguments]"]=Dt["[object Array]"]=Dt["[object ArrayBuffer]"]=Dt["[object Boolean]"]=Dt["[object DataView]"]=Dt["[object Date]"]=Dt["[object Error]"]=Dt["[object Function]"]=Dt["[object Map]"]=Dt["[object Number]"]=Dt["[object Object]"]=Dt["[object RegExp]"]=Dt["[object Set]"]=Dt["[object String]"]=Dt["[object WeakMap]"]=false;
var Tt={};Tt["[object Arguments]"]=Tt["[object Array]"]=Tt["[object ArrayBuffer]"]=Tt["[object DataView]"]=Tt["[object Boolean]"]=Tt["[object Date]"]=Tt["[object Float32Array]"]=Tt["[object Float64Array]"]=Tt["[object Int8Array]"]=Tt["[object Int16Array]"]=Tt["[object Int32Array]"]=Tt["[object Map]"]=Tt["[object Number]"]=Tt["[object Object]"]=Tt["[object RegExp]"]=Tt["[object Set]"]=Tt["[object String]"]=Tt["[object Symbol]"]=Tt["[object Uint8Array]"]=Tt["[object Uint8ClampedArray]"]=Tt["[object Uint16Array]"]=Tt["[object Uint32Array]"]=true,
Tt["[object Error]"]=Tt["[object Function]"]=Tt["[object WeakMap]"]=false;var $t,Ft={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Nt=parseFloat,Pt=parseInt,Zt=typeof global=="object"&&global&&global.Object===Object&&global,qt=typeof self=="object"&&self&&self.Object===Object&&self,Vt=Zt||qt||Function("return this")(),Kt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gt=Kt&&typeof module=="object"&&module&&!module.nodeType&&module,Jt=Gt&&Gt.exports===Kt,Yt=Jt&&Zt.g;
t:{try{$t=Yt&&Yt.f("util");break t}catch(t){}$t=void 0}var Ht=$t&&$t.isArrayBuffer,Qt=$t&&$t.isDate,Xt=$t&&$t.isMap,tn=$t&&$t.isRegExp,nn=$t&&$t.isSet,rn=$t&&$t.isTypedArray,en=j("length"),un=w({"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I",
"\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss","\u0100":"A","\u0102":"A","\u0104":"A","\u0101":"a","\u0103":"a","\u0105":"a","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C",
"\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\u010e":"D","\u0110":"D","\u010f":"d","\u0111":"d","\u0112":"E","\u0114":"E","\u0116":"E","\u0118":"E","\u011a":"E","\u0113":"e","\u0115":"e","\u0117":"e","\u0119":"e","\u011b":"e","\u011c":"G","\u011e":"G","\u0120":"G","\u0122":"G","\u011d":"g","\u011f":"g","\u0121":"g","\u0123":"g","\u0124":"H","\u0126":"H","\u0125":"h","\u0127":"h","\u0128":"I","\u012a":"I","\u012c":"I","\u012e":"I","\u0130":"I","\u0129":"i","\u012b":"i","\u012d":"i","\u012f":"i",
"\u0131":"i","\u0134":"J","\u0135":"j","\u0136":"K","\u0137":"k","\u0138":"k","\u0139":"L","\u013b":"L","\u013d":"L","\u013f":"L","\u0141":"L","\u013a":"l","\u013c":"l","\u013e":"l","\u0140":"l","\u0142":"l","\u0143":"N","\u0145":"N","\u0147":"N","\u014a":"N","\u0144":"n","\u0146":"n","\u0148":"n","\u014b":"n","\u014c":"O","\u014e":"O","\u0150":"O","\u014d":"o","\u014f":"o","\u0151":"o","\u0154":"R","\u0156":"R","\u0158":"R","\u0155":"r","\u0157":"r","\u0159":"r","\u015a":"S","\u015c":"S","\u015e":"S",
"\u0160":"S","\u015b":"s","\u015d":"s","\u015f":"s","\u0161":"s","\u0162":"T","\u0164":"T","\u0166":"T","\u0163":"t","\u0165":"t","\u0167":"t","\u0168":"U","\u016a":"U","\u016c":"U","\u016e":"U","\u0170":"U","\u0172":"U","\u0169":"u","\u016b":"u","\u016d":"u","\u016f":"u","\u0171":"u","\u0173":"u","\u0174":"W","\u0175":"w","\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017b":"Z","\u017d":"Z","\u017a":"z","\u017c":"z","\u017e":"z","\u0132":"IJ","\u0133":"ij","\u0152":"Oe","\u0153":"oe","\u0149":"'n",
"\u017f":"ss"}),on=w({"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"}),fn=w({"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"}),cn=N();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Vt._=cn, define(function(){return cn})):Gt?((Gt.exports=cn)._=cn,Kt._=cn):Vt._=cn}).call(this); | public/vendor/lodash/dist/lodash.min.js | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001733010431053117,
0.00017098805983550847,
0.00016439160390291363,
0.0001712429366307333,
0.0000023355062239716062
] |
{
"id": 4,
"code_window": [
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 54
} | # binding [](https://travis-ci.org/go-macaron/binding) [](http://gocover.io/github.com/go-macaron/binding)
Middleware binding provides request data binding and validation for [Macaron](https://github.com/go-macaron/macaron).
### Installation
go get github.com/go-macaron/binding
## Getting Help
- [API Reference](https://gowalker.org/github.com/go-macaron/binding)
- [Documentation](http://go-macaron.com/docs/middlewares/binding)
## Credits
This package is a modified version of [martini-contrib/binding](https://github.com/martini-contrib/binding).
## License
This project is under the Apache License, Version 2.0. See the [LICENSE](LICENSE) file for the full license text. | vendor/github.com/go-macaron/binding/README.md | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.006571566686034203,
0.0023039986845105886,
0.00016645838331896812,
0.00017397094052284956,
0.00301762786693871
] |
{
"id": 4,
"code_window": [
" it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });\n",
" var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 54
} | #*
*.o
*.pyc
*.pyo
*~
extern/
node_modules/
tmp/
data/
vendor/
public_gen/
dist/
| .flooignore | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001682025904301554,
0.0001672981888987124,
0.00016639380191918463,
0.0001672981888987124,
9.043942554853857e-7
] |
{
"id": 5,
"code_window": [
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where tag name IN filter in tag values query for query with one tag', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 60
} | import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import InfluxQueryBuilder from '../query_builder';
describe('InfluxQueryBuilder', function() {
describe('when building explore queries', function() {
it('should only have measurement condition in tag keys query given query with measurement', function() {
var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM "cpu"');
});
it('should handle regex measurement in tag keys query', function() {
var builder = new InfluxQueryBuilder({
measurement: '/.*/', tags: []
});
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS FROM /.*/');
});
it('should have no conditions in tags keys query given query with no measurement or tag', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be('SHOW TAG KEYS');
});
it('should have where condition in tag keys query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'host', value: 'se1'}] });
var query = builder.buildExploreQuery('TAG_KEYS');
expect(query).to.be("SHOW TAG KEYS WHERE \"host\" = 'se1'");
});
it('should have no conditions in measurement query for query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have no conditions in measurement query for query with no tags and empty query', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, '');
expect(query).to.be('SHOW MEASUREMENTS');
});
it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/');
});
it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() {
var builder = new InfluxQueryBuilder({ measurement: '', tags: [{key: 'app', value: 'email'}] });
var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something');
expect(query).to.be("SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE \"app\" = 'email'");
});
it('should have where condition in measurement query for query with tags', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('MEASUREMENTS');
expect(query).to.be("SHOW MEASUREMENTS WHERE \"app\" = 'email'");
});
it('should have where tag name IN filter in tag values query for query with one tag', function() {
var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'asdsadsad'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES WITH KEY = "app"');
});
it('should have measurement tag condition and tag name IN filter in tag values query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}, {key: 'host', value: 'server1'}]});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" = \'server1\'');
});
it('should switch to regex operator in tag condition', function() {
var builder = new InfluxQueryBuilder({
measurement: 'cpu',
tags: [{key: 'host', value: '/server.*/'}]
});
var query = builder.buildExploreQuery('TAG_VALUES', 'app');
expect(query).to.be('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" =~ /server.*/');
});
it('should build show field query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM "cpu"');
});
it('should build show field query with regexp', function() {
var builder = new InfluxQueryBuilder({measurement: '/$var/', tags: [{key: 'app', value: 'email'}]});
var query = builder.buildExploreQuery('FIELDS');
expect(query).to.be('SHOW FIELD KEYS FROM /$var/');
});
it('should build show retention policies query', function() {
var builder = new InfluxQueryBuilder({measurement: 'cpu', tags: []}, 'site');
var query = builder.buildExploreQuery('RETENTION POLICIES');
expect(query).to.be('SHOW RETENTION POLICIES on "site"');
});
});
});
| public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts | 1 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.9980419874191284,
0.8165401220321655,
0.00017963018035516143,
0.9869441986083984,
0.35094761848449707
] |
{
"id": 5,
"code_window": [
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where tag name IN filter in tag values query for query with one tag', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 60
} | @mixin hide-controls() {
.add-row-panel-hint,
.dash-row-menu-container {
display: none;
}
.resize-panel-handle,
.panel-drop-zone {
visibility: hidden;
}
}
.hide-controls {
@include hide-controls();
}
.page-kiosk-mode {
@include hide-controls();
dashnav {
display: none;
}
}
.playlist-active,
.user-activity-low {
.add-row-panel-hint,
.dash-row-menu-container,
.resize-panel-handle,
.panel-drop-zone
.dashnav-refresh-action,
.dashnav-zoom-out,
.dashnav-action-icons,
.panel-info-corner--info,
.panel-info-corner--links,
.dashnav-move-timeframe {
opacity: 0;
transition: all 1.5s ease-in-out 1s;
}
// navbar buttons
.navbar-brand-btn,
.navbar-inner {
border-color: transparent;
background: transparent;
transition: all 1.5s ease-in-out 1s;
.fa {
opacity: 0;
transition: all 1.5s ease-in-out 1s;
}
}
.navbar-page-btn {
border-color: transparent;
background: transparent;
transform: translate3d(-50px, 0, 0);
transition: all 1.5s ease-in-out 1s;
.icon-gf {
opacity: 0;
transition: all 1.5s ease-in-out 1s;
}
}
.gf-timepicker-nav-btn {
transform: translate3d(40px, 0, 0);
transition: transform 1.5s ease-in-out 1s;
}
}
.playlist-active {
.dash-playlist-actions {
.fa {
opacity: 1;
color: $text-color-faint !important;
}
}
}
| public/sass/components/_view_states.scss | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.000174832995980978,
0.00017109271720983088,
0.0001677517284406349,
0.00017099601973313838,
0.000002171417008867138
] |
{
"id": 5,
"code_window": [
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where tag name IN filter in tag values query for query with one tag', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 60
} | package login
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
"github.com/grafana/grafana/pkg/log"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
type LdapConfig struct {
Servers []*LdapServerConf `toml:"servers"`
}
type LdapServerConf struct {
Host string `toml:"host"`
Port int `toml:"port"`
UseSSL bool `toml:"use_ssl"`
StartTLS bool `toml:"start_tls"`
SkipVerifySSL bool `toml:"ssl_skip_verify"`
RootCACert string `toml:"root_ca_cert"`
BindDN string `toml:"bind_dn"`
BindPassword string `toml:"bind_password"`
Attr LdapAttributeMap `toml:"attributes"`
SearchFilter string `toml:"search_filter"`
SearchBaseDNs []string `toml:"search_base_dns"`
GroupSearchFilter string `toml:"group_search_filter"`
GroupSearchFilterUserAttribute string `toml:"group_search_filter_user_attribute"`
GroupSearchBaseDNs []string `toml:"group_search_base_dns"`
LdapGroups []*LdapGroupToOrgRole `toml:"group_mappings"`
}
type LdapAttributeMap struct {
Username string `toml:"username"`
Name string `toml:"name"`
Surname string `toml:"surname"`
Email string `toml:"email"`
MemberOf string `toml:"member_of"`
}
type LdapGroupToOrgRole struct {
GroupDN string `toml:"group_dn"`
OrgId int64 `toml:"org_id"`
OrgRole m.RoleType `toml:"org_role"`
}
var LdapCfg LdapConfig
var ldapLogger log.Logger = log.New("ldap")
func loadLdapConfig() {
if !setting.LdapEnabled {
return
}
ldapLogger.Info("Ldap enabled, reading config file", "file", setting.LdapConfigFile)
_, err := toml.DecodeFile(setting.LdapConfigFile, &LdapCfg)
if err != nil {
ldapLogger.Crit("Failed to load ldap config file", "error", err)
os.Exit(1)
}
if len(LdapCfg.Servers) == 0 {
ldapLogger.Crit("ldap enabled but no ldap servers defined in config file")
os.Exit(1)
}
// set default org id
for _, server := range LdapCfg.Servers {
assertNotEmptyCfg(server.SearchFilter, "search_filter")
assertNotEmptyCfg(server.SearchBaseDNs, "search_base_dns")
for _, groupMap := range server.LdapGroups {
if groupMap.OrgId == 0 {
groupMap.OrgId = 1
}
}
}
}
func assertNotEmptyCfg(val interface{}, propName string) {
switch v := val.(type) {
case string:
if v == "" {
ldapLogger.Crit("LDAP config file is missing option", "option", propName)
os.Exit(1)
}
case []string:
if len(v) == 0 {
ldapLogger.Crit("LDAP config file is missing option", "option", propName)
os.Exit(1)
}
default:
fmt.Println("unknown")
}
}
| pkg/login/settings.go | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.00017126213060691953,
0.0001677448453847319,
0.00016585079720243812,
0.00016758145648054779,
0.0000015111648963284097
] |
{
"id": 5,
"code_window": [
" it('should have where condition in measurement query for query with tags', function() {\n",
" var builder = new InfluxQueryBuilder({measurement: '', tags: [{key: 'app', value: 'email'}]});\n",
" var query = builder.buildExploreQuery('MEASUREMENTS');\n",
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email'\");\n",
" });\n",
"\n",
" it('should have where tag name IN filter in tag values query for query with one tag', function() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(query).to.be(\"SHOW MEASUREMENTS WHERE \\\"app\\\" = 'email' LIMIT 100\");\n"
],
"file_path": "public/app/plugins/datasource/influxdb/specs/query_builder_specs.ts",
"type": "replace",
"edit_start_line_idx": 60
} | ` foo` | vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-648 | 0 | https://github.com/grafana/grafana/commit/c485fed74454f1b07b8f5c967da26849aa0bc7a0 | [
0.0001687169133219868,
0.0001687169133219868,
0.0001687169133219868,
0.0001687169133219868,
0
] |
{
"id": 0,
"code_window": [
" t.identifier(asyncFnId.name),\n",
" t.callExpression(container, [])\n",
" )\n",
" ]);\n",
"\n",
" retFunction.id = asyncFnId;\n",
" path.replaceWith(declar);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" declar._blockHoist = true;\n"
],
"file_path": "packages/babel-helper-remap-async-to-generator/src/index.js",
"type": "add",
"edit_start_line_idx": 89
} | /* @flow */
import type { NodePath } from "babel-traverse";
import nameFunction from "babel-helper-function-name";
import template from "babel-template";
import * as t from "babel-types";
let buildWrapper = template(`
(function () {
var ref = FUNCTION;
return function (PARAMS) {
return ref.apply(this, arguments);
};
})
`);
let arrowBuildWrapper = template(`
(() => {
var ref = FUNCTION, _this = this;
return function(PARAMS) {
return ref.apply(_this, arguments);
};
})
`);
let awaitVisitor = {
ArrowFunctionExpression(path) {
if (!path.node.async) {
path.arrowFunctionToShadowed();
}
},
AwaitExpression({ node }) {
node.type = "YieldExpression";
}
};
function classOrObjectMethod(path: NodePath, callId: Object) {
let node = path.node;
let body = node.body;
node.async = false;
let container = t.functionExpression(null, [], t.blockStatement(body.body), true);
container.shadow = true;
body.body = [
t.returnStatement(t.callExpression(
t.callExpression(callId, [container]),
[]
))
];
}
function plainFunction(path: NodePath, callId: Object) {
let node = path.node;
let wrapper = buildWrapper;
if (path.isArrowFunctionExpression()) {
path.arrowFunctionToShadowed();
wrapper = arrowBuildWrapper;
}
node.async = false;
node.generator = true;
let asyncFnId = node.id;
node.id = null;
let isDeclaration = path.isFunctionDeclaration();
if (isDeclaration) {
node.type = "FunctionExpression";
}
let built = t.callExpression(callId, [node]);
let container = wrapper({
FUNCTION: built,
PARAMS: node.params.map(() => path.scope.generateUidIdentifier("x"))
}).expression;
let retFunction = container.body.body[1].argument;
if (isDeclaration) {
let declar = t.variableDeclaration("let", [
t.variableDeclarator(
t.identifier(asyncFnId.name),
t.callExpression(container, [])
)
]);
retFunction.id = asyncFnId;
path.replaceWith(declar);
} else {
if (asyncFnId && asyncFnId.name) {
retFunction.id = asyncFnId;
} else {
nameFunction({
node: retFunction,
parent: path.parent,
scope: path.scope
});
}
if (retFunction.id || node.params.length) {
// we have an inferred function id or params so we need this wrapper
path.replaceWith(t.callExpression(container, []));
} else {
// we can omit this wrapper as the conditions it protects for do not apply
path.replaceWith(built);
}
}
}
export default function (path: NodePath, callId: Object) {
let node = path.node;
if (node.generator) return;
path.traverse(awaitVisitor);
if (path.isClassMethod() || path.isObjectMethod()) {
return classOrObjectMethod(path, callId);
} else {
return plainFunction(path, callId);
}
}
| packages/babel-helper-remap-async-to-generator/src/index.js | 1 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.9898936152458191,
0.0790611207485199,
0.0001654794323258102,
0.002085675485432148,
0.26295825839042664
] |
{
"id": 0,
"code_window": [
" t.identifier(asyncFnId.name),\n",
" t.callExpression(container, [])\n",
" )\n",
" ]);\n",
"\n",
" retFunction.id = asyncFnId;\n",
" path.replaceWith(declar);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" declar._blockHoist = true;\n"
],
"file_path": "packages/babel-helper-remap-async-to-generator/src/index.js",
"type": "add",
"edit_start_line_idx": 89
} | a **= 2; | packages/babylon/test/fixtures/experimental/uncategorised/3/actual.js | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.0001750575320329517,
0.0001750575320329517,
0.0001750575320329517,
0.0001750575320329517,
0
] |
{
"id": 0,
"code_window": [
" t.identifier(asyncFnId.name),\n",
" t.callExpression(container, [])\n",
" )\n",
" ]);\n",
"\n",
" retFunction.id = asyncFnId;\n",
" path.replaceWith(declar);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" declar._blockHoist = true;\n"
],
"file_path": "packages/babel-helper-remap-async-to-generator/src/index.js",
"type": "add",
"edit_start_line_idx": 89
} | var generate = require("../lib");
var assert = require("assert");
var parse = require("babylon").parse;
var chai = require("chai");
var t = require("babel-types");
var _ = require("lodash");
suite("generation", function () {
test("completeness", function () {
_.each(t.VISITOR_KEYS, function (keys, type) {
assert.ok(!!generate.CodeGenerator.prototype[type], type + " should exist");
});
_.each(generate.CodeGenerator.prototype, function (fn, type) {
if (!/[A-Z]/.test(type[0])) return;
assert.ok(t.VISITOR_KEYS[type], type + " should not exist");
});
});
});
suite("programmatic generation", function() {
test("numeric member expression", function() {
// Should not generate `0.foo`
var mem = t.memberExpression(t.numericLiteral(60702), t.identifier("foo"));
new Function(generate.default(mem).code);
});
test("nested if statements needs block", function() {
var ifStatement = t.ifStatement(
t.stringLiteral("top cond"),
t.whileStatement(
t.stringLiteral("while cond"),
t.ifStatement(
t.stringLiteral("nested"),
t.expressionStatement(t.numericLiteral(1))
)
),
t.expressionStatement(t.stringLiteral("alt"))
);
var ast = parse(generate.default(ifStatement).code);
assert.equal(ast.program.body[0].consequent.type, 'BlockStatement');
});
});
var suites = require("babel-helper-fixtures").default(__dirname + "/fixtures");
suites.forEach(function (testSuite) {
suite("generation/" + testSuite.title, function () {
_.each(testSuite.tests, function (task) {
test(task.title, !task.disabled && function () {
var expect = task.expect;
var actual = task.actual;
var actualAst = parse(actual.code, {
filename: actual.loc,
plugins: [
"jsx",
"flow",
"decorators",
"asyncFunctions",
"exportExtensions",
"functionBind",
"classConstructorCall",
],
strictMode: false,
sourceType: "module",
});
var actualCode = generate.default(actualAst, task.options, actual.code).code;
chai.expect(actualCode).to.equal(expect.code, actual.loc + " !== " + expect.loc);
});
});
});
});
| packages/babel-generator/test/index.js | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.0011116580571979284,
0.0002899636747315526,
0.00016761421284172684,
0.0001739884610287845,
0.0003105885989498347
] |
{
"id": 0,
"code_window": [
" t.identifier(asyncFnId.name),\n",
" t.callExpression(container, [])\n",
" )\n",
" ]);\n",
"\n",
" retFunction.id = asyncFnId;\n",
" path.replaceWith(declar);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" declar._blockHoist = true;\n"
],
"file_path": "packages/babel-helper-remap-async-to-generator/src/index.js",
"type": "add",
"edit_start_line_idx": 89
} | {
"type": "File",
"start": 0,
"end": 1,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
}
},
"program": {
"type": "Program",
"start": 0,
"end": 1,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
}
},
"sourceType": "script",
"body": [
{
"type": "ExpressionStatement",
"start": 0,
"end": 1,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
}
},
"expression": {
"type": "Identifier",
"start": 0,
"end": 1,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 1
}
},
"name": "x"
}
}
]
}
} | packages/babylon/test/fixtures/core/uncategorised/224/expected.json | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.00017637896235100925,
0.00017308813403360546,
0.0001686080649960786,
0.00017295654106419533,
0.0000023304585283767665
] |
{
"id": 1,
"code_window": [
"function normalFunction() {}\n",
"\n",
"async function foo() {\n",
" var wat = await bar();\n",
"}"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/actual.js",
"type": "replace",
"edit_start_line_idx": 0
} | /* @flow */
import type { NodePath } from "babel-traverse";
import nameFunction from "babel-helper-function-name";
import template from "babel-template";
import * as t from "babel-types";
let buildWrapper = template(`
(function () {
var ref = FUNCTION;
return function (PARAMS) {
return ref.apply(this, arguments);
};
})
`);
let arrowBuildWrapper = template(`
(() => {
var ref = FUNCTION, _this = this;
return function(PARAMS) {
return ref.apply(_this, arguments);
};
})
`);
let awaitVisitor = {
ArrowFunctionExpression(path) {
if (!path.node.async) {
path.arrowFunctionToShadowed();
}
},
AwaitExpression({ node }) {
node.type = "YieldExpression";
}
};
function classOrObjectMethod(path: NodePath, callId: Object) {
let node = path.node;
let body = node.body;
node.async = false;
let container = t.functionExpression(null, [], t.blockStatement(body.body), true);
container.shadow = true;
body.body = [
t.returnStatement(t.callExpression(
t.callExpression(callId, [container]),
[]
))
];
}
function plainFunction(path: NodePath, callId: Object) {
let node = path.node;
let wrapper = buildWrapper;
if (path.isArrowFunctionExpression()) {
path.arrowFunctionToShadowed();
wrapper = arrowBuildWrapper;
}
node.async = false;
node.generator = true;
let asyncFnId = node.id;
node.id = null;
let isDeclaration = path.isFunctionDeclaration();
if (isDeclaration) {
node.type = "FunctionExpression";
}
let built = t.callExpression(callId, [node]);
let container = wrapper({
FUNCTION: built,
PARAMS: node.params.map(() => path.scope.generateUidIdentifier("x"))
}).expression;
let retFunction = container.body.body[1].argument;
if (isDeclaration) {
let declar = t.variableDeclaration("let", [
t.variableDeclarator(
t.identifier(asyncFnId.name),
t.callExpression(container, [])
)
]);
retFunction.id = asyncFnId;
path.replaceWith(declar);
} else {
if (asyncFnId && asyncFnId.name) {
retFunction.id = asyncFnId;
} else {
nameFunction({
node: retFunction,
parent: path.parent,
scope: path.scope
});
}
if (retFunction.id || node.params.length) {
// we have an inferred function id or params so we need this wrapper
path.replaceWith(t.callExpression(container, []));
} else {
// we can omit this wrapper as the conditions it protects for do not apply
path.replaceWith(built);
}
}
}
export default function (path: NodePath, callId: Object) {
let node = path.node;
if (node.generator) return;
path.traverse(awaitVisitor);
if (path.isClassMethod() || path.isObjectMethod()) {
return classOrObjectMethod(path, callId);
} else {
return plainFunction(path, callId);
}
}
| packages/babel-helper-remap-async-to-generator/src/index.js | 1 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.0005302809877321124,
0.00024390031467191875,
0.0001665031595621258,
0.00019999650248792022,
0.0001103296090150252
] |
{
"id": 1,
"code_window": [
"function normalFunction() {}\n",
"\n",
"async function foo() {\n",
" var wat = await bar();\n",
"}"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/actual.js",
"type": "replace",
"edit_start_line_idx": 0
} | {
"throws": "Identifier directly after number (1:1)"
} | packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0008/options.json | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.0001764425542205572,
0.0001764425542205572,
0.0001764425542205572,
0.0001764425542205572,
0
] |
{
"id": 1,
"code_window": [
"function normalFunction() {}\n",
"\n",
"async function foo() {\n",
" var wat = await bar();\n",
"}"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/actual.js",
"type": "replace",
"edit_start_line_idx": 0
} | node_modules
*.log
src
test
| packages/babel-plugin-transform-react-constant-elements/.npmignore | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.00017624245083425194,
0.00017624245083425194,
0.00017624245083425194,
0.00017624245083425194,
0
] |
{
"id": 1,
"code_window": [
"function normalFunction() {}\n",
"\n",
"async function foo() {\n",
" var wat = await bar();\n",
"}"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/actual.js",
"type": "replace",
"edit_start_line_idx": 0
} | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _default() {
return function () {
function Select() {
babelHelpers.classCallCheck(this, Select);
}
babelHelpers.createClass(Select, [{
key: "query",
value: function query(_query) {}
}]);
return Select;
}();
}
exports.default = _default;
| packages/babel-plugin-transform-es2015-classes/test/fixtures/regression/T6750/expected.js | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.0001740193838486448,
0.00017136188398580998,
0.00016870438412297517,
0.00017136188398580998,
0.000002657499862834811
] |
{
"id": 2,
"code_window": [
"function normalFunction() {}\n",
"\n",
"let foo = function () {\n",
" var ref = babelHelpers.asyncToGenerator(function* () {\n",
" var wat = yield bar();\n"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/expected.js",
"type": "replace",
"edit_start_line_idx": 0
} | /* @flow */
import type { NodePath } from "babel-traverse";
import nameFunction from "babel-helper-function-name";
import template from "babel-template";
import * as t from "babel-types";
let buildWrapper = template(`
(function () {
var ref = FUNCTION;
return function (PARAMS) {
return ref.apply(this, arguments);
};
})
`);
let arrowBuildWrapper = template(`
(() => {
var ref = FUNCTION, _this = this;
return function(PARAMS) {
return ref.apply(_this, arguments);
};
})
`);
let awaitVisitor = {
ArrowFunctionExpression(path) {
if (!path.node.async) {
path.arrowFunctionToShadowed();
}
},
AwaitExpression({ node }) {
node.type = "YieldExpression";
}
};
function classOrObjectMethod(path: NodePath, callId: Object) {
let node = path.node;
let body = node.body;
node.async = false;
let container = t.functionExpression(null, [], t.blockStatement(body.body), true);
container.shadow = true;
body.body = [
t.returnStatement(t.callExpression(
t.callExpression(callId, [container]),
[]
))
];
}
function plainFunction(path: NodePath, callId: Object) {
let node = path.node;
let wrapper = buildWrapper;
if (path.isArrowFunctionExpression()) {
path.arrowFunctionToShadowed();
wrapper = arrowBuildWrapper;
}
node.async = false;
node.generator = true;
let asyncFnId = node.id;
node.id = null;
let isDeclaration = path.isFunctionDeclaration();
if (isDeclaration) {
node.type = "FunctionExpression";
}
let built = t.callExpression(callId, [node]);
let container = wrapper({
FUNCTION: built,
PARAMS: node.params.map(() => path.scope.generateUidIdentifier("x"))
}).expression;
let retFunction = container.body.body[1].argument;
if (isDeclaration) {
let declar = t.variableDeclaration("let", [
t.variableDeclarator(
t.identifier(asyncFnId.name),
t.callExpression(container, [])
)
]);
retFunction.id = asyncFnId;
path.replaceWith(declar);
} else {
if (asyncFnId && asyncFnId.name) {
retFunction.id = asyncFnId;
} else {
nameFunction({
node: retFunction,
parent: path.parent,
scope: path.scope
});
}
if (retFunction.id || node.params.length) {
// we have an inferred function id or params so we need this wrapper
path.replaceWith(t.callExpression(container, []));
} else {
// we can omit this wrapper as the conditions it protects for do not apply
path.replaceWith(built);
}
}
}
export default function (path: NodePath, callId: Object) {
let node = path.node;
if (node.generator) return;
path.traverse(awaitVisitor);
if (path.isClassMethod() || path.isObjectMethod()) {
return classOrObjectMethod(path, callId);
} else {
return plainFunction(path, callId);
}
}
| packages/babel-helper-remap-async-to-generator/src/index.js | 1 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.995794415473938,
0.1573733389377594,
0.00016320912982337177,
0.00031818210845813155,
0.35711923241615295
] |
{
"id": 2,
"code_window": [
"function normalFunction() {}\n",
"\n",
"let foo = function () {\n",
" var ref = babelHelpers.asyncToGenerator(function* () {\n",
" var wat = yield bar();\n"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/expected.js",
"type": "replace",
"edit_start_line_idx": 0
} | {
"throws": "Binding eval in strict mode (1:44)"
} | packages/babylon/test/fixtures/harmony/uncategorised/227/options.json | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.00016710229101590812,
0.00016710229101590812,
0.00016710229101590812,
0.00016710229101590812,
0
] |
{
"id": 2,
"code_window": [
"function normalFunction() {}\n",
"\n",
"let foo = function () {\n",
" var ref = babelHelpers.asyncToGenerator(function* () {\n",
" var wat = yield bar();\n"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/expected.js",
"type": "replace",
"edit_start_line_idx": 0
} | --1 | packages/babylon/test/fixtures/core/uncategorised/373/actual.js | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.00017581899010110646,
0.00017581899010110646,
0.00017581899010110646,
0.00017581899010110646,
0
] |
{
"id": 2,
"code_window": [
"function normalFunction() {}\n",
"\n",
"let foo = function () {\n",
" var ref = babelHelpers.asyncToGenerator(function* () {\n",
" var wat = yield bar();\n"
],
"labels": [
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-plugin-transform-async-to-generator/test/fixtures/async-to-generator/statement/expected.js",
"type": "replace",
"edit_start_line_idx": 0
} | export function f(...args) {
return args;
}
| packages/babel-preset-es2015/test/fixtures/traceur/TemplateLiterals/resources/f.js | 0 | https://github.com/babel/babel/commit/ec61bd9386c86fc4006e121b9ad6bdc9b7b2c8f0 | [
0.00016854729619808495,
0.00016854729619808495,
0.00016854729619808495,
0.00016854729619808495,
0
] |
{
"id": 0,
"code_window": [
" showLongToast() {\n",
" const toast = this.toastCtrl.create({\n",
" message: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea voluptatibus quibusdam eum nihil optio, ullam accusamus magni, nobis suscipit reprehenderit, sequi quam amet impedit. Accusamus dolorem voluptates laborum dolor obcaecati.',\n",
" duration: 5000\n",
" });\n",
"\n",
" toast.onDidDismiss(this.dismissHandler);\n",
" toast.present();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" duration: 5000,\n",
" cssClass: 'custom-class my-toast'\n"
],
"file_path": "src/components/toast/test/basic/index.ts",
"type": "replace",
"edit_start_line_idx": 49
} | import { AfterViewInit, Component, ElementRef, Renderer } from '@angular/core';
import { NgIf } from '@angular/common';
import { Animation } from '../../animations/animation';
import { Config } from '../../config/config';
import { isPresent } from '../../util/util';
import { NavParams } from '../nav/nav-params';
import { Transition, TransitionOptions } from '../../transitions/transition';
import { ViewController } from '../nav/view-controller';
/**
* @private
*/
@Component({
selector: 'ion-toast',
template: `
<div class="toast-wrapper"
[class.toast-bottom]="d.position === 'bottom'"
[class.toast-middle]="d.position === 'middle'"
[class.toast-top]="d.position === 'top'">
<div class="toast-container">
<div class="toast-message" id="{{hdrId}}" *ngIf="d.message">{{d.message}}</div>
<button clear class="toast-button" *ngIf="d.showCloseButton" (click)="cbClick()">
{{ d.closeButtonText || 'Close' }}
</button>
</div>
</div>
`,
directives: [NgIf],
host: {
'role': 'dialog',
'[attr.aria-labelledby]': 'hdrId',
'[attr.aria-describedby]': 'descId',
},
})
export class ToastCmp implements AfterViewInit {
private d: any;
private descId: string;
private dismissTimeout: number = undefined;
private enabled: boolean;
private hdrId: string;
private id: number;
constructor(
private _viewCtrl: ViewController,
private _config: Config,
private _elementRef: ElementRef,
params: NavParams,
renderer: Renderer
) {
this.d = params.data;
if (this.d.cssClass) {
renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);
}
this.id = (++toastIds);
if (this.d.message) {
this.hdrId = 'toast-hdr-' + this.id;
}
}
ngAfterViewInit() {
// if there's a `duration` set, automatically dismiss.
if (this.d.duration) {
this.dismissTimeout =
setTimeout(() => {
this.dismiss('backdrop');
}, this.d.duration);
}
this.enabled = true;
}
ionViewDidEnter() {
const { activeElement }: any = document;
if (activeElement) {
activeElement.blur();
}
let focusableEle = this._elementRef.nativeElement.querySelector('button');
if (focusableEle) {
focusableEle.focus();
}
}
cbClick() {
if (this.enabled) {
this.dismiss('close');
}
}
dismiss(role: any): Promise<any> {
clearTimeout(this.dismissTimeout);
this.dismissTimeout = undefined;
return this._viewCtrl.dismiss(null, role);
}
}
class ToastSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM READS
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = <HTMLElement> ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
// by default, it is -100% hidden (above the screen)
// so move from that to 10px below top: 0px;
wrapper.fromTo('translateY', '-100%', `${10}px`);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
} else {
// bottom
// by default, it is 100% hidden (below the screen),
// so move from that to 10 px above bottom: 0px
wrapper.fromTo('translateY', '100%', `${0 - 10}px`);
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(wrapper);
}
}
class ToastSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = <HTMLElement> ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${10}px`, '-100%');
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0 - 10}px`, '100%');
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(300).add(wrapper);
}
}
class ToastMdSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM reads
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
// by default, it is -100% hidden (above the screen)
// so move from that to top: 0px;
wrapper.fromTo('translateY', '-100%', `0%`);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
} else {
// bottom
// by default, it is 100% hidden (below the screen),
// so move from that to bottom: 0px
wrapper.fromTo('translateY', '100%', `0%`);
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(wrapper);
}
}
class ToastMdSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0}%`, '-100%');
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0}%`, '100%');
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(wrapper);
}
}
class ToastWpPopIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
} else {
// bottom
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
}
this.easing('cubic-bezier(0,0 0.05,1)').duration(200).add(wrapper);
}
}
class ToastWpPopOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM reads
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
}
// DOM writes
const EASE: string = 'ease-out';
const DURATION: number = 150;
this.easing(EASE).duration(DURATION).add(wrapper);
}
}
Transition.register('toast-slide-in', ToastSlideIn);
Transition.register('toast-slide-out', ToastSlideOut);
Transition.register('toast-md-slide-in', ToastMdSlideIn);
Transition.register('toast-md-slide-out', ToastMdSlideOut);
Transition.register('toast-wp-slide-out', ToastWpPopOut);
Transition.register('toast-wp-slide-in', ToastWpPopIn);
let toastIds = -1;
const TOAST_POSITION_TOP = 'top';
const TOAST_POSITION_MIDDLE = 'middle';
const TOAST_POSITION_BOTTOM = 'bottom';
| src/components/toast/toast-component.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.0014938880922272801,
0.00024409109028056264,
0.00016133290773723274,
0.00017036111967172474,
0.0002662304905243218
] |
{
"id": 0,
"code_window": [
" showLongToast() {\n",
" const toast = this.toastCtrl.create({\n",
" message: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea voluptatibus quibusdam eum nihil optio, ullam accusamus magni, nobis suscipit reprehenderit, sequi quam amet impedit. Accusamus dolorem voluptates laborum dolor obcaecati.',\n",
" duration: 5000\n",
" });\n",
"\n",
" toast.onDidDismiss(this.dismissHandler);\n",
" toast.present();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" duration: 5000,\n",
" cssClass: 'custom-class my-toast'\n"
],
"file_path": "src/components/toast/test/basic/index.ts",
"type": "replace",
"edit_start_line_idx": 49
} | src/components/range/test/basic/e2e.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00016584762488491833,
0.00016584762488491833,
0.00016584762488491833,
0.00016584762488491833,
0
] |
|
{
"id": 0,
"code_window": [
" showLongToast() {\n",
" const toast = this.toastCtrl.create({\n",
" message: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea voluptatibus quibusdam eum nihil optio, ullam accusamus magni, nobis suscipit reprehenderit, sequi quam amet impedit. Accusamus dolorem voluptates laborum dolor obcaecati.',\n",
" duration: 5000\n",
" });\n",
"\n",
" toast.onDidDismiss(this.dismissHandler);\n",
" toast.present();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" duration: 5000,\n",
" cssClass: 'custom-class my-toast'\n"
],
"file_path": "src/components/toast/test/basic/index.ts",
"type": "replace",
"edit_start_line_idx": 49
} | import { Component } from '@angular/core';
import { ionicBootstrap } from 'ionic-angular';
@Component({
templateUrl: 'main.html'
})
class ApiDemoPage {}
@Component({
template: '<ion-nav [root]="root"></ion-nav>'
})
class ApiDemoApp {
root = ApiDemoPage;
}
ionicBootstrap(ApiDemoApp);
| demos/button/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00018735173216555268,
0.00017662206664681435,
0.00016589240112807602,
0.00017662206664681435,
0.00001072966551873833
] |
{
"id": 0,
"code_window": [
" showLongToast() {\n",
" const toast = this.toastCtrl.create({\n",
" message: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea voluptatibus quibusdam eum nihil optio, ullam accusamus magni, nobis suscipit reprehenderit, sequi quam amet impedit. Accusamus dolorem voluptates laborum dolor obcaecati.',\n",
" duration: 5000\n",
" });\n",
"\n",
" toast.onDidDismiss(this.dismissHandler);\n",
" toast.present();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" duration: 5000,\n",
" cssClass: 'custom-class my-toast'\n"
],
"file_path": "src/components/toast/test/basic/index.ts",
"type": "replace",
"edit_start_line_idx": 49
} | import { ComponentResolver, Directive, ElementRef, forwardRef, Inject, NgZone, Optional, Renderer, ViewContainerRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { GestureController } from '../../gestures/gesture-controller';
import { Keyboard } from '../../util/keyboard';
import { NavControllerBase } from '../nav/nav-controller-base';
/**
* @private
*/
@Directive({
selector: '[nav-portal]'
})
export class NavPortal extends NavControllerBase {
constructor(
@Inject(forwardRef(() => App)) app: App,
config: Config,
keyboard: Keyboard,
elementRef: ElementRef,
zone: NgZone,
renderer: Renderer,
compiler: ComponentResolver,
gestureCtrl: GestureController,
viewPort: ViewContainerRef
) {
super(null, app, config, keyboard, elementRef, zone, renderer, compiler, gestureCtrl);
this._isPortal = true;
this._init = true;
this.setViewport(viewPort);
app.setPortal(this);
// on every page change make sure the portal has
// dismissed any views that should be auto dismissed on page change
app.viewDidLeave.subscribe(this.dismissPageChangeViews.bind(this));
}
}
| src/components/nav/nav-portal.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00020269665401428938,
0.00017989503976423293,
0.00017203466268256307,
0.00017242442118003964,
0.00001316704583587125
] |
{
"id": 1,
"code_window": [
" },\n",
"})\n",
"export class ToastCmp implements AfterViewInit {\n",
" private d: any;\n",
" private descId: string;\n",
" private dismissTimeout: number = undefined;\n",
" private enabled: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" private d: {\n",
" message?: string;\n",
" cssClass?: string;\n",
" duration?: number;\n",
" showCloseButton?: boolean;\n",
" closeButtonText?: string;\n",
" dismissOnPageChange?: boolean;\n",
" position?: string;\n",
" };\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { AfterViewInit, Component, ElementRef, Renderer } from '@angular/core';
import { NgIf } from '@angular/common';
import { Animation } from '../../animations/animation';
import { Config } from '../../config/config';
import { isPresent } from '../../util/util';
import { NavParams } from '../nav/nav-params';
import { Transition, TransitionOptions } from '../../transitions/transition';
import { ViewController } from '../nav/view-controller';
/**
* @private
*/
@Component({
selector: 'ion-toast',
template: `
<div class="toast-wrapper"
[class.toast-bottom]="d.position === 'bottom'"
[class.toast-middle]="d.position === 'middle'"
[class.toast-top]="d.position === 'top'">
<div class="toast-container">
<div class="toast-message" id="{{hdrId}}" *ngIf="d.message">{{d.message}}</div>
<button clear class="toast-button" *ngIf="d.showCloseButton" (click)="cbClick()">
{{ d.closeButtonText || 'Close' }}
</button>
</div>
</div>
`,
directives: [NgIf],
host: {
'role': 'dialog',
'[attr.aria-labelledby]': 'hdrId',
'[attr.aria-describedby]': 'descId',
},
})
export class ToastCmp implements AfterViewInit {
private d: any;
private descId: string;
private dismissTimeout: number = undefined;
private enabled: boolean;
private hdrId: string;
private id: number;
constructor(
private _viewCtrl: ViewController,
private _config: Config,
private _elementRef: ElementRef,
params: NavParams,
renderer: Renderer
) {
this.d = params.data;
if (this.d.cssClass) {
renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);
}
this.id = (++toastIds);
if (this.d.message) {
this.hdrId = 'toast-hdr-' + this.id;
}
}
ngAfterViewInit() {
// if there's a `duration` set, automatically dismiss.
if (this.d.duration) {
this.dismissTimeout =
setTimeout(() => {
this.dismiss('backdrop');
}, this.d.duration);
}
this.enabled = true;
}
ionViewDidEnter() {
const { activeElement }: any = document;
if (activeElement) {
activeElement.blur();
}
let focusableEle = this._elementRef.nativeElement.querySelector('button');
if (focusableEle) {
focusableEle.focus();
}
}
cbClick() {
if (this.enabled) {
this.dismiss('close');
}
}
dismiss(role: any): Promise<any> {
clearTimeout(this.dismissTimeout);
this.dismissTimeout = undefined;
return this._viewCtrl.dismiss(null, role);
}
}
class ToastSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM READS
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = <HTMLElement> ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
// by default, it is -100% hidden (above the screen)
// so move from that to 10px below top: 0px;
wrapper.fromTo('translateY', '-100%', `${10}px`);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
} else {
// bottom
// by default, it is 100% hidden (below the screen),
// so move from that to 10 px above bottom: 0px
wrapper.fromTo('translateY', '100%', `${0 - 10}px`);
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(wrapper);
}
}
class ToastSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = <HTMLElement> ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${10}px`, '-100%');
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0 - 10}px`, '100%');
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(300).add(wrapper);
}
}
class ToastMdSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM reads
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
// by default, it is -100% hidden (above the screen)
// so move from that to top: 0px;
wrapper.fromTo('translateY', '-100%', `0%`);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
} else {
// bottom
// by default, it is 100% hidden (below the screen),
// so move from that to bottom: 0px
wrapper.fromTo('translateY', '100%', `0%`);
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(wrapper);
}
}
class ToastMdSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0}%`, '-100%');
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0}%`, '100%');
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(wrapper);
}
}
class ToastWpPopIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
} else {
// bottom
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
}
this.easing('cubic-bezier(0,0 0.05,1)').duration(200).add(wrapper);
}
}
class ToastWpPopOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM reads
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
}
// DOM writes
const EASE: string = 'ease-out';
const DURATION: number = 150;
this.easing(EASE).duration(DURATION).add(wrapper);
}
}
Transition.register('toast-slide-in', ToastSlideIn);
Transition.register('toast-slide-out', ToastSlideOut);
Transition.register('toast-md-slide-in', ToastMdSlideIn);
Transition.register('toast-md-slide-out', ToastMdSlideOut);
Transition.register('toast-wp-slide-out', ToastWpPopOut);
Transition.register('toast-wp-slide-in', ToastWpPopIn);
let toastIds = -1;
const TOAST_POSITION_TOP = 'top';
const TOAST_POSITION_MIDDLE = 'middle';
const TOAST_POSITION_BOTTOM = 'bottom';
| src/components/toast/toast-component.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.9976035952568054,
0.0344848558306694,
0.00016547249106224626,
0.0002686723310034722,
0.17600056529045105
] |
{
"id": 1,
"code_window": [
" },\n",
"})\n",
"export class ToastCmp implements AfterViewInit {\n",
" private d: any;\n",
" private descId: string;\n",
" private dismissTimeout: number = undefined;\n",
" private enabled: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" private d: {\n",
" message?: string;\n",
" cssClass?: string;\n",
" duration?: number;\n",
" showCloseButton?: boolean;\n",
" closeButtonText?: string;\n",
" dismissOnPageChange?: boolean;\n",
" position?: string;\n",
" };\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ionicBootstrap, Toggle } from '../../../../../src';
@Component({
templateUrl: 'main.html'
})
class E2EPage {
fruitsForm: FormGroup;
grapeDisabled: boolean;
grapeChecked: boolean;
kiwiValue: boolean;
strawberryValue: boolean;
formResults: string;
constructor() {
this.fruitsForm = new FormGroup({
'appleCtrl': new FormControl(false),
'bananaCtrl': new FormControl(true),
'cherryCtrl': new FormControl(false),
'grapeCtrl': new FormControl(true)
});
this.grapeChecked = true;
this.grapeDisabled = true;
}
toggleGrapeChecked() {
this.grapeChecked = !this.grapeChecked;
}
toggleGrapeDisabled() {
this.grapeDisabled = !this.grapeDisabled;
}
appleChange(toggle: Toggle) {
console.log('appleChange', toggle);
}
bananaChange(toggle: Toggle) {
console.log('bananaChange', toggle);
}
kiwiChange(toggle: Toggle) {
console.log('kiwiChange', toggle);
this.kiwiValue = toggle.checked;
}
strawberryChange(toggle: Toggle) {
console.log('strawberryChange', toggle);
this.strawberryValue = toggle.checked;
}
doSubmit(ev: UIEvent) {
console.log('Submitting form', this.fruitsForm.value);
this.formResults = JSON.stringify(this.fruitsForm.value);
ev.preventDefault();
}
}
@Component({
template: '<ion-nav [root]="root"></ion-nav>'
})
class E2EApp {
root = E2EPage;
}
ionicBootstrap(E2EApp);
| src/components/toggle/test/basic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00017390839639119804,
0.0001704716560197994,
0.00016701468848623335,
0.00017067429143935442,
0.000002046267354671727
] |
{
"id": 1,
"code_window": [
" },\n",
"})\n",
"export class ToastCmp implements AfterViewInit {\n",
" private d: any;\n",
" private descId: string;\n",
" private dismissTimeout: number = undefined;\n",
" private enabled: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" private d: {\n",
" message?: string;\n",
" cssClass?: string;\n",
" duration?: number;\n",
" showCloseButton?: boolean;\n",
" closeButtonText?: string;\n",
" dismissOnPageChange?: boolean;\n",
" position?: string;\n",
" };\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 37
} |
// Item reorder
// --------------------------------------------------
ion-reorder {
display: none;
flex: 1;
align-items: center;
justify-content: center;
max-width: 40px;
height: 100%;
font-size: 1.45em;
opacity: .5;
pointer-events: all;
touch-action: manipulation;
ion-icon {
pointer-events: none;
}
}
.reorder-enabled {
.item,
.item-wrapper {
transition: transform 300ms;
will-change: transform;
}
ion-reorder {
display: flex;
}
}
.reorder-list-active {
.item-inner {
pointer-events: none;
}
}
.item-wrapper.reorder-active,
.item.reorder-active,
.reorder-active {
z-index: 4;
box-shadow: 0 0 10px rgba(0, 0, 0, .4);
opacity: .8;
transition: none;
pointer-events: none;
}
| src/components/item/item-reorder.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00017480681708548218,
0.0001724180910969153,
0.0001695191749604419,
0.00017234060214832425,
0.000001675679186519119
] |
{
"id": 1,
"code_window": [
" },\n",
"})\n",
"export class ToastCmp implements AfterViewInit {\n",
" private d: any;\n",
" private descId: string;\n",
" private dismissTimeout: number = undefined;\n",
" private enabled: boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" private d: {\n",
" message?: string;\n",
" cssClass?: string;\n",
" duration?: number;\n",
" showCloseButton?: boolean;\n",
" closeButtonText?: string;\n",
" dismissOnPageChange?: boolean;\n",
" position?: string;\n",
" };\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 37
} | <ion-content>
<button fab fab-left fab-top>
<ion-icon name="add"></ion-icon>
</button>
<button fab fab-center fab-top secondary>
<ion-icon name="add"></ion-icon>
</button>
<button fab fab-right fab-top danger>
<ion-icon name="add"></ion-icon>
</button>
<button fab fab-left fab-bottom light>
<ion-icon name="add"></ion-icon>
</button>
<button fab fab-center fab-bottom primary>
<ion-icon name="add"></ion-icon>
</button>
<button fab fab-right fab-bottom dark>
<ion-icon name="add"></ion-icon>
</button>
</ion-content>
| src/components/button/test/fab/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00017153409135062248,
0.00016869536193553358,
0.00016547547420486808,
0.00016907654935494065,
0.0000024880625915102428
] |
{
"id": 2,
"code_window": [
" this.d = params.data;\n",
"\n",
" if (this.d.cssClass) {\n",
" renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);\n",
" }\n",
"\n",
" this.id = (++toastIds);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.d.cssClass.split(' ').forEach(cssClass => {\n",
" // Make sure the class isn't whitespace, otherwise it throws exceptions\n",
" if (cssClass.trim() !== '') renderer.setElementClass(_elementRef.nativeElement, cssClass, true);\n",
" });\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 55
} | import { AfterViewInit, Component, ElementRef, Renderer } from '@angular/core';
import { NgIf } from '@angular/common';
import { Animation } from '../../animations/animation';
import { Config } from '../../config/config';
import { isPresent } from '../../util/util';
import { NavParams } from '../nav/nav-params';
import { Transition, TransitionOptions } from '../../transitions/transition';
import { ViewController } from '../nav/view-controller';
/**
* @private
*/
@Component({
selector: 'ion-toast',
template: `
<div class="toast-wrapper"
[class.toast-bottom]="d.position === 'bottom'"
[class.toast-middle]="d.position === 'middle'"
[class.toast-top]="d.position === 'top'">
<div class="toast-container">
<div class="toast-message" id="{{hdrId}}" *ngIf="d.message">{{d.message}}</div>
<button clear class="toast-button" *ngIf="d.showCloseButton" (click)="cbClick()">
{{ d.closeButtonText || 'Close' }}
</button>
</div>
</div>
`,
directives: [NgIf],
host: {
'role': 'dialog',
'[attr.aria-labelledby]': 'hdrId',
'[attr.aria-describedby]': 'descId',
},
})
export class ToastCmp implements AfterViewInit {
private d: any;
private descId: string;
private dismissTimeout: number = undefined;
private enabled: boolean;
private hdrId: string;
private id: number;
constructor(
private _viewCtrl: ViewController,
private _config: Config,
private _elementRef: ElementRef,
params: NavParams,
renderer: Renderer
) {
this.d = params.data;
if (this.d.cssClass) {
renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);
}
this.id = (++toastIds);
if (this.d.message) {
this.hdrId = 'toast-hdr-' + this.id;
}
}
ngAfterViewInit() {
// if there's a `duration` set, automatically dismiss.
if (this.d.duration) {
this.dismissTimeout =
setTimeout(() => {
this.dismiss('backdrop');
}, this.d.duration);
}
this.enabled = true;
}
ionViewDidEnter() {
const { activeElement }: any = document;
if (activeElement) {
activeElement.blur();
}
let focusableEle = this._elementRef.nativeElement.querySelector('button');
if (focusableEle) {
focusableEle.focus();
}
}
cbClick() {
if (this.enabled) {
this.dismiss('close');
}
}
dismiss(role: any): Promise<any> {
clearTimeout(this.dismissTimeout);
this.dismissTimeout = undefined;
return this._viewCtrl.dismiss(null, role);
}
}
class ToastSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM READS
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = <HTMLElement> ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
// by default, it is -100% hidden (above the screen)
// so move from that to 10px below top: 0px;
wrapper.fromTo('translateY', '-100%', `${10}px`);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
} else {
// bottom
// by default, it is 100% hidden (below the screen),
// so move from that to 10 px above bottom: 0px
wrapper.fromTo('translateY', '100%', `${0 - 10}px`);
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(wrapper);
}
}
class ToastSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = <HTMLElement> ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${10}px`, '-100%');
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0 - 10}px`, '100%');
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(300).add(wrapper);
}
}
class ToastMdSlideIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM reads
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
// by default, it is -100% hidden (above the screen)
// so move from that to top: 0px;
wrapper.fromTo('translateY', '-100%', `0%`);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
} else {
// bottom
// by default, it is 100% hidden (below the screen),
// so move from that to bottom: 0px
wrapper.fromTo('translateY', '100%', `0%`);
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(wrapper);
}
}
class ToastMdSlideOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0}%`, '-100%');
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('translateY', `${0}%`, '100%');
}
this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(wrapper);
}
}
class ToastWpPopIn extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
let ele = enteringView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (enteringView.data && enteringView.data.position === TOAST_POSITION_TOP) {
// top
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
} else if (enteringView.data && enteringView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just center it and fade it in
let topPosition = Math.floor(ele.clientHeight / 2 - wrapperEle.clientHeight / 2);
// DOM WRITE
wrapperEle.style.top = `${topPosition}px`;
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
} else {
// bottom
wrapper.fromTo('opacity', 0.01, 1);
wrapper.fromTo('scale', 1.3, 1);
}
this.easing('cubic-bezier(0,0 0.05,1)').duration(200).add(wrapper);
}
}
class ToastWpPopOut extends Transition {
constructor(enteringView: ViewController, leavingView: ViewController, opts: TransitionOptions) {
super(enteringView, leavingView, opts);
// DOM reads
let ele = leavingView.pageRef().nativeElement;
const wrapperEle = ele.querySelector('.toast-wrapper');
let wrapper = new Animation(wrapperEle);
if (leavingView.data && leavingView.data.position === TOAST_POSITION_TOP) {
// top
// reverse arguments from enter transition
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
} else if (leavingView.data && leavingView.data.position === TOAST_POSITION_MIDDLE) {
// Middle
// just fade it out
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
} else {
// bottom
// reverse arguments from enter transition
wrapper.fromTo('opacity', 0.99, 0);
wrapper.fromTo('scale', 1, 1.3);
}
// DOM writes
const EASE: string = 'ease-out';
const DURATION: number = 150;
this.easing(EASE).duration(DURATION).add(wrapper);
}
}
Transition.register('toast-slide-in', ToastSlideIn);
Transition.register('toast-slide-out', ToastSlideOut);
Transition.register('toast-md-slide-in', ToastMdSlideIn);
Transition.register('toast-md-slide-out', ToastMdSlideOut);
Transition.register('toast-wp-slide-out', ToastWpPopOut);
Transition.register('toast-wp-slide-in', ToastWpPopIn);
let toastIds = -1;
const TOAST_POSITION_TOP = 'top';
const TOAST_POSITION_MIDDLE = 'middle';
const TOAST_POSITION_BOTTOM = 'bottom';
| src/components/toast/toast-component.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.9980459213256836,
0.06073560193181038,
0.00016322608280461282,
0.0002759536437224597,
0.2298174798488617
] |
{
"id": 2,
"code_window": [
" this.d = params.data;\n",
"\n",
" if (this.d.cssClass) {\n",
" renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);\n",
" }\n",
"\n",
" this.id = (++toastIds);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.d.cssClass.split(' ').forEach(cssClass => {\n",
" // Make sure the class isn't whitespace, otherwise it throws exceptions\n",
" if (cssClass.trim() !== '') renderer.setElementClass(_elementRef.nativeElement, cssClass, true);\n",
" });\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 55
} | src/components/button/test/icons/e2e.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00017440725059714168,
0.00017440725059714168,
0.00017440725059714168,
0.00017440725059714168,
0
] |
|
{
"id": 2,
"code_window": [
" this.d = params.data;\n",
"\n",
" if (this.d.cssClass) {\n",
" renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);\n",
" }\n",
"\n",
" this.id = (++toastIds);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.d.cssClass.split(' ').forEach(cssClass => {\n",
" // Make sure the class isn't whitespace, otherwise it throws exceptions\n",
" if (cssClass.trim() !== '') renderer.setElementClass(_elementRef.nativeElement, cssClass, true);\n",
" });\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 55
} | <ion-header>
<ion-navbar>
<ion-title>Loading</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button block (click)="presentLoadingIos()">iOS Spinner</button>
<button block (click)="presentLoadingDots()">Dots Spinner</button>
<button block (click)="presentLoadingBubbles()">Bubbles Spinner</button>
<button block (click)="presentLoadingCircles()">Circles Spinner</button>
<button block (click)="presentLoadingCrescent()">Crescent Spinner</button>
<button block (click)="presentLoadingDefault()" secondary class="e2eLoadingDefaultSpinner">Default Spinner</button>
<button block (click)="presentLoadingCustom()" light>Custom Spinner</button>
<button block (click)="presentLoadingText()" dark>Content Only w/ Nav</button>
<button block (click)="presentLoadingMultiple()" danger>Multiple Loading</button>
<button block (click)="presentLoadingMultipleNav()" danger>Multiple Nav Loading</button>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-buttons end>
<button (click)="goToPage2()">
Navigate
<ion-icon name="arrow-forward"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-footer> | src/components/loading/test/basic/main.html | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.00017324257350992411,
0.00017025969282258302,
0.00016615628555882722,
0.00017081995611079037,
0.000002571248614913202
] |
{
"id": 2,
"code_window": [
" this.d = params.data;\n",
"\n",
" if (this.d.cssClass) {\n",
" renderer.setElementClass(_elementRef.nativeElement, this.d.cssClass, true);\n",
" }\n",
"\n",
" this.id = (++toastIds);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.d.cssClass.split(' ').forEach(cssClass => {\n",
" // Make sure the class isn't whitespace, otherwise it throws exceptions\n",
" if (cssClass.trim() !== '') renderer.setElementClass(_elementRef.nativeElement, cssClass, true);\n",
" });\n"
],
"file_path": "src/components/toast/toast-component.ts",
"type": "replace",
"edit_start_line_idx": 55
} | import { Directive, ElementRef, EventEmitter, HostListener, Output, Renderer } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Config } from '../../config/config';
import { CSS, hasFocus } from '../../util/dom';
/**
* @private
*/
@Directive({
selector: '.text-input'
})
export class NativeInput {
private _relocated: boolean;
private _clone: boolean;
private _blurring: boolean;
private _unrefBlur: Function;
@Output() focusChange: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output() valueChange: EventEmitter<string> = new EventEmitter<string>();
constructor(
private _elementRef: ElementRef,
private _renderer: Renderer,
config: Config,
public ngControl: NgControl
) {
this._clone = config.getBoolean('inputCloning', false);
this._blurring = config.getBoolean('inputBlurring', false);
}
@HostListener('input', ['$event'])
private _change(ev: any) {
this.valueChange.emit(ev.target.value);
}
@HostListener('focus')
private _focus() {
var self = this;
self.focusChange.emit(true);
function docTouchEnd(ev: TouchEvent) {
var tapped = <HTMLElement>ev.target;
if (tapped && self.element()) {
if (tapped.tagName !== 'INPUT' && tapped.tagName !== 'TEXTAREA' && !tapped.classList.contains('input-cover')) {
self.element().blur();
}
}
}
if (self._blurring) {
// automatically blur input if:
// 1) this input has focus
// 2) the newly tapped document element is not an input
console.debug('input blurring enabled');
document.addEventListener('touchend', docTouchEnd, true);
self._unrefBlur = function() {
console.debug('input blurring disabled');
document.removeEventListener('touchend', docTouchEnd, true);
};
}
}
@HostListener('blur')
private _blur() {
this.focusChange.emit(false);
this.hideFocus(false);
this._unrefBlur && this._unrefBlur();
this._unrefBlur = null;
}
labelledBy(val: string) {
this._renderer.setElementAttribute(this._elementRef.nativeElement, 'aria-labelledby', val);
}
isDisabled(val: boolean) {
this._renderer.setElementAttribute(this._elementRef.nativeElement, 'disabled', val ? '' : null);
}
setFocus() {
// let's set focus to the element
// but only if it does not already have focus
if (document.activeElement !== this.element()) {
this.element().focus();
}
}
beginFocus(shouldFocus: boolean, inputRelativeY: number) {
if (this._relocated !== shouldFocus) {
var focusedInputEle = this.element();
if (shouldFocus) {
// we should focus into this element
if (this._clone) {
// this platform needs the input to be cloned
// this allows for the actual input to receive the focus from
// the user's touch event, but before it receives focus, it
// moves the actual input to a location that will not screw
// up the app's layout, and does not allow the native browser
// to attempt to scroll the input into place (messing up headers/footers)
// the cloned input fills the area of where native input should be
// while the native input fakes out the browser by relocating itself
// before it receives the actual focus event
var clonedInputEle = cloneInput(focusedInputEle, 'cloned-focus');
focusedInputEle.parentNode.insertBefore(clonedInputEle, focusedInputEle);
// move the native input to a location safe to receive focus
// according to the browser, the native input receives focus in an
// area which doesn't require the browser to scroll the input into place
focusedInputEle.style[CSS.transform] = `translate3d(-9999px,${inputRelativeY}px,0)`;
focusedInputEle.style.opacity = '0';
}
// let's now set focus to the actual native element
// at this point it is safe to assume the browser will not attempt
// to scroll the input into view itself (screwing up headers/footers)
this.setFocus();
if (this._clone) {
focusedInputEle.classList.add('cloned-active');
}
} else {
// should remove the focus
if (this._clone) {
// should remove the cloned node
focusedInputEle.classList.remove('cloned-active');
focusedInputEle.style[CSS.transform] = '';
focusedInputEle.style.opacity = '';
removeClone(focusedInputEle, 'cloned-focus');
}
}
this._relocated = shouldFocus;
}
}
hideFocus(shouldHideFocus: boolean) {
let focusedInputEle = this.element();
console.debug(`native input hideFocus, shouldHideFocus: ${shouldHideFocus}, input value: ${focusedInputEle.value}`);
if (shouldHideFocus) {
let clonedInputEle = cloneInput(focusedInputEle, 'cloned-move');
focusedInputEle.classList.add('cloned-active');
focusedInputEle.parentNode.insertBefore(clonedInputEle, focusedInputEle);
} else {
focusedInputEle.classList.remove('cloned-active');
removeClone(focusedInputEle, 'cloned-move');
}
}
hasFocus(): boolean {
return hasFocus(this.element());
}
getValue(): string {
return this.element().value;
}
setCssClass(cssClass: string, shouldAdd: boolean) {
this._renderer.setElementClass(this._elementRef.nativeElement, cssClass, shouldAdd);
}
element(): HTMLInputElement {
return this._elementRef.nativeElement;
}
ngOnDestroy() {
this._unrefBlur && this._unrefBlur();
}
}
function cloneInput(focusedInputEle: any, addCssClass: string) {
let clonedInputEle = focusedInputEle.cloneNode(true);
clonedInputEle.classList.add('cloned-input');
clonedInputEle.classList.add(addCssClass);
clonedInputEle.setAttribute('aria-hidden', true);
clonedInputEle.removeAttribute('aria-labelledby');
clonedInputEle.tabIndex = -1;
clonedInputEle.style.width = (focusedInputEle.offsetWidth + 10) + 'px';
clonedInputEle.style.height = focusedInputEle.offsetHeight + 'px';
clonedInputEle.value = focusedInputEle.value;
return clonedInputEle;
}
function removeClone(focusedInputEle: any, queryCssClass: string) {
let clonedInputEle = focusedInputEle.parentElement.querySelector('.' + queryCssClass);
if (clonedInputEle) {
clonedInputEle.parentNode.removeChild(clonedInputEle);
}
}
/**
* @private
*/
@Directive({
selector: '[next-input]'
})
export class NextInput {
@Output() focused: EventEmitter<boolean> = new EventEmitter<boolean>();
@HostListener('focus')
receivedFocus() {
console.debug('native-input, next-input received focus');
this.focused.emit(true);
}
}
| src/components/input/native-input.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/79e25a342dde37ed264a1fcf3d40eef523383170 | [
0.0035291570238769054,
0.0006191930151544511,
0.00016465045337099582,
0.00017168311751447618,
0.0009824674343690276
] |
{
"id": 0,
"code_window": [
" modifiers: ?ASTModifiers\n",
"): ?boolean {\n",
" const type = el.attrsMap.type\n",
"\n",
" // warn if v-bind:value conflicts with v-model\n",
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // except for inputs with v-bind:type\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "add",
"edit_start_line_idx": 132
} | /* @flow */
import config from 'core/config'
import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'
import { genComponentModel, genAssignmentCode } from 'compiler/directives/model'
let warn
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
export const RANGE_TOKEN = '__r'
export const CHECKBOX_RADIO_TOKEN = '__c'
export default function model (
el: ASTElement,
dir: ASTDirective,
_warn: Function
): ?boolean {
warn = _warn
const value = dir.value
const modifiers = dir.modifiers
const tag = el.tag
const type = el.attrsMap.type
if (process.env.NODE_ENV !== 'production') {
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn(
`<${el.tag} v-model="${value}" type="file">:\n` +
`File inputs are read only. Use a v-on:change listener instead.`
)
}
}
if (el.component) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers)
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers)
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers)
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers)
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (process.env.NODE_ENV !== 'production') {
warn(
`<${el.tag} v-model="${value}">: ` +
`v-model is not supported on this element type. ` +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.'
)
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const valueBinding = getBindingAttr(el, 'value') || 'null'
const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'
const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'
addProp(el, 'checked',
`Array.isArray(${value})` +
`?_i(${value},${valueBinding})>-1` + (
trueValueBinding === 'true'
? `:(${value})`
: `:_q(${value},${trueValueBinding})`
)
)
addHandler(el, 'change',
`var $$a=${value},` +
'$$el=$event.target,' +
`$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +
'if(Array.isArray($$a)){' +
`var $$v=${number ? '_n(' + valueBinding + ')' : valueBinding},` +
'$$i=_i($$a,$$v);' +
`if($$el.checked){$$i<0&&(${value}=$$a.concat([$$v]))}` +
`else{$$i>-1&&(${value}=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}` +
`}else{${genAssignmentCode(value, '$$c')}}`,
null, true
)
}
function genRadioModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
let valueBinding = getBindingAttr(el, 'value') || 'null'
valueBinding = number ? `_n(${valueBinding})` : valueBinding
addProp(el, 'checked', `_q(${value},${valueBinding})`)
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)
}
function genSelect (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const selectedVal = `Array.prototype.filter` +
`.call($event.target.options,function(o){return o.selected})` +
`.map(function(o){var val = "_value" in o ? o._value : o.value;` +
`return ${number ? '_n(val)' : 'val'}})`
const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'
let code = `var $$selectedVal = ${selectedVal};`
code = `${code} ${genAssignmentCode(value, assignment)}`
addHandler(el, 'change', code, null, true)
}
function genDefaultModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
): ?boolean {
const type = el.attrsMap.type
// warn if v-bind:value conflicts with v-model
if (process.env.NODE_ENV !== 'production') {
const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']
if (value) {
const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'
warn(
`${binding}="${value}" conflicts with v-model on the same element ` +
'because the latter already expands to a value binding internally'
)
}
}
const { lazy, number, trim } = modifiers || {}
const needCompositionGuard = !lazy && type !== 'range'
const event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input'
let valueExpression = '$event.target.value'
if (trim) {
valueExpression = `$event.target.value.trim()`
}
if (number) {
valueExpression = `_n(${valueExpression})`
}
let code = genAssignmentCode(value, valueExpression)
if (needCompositionGuard) {
code = `if($event.target.composing)return;${code}`
}
addProp(el, 'value', `(${value})`)
addHandler(el, event, code, null, true)
if (trim || number) {
addHandler(el, 'blur', '$forceUpdate()')
}
}
| src/platforms/web/compiler/directives/model.js | 1 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.9978686571121216,
0.556354820728302,
0.00017379601194988936,
0.8513695001602173,
0.46498316526412964
] |
{
"id": 0,
"code_window": [
" modifiers: ?ASTModifiers\n",
"): ?boolean {\n",
" const type = el.attrsMap.type\n",
"\n",
" // warn if v-bind:value conflicts with v-model\n",
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // except for inputs with v-bind:type\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "add",
"edit_start_line_idx": 132
} | /* @flow */
import { extend, cached, camelize } from 'shared/util'
const normalize = cached(camelize)
function createStyle (oldVnode: VNodeWithData, vnode: VNodeWithData) {
if (!vnode.data.staticStyle) {
updateStyle(oldVnode, vnode)
return
}
const elm = vnode.elm
const staticStyle = vnode.data.staticStyle
const supportBatchUpdate = typeof elm.setStyles === 'function'
const batchedStyles = {}
for (const name in staticStyle) {
if (staticStyle[name]) {
supportBatchUpdate
? (batchedStyles[normalize(name)] = staticStyle[name])
: elm.setStyle(normalize(name), staticStyle[name])
}
}
if (supportBatchUpdate) {
elm.setStyles(batchedStyles)
}
updateStyle(oldVnode, vnode)
}
function updateStyle (oldVnode: VNodeWithData, vnode: VNodeWithData) {
if (!oldVnode.data.style && !vnode.data.style) {
return
}
let cur, name
const elm = vnode.elm
const oldStyle: any = oldVnode.data.style || {}
let style: any = vnode.data.style || {}
const needClone = style.__ob__
// handle array syntax
if (Array.isArray(style)) {
style = vnode.data.style = toObject(style)
}
// clone the style for future updates,
// in case the user mutates the style object in-place.
if (needClone) {
style = vnode.data.style = extend({}, style)
}
const supportBatchUpdate = typeof elm.setStyles === 'function'
const batchedStyles = {}
for (name in oldStyle) {
if (!style[name]) {
supportBatchUpdate
? (batchedStyles[normalize(name)] = '')
: elm.setStyle(normalize(name), '')
}
}
for (name in style) {
cur = style[name]
supportBatchUpdate
? (batchedStyles[normalize(name)] = cur)
: elm.setStyle(normalize(name), cur)
}
if (supportBatchUpdate) {
elm.setStyles(batchedStyles)
}
}
function toObject (arr) {
const res = {}
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i])
}
}
return res
}
export default {
create: createStyle,
update: updateStyle
}
| src/platforms/weex/runtime/modules/style.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.9903942942619324,
0.11020129919052124,
0.00016852092812769115,
0.0001755345583660528,
0.3111951947212219
] |
{
"id": 0,
"code_window": [
" modifiers: ?ASTModifiers\n",
"): ?boolean {\n",
" const type = el.attrsMap.type\n",
"\n",
" // warn if v-bind:value conflicts with v-model\n",
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // except for inputs with v-bind:type\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "add",
"edit_start_line_idx": 132
} | 'use strict'
const self = (global || root)
self.performance = {
now: function () {
var hrtime = process.hrtime()
return ((hrtime[0] * 1000000 + hrtime[1] / 1000) / 1000)
}
}
function generateGrid (rowCount, columnCount) {
var grid = []
for (var r = 0; r < rowCount; r++) {
var row = { id: r, items: [] }
for (var c = 0; c < columnCount; c++) {
row.items.push({ id: (r + '-' + c) })
}
grid.push(row)
}
return grid
}
const gridData = generateGrid(1000, 10)
module.exports = {
template: '<div><h1>{{ Math.random() }}</h1><my-table></my-table></div>',
components: {
myTable: {
data: function () {
return {
grid: gridData
}
},
// template: '<table><tr v-for="row in grid"><th>123</th><td v-for="item in row.items">{{ item.id }}</td></tr></table>',
template: '<table width="100%" cellspacing="2"><row v-for="row in grid" :row="row"></row></table>',
components: {
row: {
props: ['row'],
template: '<tr><th>{{ Math.random() }}</th><column v-for="item in row.items"></column></tr>',
components: {
column: {
template: '<td class="item">' +
// 25 plain elements for each cell
'<ul class="yoyo">' +
`<li v-for="i in 5" :class="'hihi' + i">` +
`<span :id="i + '_' + j" v-for="j in 5">fsefs</span>` +
'</li>' +
'</ul>' +
'</td>'
}
}
}
}
}
}
}
| benchmarks/ssr/common.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.00017518960521556437,
0.0001738202408887446,
0.00016999845684040338,
0.0001744486071402207,
0.000001788009399206203
] |
{
"id": 0,
"code_window": [
" modifiers: ?ASTModifiers\n",
"): ?boolean {\n",
" const type = el.attrsMap.type\n",
"\n",
" // warn if v-bind:value conflicts with v-model\n",
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" // except for inputs with v-bind:type\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "add",
"edit_start_line_idx": 132
} | /* @flow */
import config from '../config'
import { warn } from './debug'
import { nativeWatch } from './env'
import { set } from '../observer/index'
import {
ASSET_TYPES,
LIFECYCLE_HOOKS
} from 'shared/constants'
import {
extend,
hasOwn,
camelize,
toRawType,
capitalize,
isBuiltInTag,
isPlainObject
} from 'shared/util'
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
const strats = config.optionMergeStrategies
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
`option "${key}" can only be used during instance ` +
'creation with the `new` keyword.'
)
}
return defaultStrat(parent, child)
}
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to: Object, from: ?Object): Object {
if (!from) return to
let key, toVal, fromVal
const keys = Object.keys(from)
for (let i = 0; i < keys.length; i++) {
key = keys[i]
toVal = to[key]
fromVal = from[key]
if (!hasOwn(to, key)) {
set(to, key, fromVal)
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal)
}
}
return to
}
/**
* Data
*/
export function mergeDataOrFn (
parentVal: any,
childVal: any,
vm?: Component
): ?Function {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
typeof childVal === 'function' ? childVal.call(this, this) : childVal,
typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
)
}
} else {
return function mergedInstanceDataFn () {
// instance merge
const instanceData = typeof childVal === 'function'
? childVal.call(vm, vm)
: childVal
const defaultData = typeof parentVal === 'function'
? parentVal.call(vm, vm)
: parentVal
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
strats.data = function (
parentVal: any,
childVal: any,
vm?: Component
): ?Function {
if (!vm) {
if (childVal && typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
)
return parentVal
}
return mergeDataOrFn(parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
}
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal: ?Array<Function>,
childVal: ?Function | ?Array<Function>
): ?Array<Function> {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
LIFECYCLE_HOOKS.forEach(hook => {
strats[hook] = mergeHook
})
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (
parentVal: ?Object,
childVal: ?Object,
vm?: Component,
key: string
): Object {
const res = Object.create(parentVal || null)
if (childVal) {
process.env.NODE_ENV !== 'production' && assertObjectType(key, childVal, vm)
return extend(res, childVal)
} else {
return res
}
}
ASSET_TYPES.forEach(function (type) {
strats[type + 's'] = mergeAssets
})
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (
parentVal: ?Object,
childVal: ?Object,
vm?: Component,
key: string
): ?Object {
// work around Firefox's Object.prototype.watch...
if (parentVal === nativeWatch) parentVal = undefined
if (childVal === nativeWatch) childVal = undefined
/* istanbul ignore if */
if (!childVal) return Object.create(parentVal || null)
if (process.env.NODE_ENV !== 'production') {
assertObjectType(key, childVal, vm)
}
if (!parentVal) return childVal
const ret = {}
extend(ret, parentVal)
for (const key in childVal) {
let parent = ret[key]
const child = childVal[key]
if (parent && !Array.isArray(parent)) {
parent = [parent]
}
ret[key] = parent
? parent.concat(child)
: Array.isArray(child) ? child : [child]
}
return ret
}
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.inject =
strats.computed = function (
parentVal: ?Object,
childVal: ?Object,
vm?: Component,
key: string
): ?Object {
if (childVal && process.env.NODE_ENV !== 'production') {
assertObjectType(key, childVal, vm)
}
if (!parentVal) return childVal
const ret = Object.create(null)
extend(ret, parentVal)
if (childVal) extend(ret, childVal)
return ret
}
strats.provide = mergeDataOrFn
/**
* Default strategy.
*/
const defaultStrat = function (parentVal: any, childVal: any): any {
return childVal === undefined
? parentVal
: childVal
}
/**
* Validate component names
*/
function checkComponents (options: Object) {
for (const key in options.components) {
validateComponentName(key)
}
}
export function validateComponentName (name: string) {
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characters and the hyphen, ' +
'and must start with a letter.'
)
}
if (isBuiltInTag(name) || config.isReservedTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + name
)
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options: Object, vm: ?Component) {
const props = options.props
if (!props) return
const res = {}
let i, val, name
if (Array.isArray(props)) {
i = props.length
while (i--) {
val = props[i]
if (typeof val === 'string') {
name = camelize(val)
res[name] = { type: null }
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.')
}
}
} else if (isPlainObject(props)) {
for (const key in props) {
val = props[key]
name = camelize(key)
res[name] = isPlainObject(val)
? val
: { type: val }
}
} else if (process.env.NODE_ENV !== 'production') {
warn(
`Invalid value for option "props": expected an Array or an Object, ` +
`but got ${toRawType(props)}.`,
vm
)
}
options.props = res
}
/**
* Normalize all injections into Object-based format
*/
function normalizeInject (options: Object, vm: ?Component) {
const inject = options.inject
if (!inject) return
const normalized = options.inject = {}
if (Array.isArray(inject)) {
for (let i = 0; i < inject.length; i++) {
normalized[inject[i]] = { from: inject[i] }
}
} else if (isPlainObject(inject)) {
for (const key in inject) {
const val = inject[key]
normalized[key] = isPlainObject(val)
? extend({ from: key }, val)
: { from: val }
}
} else if (process.env.NODE_ENV !== 'production') {
warn(
`Invalid value for option "inject": expected an Array or an Object, ` +
`but got ${toRawType(inject)}.`,
vm
)
}
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options: Object) {
const dirs = options.directives
if (dirs) {
for (const key in dirs) {
const def = dirs[key]
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def }
}
}
}
}
function assertObjectType (name: string, value: any, vm: ?Component) {
if (!isPlainObject(value)) {
warn(
`Invalid value for option "${name}": expected an Object, ` +
`but got ${toRawType(value)}.`,
vm
)
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
export function mergeOptions (
parent: Object,
child: Object,
vm?: Component
): Object {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child)
}
if (typeof child === 'function') {
child = child.options
}
normalizeProps(child, vm)
normalizeInject(child, vm)
normalizeDirectives(child)
const extendsFrom = child.extends
if (extendsFrom) {
parent = mergeOptions(parent, extendsFrom, vm)
}
if (child.mixins) {
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
const options = {}
let key
for (key in parent) {
mergeField(key)
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key)
}
}
function mergeField (key) {
const strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key)
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
export function resolveAsset (
options: Object,
type: string,
id: string,
warnMissing?: boolean
): any {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
const assets = options[type]
// check local registration variations first
if (hasOwn(assets, id)) return assets[id]
const camelizedId = camelize(id)
if (hasOwn(assets, camelizedId)) return assets[camelizedId]
const PascalCaseId = capitalize(camelizedId)
if (hasOwn(assets, PascalCaseId)) return assets[PascalCaseId]
// fallback to prototype chain
const res = assets[id] || assets[camelizedId] || assets[PascalCaseId]
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
)
}
return res
}
| src/core/util/options.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.996498703956604,
0.0669667199254036,
0.0001621690025785938,
0.00017339955957140774,
0.24508532881736755
] |
{
"id": 1,
"code_window": [
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n",
" if (value) {\n",
" const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'\n",
" warn(\n",
" `${binding}=\"${value}\" conflicts with v-model on the same element ` +\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']\n",
" if (value && !typeBinding) {\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "replace",
"edit_start_line_idx": 134
} | /* @flow */
import config from 'core/config'
import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'
import { genComponentModel, genAssignmentCode } from 'compiler/directives/model'
let warn
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
export const RANGE_TOKEN = '__r'
export const CHECKBOX_RADIO_TOKEN = '__c'
export default function model (
el: ASTElement,
dir: ASTDirective,
_warn: Function
): ?boolean {
warn = _warn
const value = dir.value
const modifiers = dir.modifiers
const tag = el.tag
const type = el.attrsMap.type
if (process.env.NODE_ENV !== 'production') {
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn(
`<${el.tag} v-model="${value}" type="file">:\n` +
`File inputs are read only. Use a v-on:change listener instead.`
)
}
}
if (el.component) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers)
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers)
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers)
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers)
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (process.env.NODE_ENV !== 'production') {
warn(
`<${el.tag} v-model="${value}">: ` +
`v-model is not supported on this element type. ` +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.'
)
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const valueBinding = getBindingAttr(el, 'value') || 'null'
const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'
const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'
addProp(el, 'checked',
`Array.isArray(${value})` +
`?_i(${value},${valueBinding})>-1` + (
trueValueBinding === 'true'
? `:(${value})`
: `:_q(${value},${trueValueBinding})`
)
)
addHandler(el, 'change',
`var $$a=${value},` +
'$$el=$event.target,' +
`$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +
'if(Array.isArray($$a)){' +
`var $$v=${number ? '_n(' + valueBinding + ')' : valueBinding},` +
'$$i=_i($$a,$$v);' +
`if($$el.checked){$$i<0&&(${value}=$$a.concat([$$v]))}` +
`else{$$i>-1&&(${value}=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}` +
`}else{${genAssignmentCode(value, '$$c')}}`,
null, true
)
}
function genRadioModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
let valueBinding = getBindingAttr(el, 'value') || 'null'
valueBinding = number ? `_n(${valueBinding})` : valueBinding
addProp(el, 'checked', `_q(${value},${valueBinding})`)
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)
}
function genSelect (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const selectedVal = `Array.prototype.filter` +
`.call($event.target.options,function(o){return o.selected})` +
`.map(function(o){var val = "_value" in o ? o._value : o.value;` +
`return ${number ? '_n(val)' : 'val'}})`
const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'
let code = `var $$selectedVal = ${selectedVal};`
code = `${code} ${genAssignmentCode(value, assignment)}`
addHandler(el, 'change', code, null, true)
}
function genDefaultModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
): ?boolean {
const type = el.attrsMap.type
// warn if v-bind:value conflicts with v-model
if (process.env.NODE_ENV !== 'production') {
const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']
if (value) {
const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'
warn(
`${binding}="${value}" conflicts with v-model on the same element ` +
'because the latter already expands to a value binding internally'
)
}
}
const { lazy, number, trim } = modifiers || {}
const needCompositionGuard = !lazy && type !== 'range'
const event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input'
let valueExpression = '$event.target.value'
if (trim) {
valueExpression = `$event.target.value.trim()`
}
if (number) {
valueExpression = `_n(${valueExpression})`
}
let code = genAssignmentCode(value, valueExpression)
if (needCompositionGuard) {
code = `if($event.target.composing)return;${code}`
}
addProp(el, 'value', `(${value})`)
addHandler(el, event, code, null, true)
if (trim || number) {
addHandler(el, 'blur', '$forceUpdate()')
}
}
| src/platforms/web/compiler/directives/model.js | 1 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.9985338449478149,
0.14332886040210724,
0.0001672505313763395,
0.00184443942271173,
0.29834869503974915
] |
{
"id": 1,
"code_window": [
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n",
" if (value) {\n",
" const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'\n",
" warn(\n",
" `${binding}=\"${value}\" conflicts with v-model on the same element ` +\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']\n",
" if (value && !typeBinding) {\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "replace",
"edit_start_line_idx": 134
} | ({
type: 'recycle-list',
attr: {
append: 'tree',
listData: [
{ type: 'A' },
{ type: 'A' }
],
switch: 'type',
alias: 'item'
},
children: [{
type: 'cell-slot',
attr: { append: 'tree', case: 'A' },
children: [{
type: 'div',
attr: {
'[[repeat]]': {
'@expression': 'item.list',
'@index': 'index',
'@alias': 'object'
}
},
children: [{
type: 'text',
attr: {
value: {
'@binding': 'object.name'
}
}
}, {
type: 'text',
attr: {
'[[repeat]]': {
'@expression': 'object',
'@alias': 'v',
'@key': 'k',
'@index': 'i'
},
value: {
'@binding': 'v'
}
}
}]
}]
}]
})
| test/weex/cases/recycle-list/v-for-iterator.vdom.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.0001752469252096489,
0.0001721661537885666,
0.0001695872488198802,
0.00017186430341098458,
0.000002373369397901115
] |
{
"id": 1,
"code_window": [
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n",
" if (value) {\n",
" const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'\n",
" warn(\n",
" `${binding}=\"${value}\" conflicts with v-model on the same element ` +\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']\n",
" if (value && !typeBinding) {\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "replace",
"edit_start_line_idx": 134
} | {
"root": true,
"plugins": [
"flowtype"
],
"extends": [
"plugin:vue-libs/recommended",
"plugin:flowtype/recommended"
],
"globals": {
"__WEEX__": true,
"WXEnvironment": true
}
}
| .eslintrc | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.00017299580213148147,
0.00017291739641223103,
0.0001728389906929806,
0.00017291739641223103,
7.84057192504406e-8
] |
{
"id": 1,
"code_window": [
" if (process.env.NODE_ENV !== 'production') {\n",
" const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']\n",
" if (value) {\n",
" const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'\n",
" warn(\n",
" `${binding}=\"${value}\" conflicts with v-model on the same element ` +\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']\n",
" if (value && !typeBinding) {\n"
],
"file_path": "src/platforms/web/compiler/directives/model.js",
"type": "replace",
"edit_start_line_idx": 134
} | import Vue from 'vue'
describe('Options el', () => {
it('basic usage', () => {
const el = document.createElement('div')
el.innerHTML = '<span>{{message}}</span>'
const vm = new Vue({
el,
data: { message: 'hello world' }
})
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe(vm.message)
})
it('should be replaced when use together with `template` option', () => {
const el = document.createElement('div')
el.innerHTML = '<span>{{message}}</span>'
const vm = new Vue({
el,
template: '<p id="app"><span>{{message}}</span></p>',
data: { message: 'hello world' }
})
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe(vm.message)
})
it('should be replaced when use together with `render` option', () => {
const el = document.createElement('div')
el.innerHTML = '<span>{{message}}</span>'
const vm = new Vue({
el,
render (h) {
return h('p', { staticAttrs: { id: 'app' }}, [
h('span', {}, [this.message])
])
},
data: { message: 'hello world' }
})
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe(vm.message)
})
it('svg element', () => {
const parent = document.createElement('div')
parent.innerHTML =
'<svg>' +
'<text :x="x" :y="y" :fill="color">{{ text }}</text>' +
'<g><clipPath><foo></foo></clipPath></g>' +
'</svg>'
const vm = new Vue({
el: parent.childNodes[0],
data: {
x: 64,
y: 128,
color: 'red',
text: 'svg text'
}
})
expect(vm.$el.tagName).toBe('svg')
expect(vm.$el.childNodes[0].getAttribute('x')).toBe(vm.x.toString())
expect(vm.$el.childNodes[0].getAttribute('y')).toBe(vm.y.toString())
expect(vm.$el.childNodes[0].getAttribute('fill')).toBe(vm.color)
expect(vm.$el.childNodes[0].textContent).toBe(vm.text)
// nested, non-explicitly listed SVG elements
expect(vm.$el.childNodes[1].childNodes[0].namespaceURI).toContain('svg')
expect(vm.$el.childNodes[1].childNodes[0].childNodes[0].namespaceURI).toContain('svg')
})
// https://w3c.github.io/DOM-Parsing/#dfn-serializing-an-attribute-value
it('properly decode attribute values when parsing templates from DOM', () => {
const el = document.createElement('div')
el.innerHTML = '<a href="/a?foo=bar&baz=qux" name="<abc>" single=\'"hi"\'></a>'
const vm = new Vue({ el })
expect(vm.$el.children[0].getAttribute('href')).toBe('/a?foo=bar&baz=qux')
expect(vm.$el.children[0].getAttribute('name')).toBe('<abc>')
expect(vm.$el.children[0].getAttribute('single')).toBe('"hi"')
})
it('decode attribute value newlines when parsing templates from DOM in IE', () => {
const el = document.createElement('div')
el.innerHTML = `<a :style="{\ncolor:'red'\n}"></a>`
const vm = new Vue({ el })
expect(vm.$el.children[0].style.color).toBe('red')
})
it('warn cannot find element', () => {
new Vue({ el: '#non-existent' })
expect('Cannot find element: #non-existent').toHaveBeenWarned()
})
})
| test/unit/features/options/el.spec.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.0018477592384442687,
0.0006795238004997373,
0.00016455064178444445,
0.00026916907518170774,
0.0006726334104314446
] |
{
"id": 2,
"code_window": [
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n",
" if (!isAndroid) {\n",
" it('does not trigger extra input events with single compositionend', () => {\n",
" const spy = jasmine.createSpy()\n",
" const vm = new Vue({\n",
" data: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should not warn on input with dynamic type binding', () => {\n",
" new Vue({\n",
" data: {\n",
" type: 'checkbox',\n",
" test: 'foo'\n",
" },\n",
" template: '<input :type=\"type\" v-model=\"test\" :value=\"test\">'\n",
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n"
],
"file_path": "test/unit/features/directives/model-text.spec.js",
"type": "add",
"edit_start_line_idx": 291
} | /* @flow */
import config from 'core/config'
import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'
import { genComponentModel, genAssignmentCode } from 'compiler/directives/model'
let warn
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
export const RANGE_TOKEN = '__r'
export const CHECKBOX_RADIO_TOKEN = '__c'
export default function model (
el: ASTElement,
dir: ASTDirective,
_warn: Function
): ?boolean {
warn = _warn
const value = dir.value
const modifiers = dir.modifiers
const tag = el.tag
const type = el.attrsMap.type
if (process.env.NODE_ENV !== 'production') {
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn(
`<${el.tag} v-model="${value}" type="file">:\n` +
`File inputs are read only. Use a v-on:change listener instead.`
)
}
}
if (el.component) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers)
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers)
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers)
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers)
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (process.env.NODE_ENV !== 'production') {
warn(
`<${el.tag} v-model="${value}">: ` +
`v-model is not supported on this element type. ` +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.'
)
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const valueBinding = getBindingAttr(el, 'value') || 'null'
const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'
const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'
addProp(el, 'checked',
`Array.isArray(${value})` +
`?_i(${value},${valueBinding})>-1` + (
trueValueBinding === 'true'
? `:(${value})`
: `:_q(${value},${trueValueBinding})`
)
)
addHandler(el, 'change',
`var $$a=${value},` +
'$$el=$event.target,' +
`$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +
'if(Array.isArray($$a)){' +
`var $$v=${number ? '_n(' + valueBinding + ')' : valueBinding},` +
'$$i=_i($$a,$$v);' +
`if($$el.checked){$$i<0&&(${value}=$$a.concat([$$v]))}` +
`else{$$i>-1&&(${value}=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}` +
`}else{${genAssignmentCode(value, '$$c')}}`,
null, true
)
}
function genRadioModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
let valueBinding = getBindingAttr(el, 'value') || 'null'
valueBinding = number ? `_n(${valueBinding})` : valueBinding
addProp(el, 'checked', `_q(${value},${valueBinding})`)
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)
}
function genSelect (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const selectedVal = `Array.prototype.filter` +
`.call($event.target.options,function(o){return o.selected})` +
`.map(function(o){var val = "_value" in o ? o._value : o.value;` +
`return ${number ? '_n(val)' : 'val'}})`
const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'
let code = `var $$selectedVal = ${selectedVal};`
code = `${code} ${genAssignmentCode(value, assignment)}`
addHandler(el, 'change', code, null, true)
}
function genDefaultModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
): ?boolean {
const type = el.attrsMap.type
// warn if v-bind:value conflicts with v-model
if (process.env.NODE_ENV !== 'production') {
const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value']
if (value) {
const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'
warn(
`${binding}="${value}" conflicts with v-model on the same element ` +
'because the latter already expands to a value binding internally'
)
}
}
const { lazy, number, trim } = modifiers || {}
const needCompositionGuard = !lazy && type !== 'range'
const event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input'
let valueExpression = '$event.target.value'
if (trim) {
valueExpression = `$event.target.value.trim()`
}
if (number) {
valueExpression = `_n(${valueExpression})`
}
let code = genAssignmentCode(value, valueExpression)
if (needCompositionGuard) {
code = `if($event.target.composing)return;${code}`
}
addProp(el, 'value', `(${value})`)
addHandler(el, event, code, null, true)
if (trim || number) {
addHandler(el, 'blur', '$forceUpdate()')
}
}
| src/platforms/web/compiler/directives/model.js | 1 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.0005716359592042863,
0.00021404259314294904,
0.0001667711912887171,
0.00017703379853628576,
0.00009273643809137866
] |
{
"id": 2,
"code_window": [
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n",
" if (!isAndroid) {\n",
" it('does not trigger extra input events with single compositionend', () => {\n",
" const spy = jasmine.createSpy()\n",
" const vm = new Vue({\n",
" data: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should not warn on input with dynamic type binding', () => {\n",
" new Vue({\n",
" data: {\n",
" type: 'checkbox',\n",
" test: 'foo'\n",
" },\n",
" template: '<input :type=\"type\" v-model=\"test\" :value=\"test\">'\n",
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n"
],
"file_path": "test/unit/features/directives/model-text.spec.js",
"type": "add",
"edit_start_line_idx": 291
} | import Vue from 'vue'
import { Promise } from 'es6-promise'
describe('Component async', () => {
it('normal', done => {
const vm = new Vue({
template: '<div><test></test></div>',
components: {
test: (resolve) => {
setTimeout(() => {
resolve({
template: '<div>hi</div>'
})
// wait for parent update
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<!---->')
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.innerHTML).toBe('<div>hi</div>')
expect(vm.$children.length).toBe(1)
done()
}
})
it('resolve ES module default', done => {
const vm = new Vue({
template: '<div><test></test></div>',
components: {
test: (resolve) => {
setTimeout(() => {
resolve({
__esModule: true,
default: {
template: '<div>hi</div>'
}
})
// wait for parent update
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<!---->')
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.innerHTML).toBe('<div>hi</div>')
expect(vm.$children.length).toBe(1)
done()
}
})
it('as root', done => {
const vm = new Vue({
template: '<test></test>',
components: {
test: resolve => {
setTimeout(() => {
resolve({
template: '<div>hi</div>'
})
// wait for parent update
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
expect(vm.$el.nodeType).toBe(8)
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.nodeType).toBe(1)
expect(vm.$el.outerHTML).toBe('<div>hi</div>')
expect(vm.$children.length).toBe(1)
done()
}
})
it('dynamic', done => {
var vm = new Vue({
template: '<component :is="view"></component>',
data: {
view: 'view-a'
},
components: {
'view-a': resolve => {
setTimeout(() => {
resolve({
template: '<div>A</div>'
})
Vue.nextTick(step1)
}, 0)
},
'view-b': resolve => {
setTimeout(() => {
resolve({
template: '<p>B</p>'
})
Vue.nextTick(step2)
}, 0)
}
}
}).$mount()
var aCalled = false
function step1 () {
// ensure A is resolved only once
expect(aCalled).toBe(false)
aCalled = true
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('A')
vm.view = 'view-b'
}
function step2 () {
expect(vm.$el.tagName).toBe('P')
expect(vm.$el.textContent).toBe('B')
vm.view = 'view-a'
waitForUpdate(function () {
expect(vm.$el.tagName).toBe('DIV')
expect(vm.$el.textContent).toBe('A')
}).then(done)
}
})
it('warn reject', () => {
new Vue({
template: '<test></test>',
components: {
test: (resolve, reject) => {
reject('nooooo')
}
}
}).$mount()
expect('Reason: nooooo').toHaveBeenWarned()
})
it('with v-for', done => {
const vm = new Vue({
template: '<div><test v-for="n in list" :key="n" :n="n"></test></div>',
data: {
list: [1, 2, 3]
},
components: {
test: resolve => {
setTimeout(() => {
resolve({
props: ['n'],
template: '<div>{{n}}</div>'
})
Vue.nextTick(next)
}, 0)
}
}
}).$mount()
function next () {
expect(vm.$el.innerHTML).toBe('<div>1</div><div>2</div><div>3</div>')
done()
}
})
it('returning Promise', done => {
const vm = new Vue({
template: '<div><test></test></div>',
components: {
test: () => {
return new Promise(resolve => {
setTimeout(() => {
resolve({
template: '<div>hi</div>'
})
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 0)
})
}
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<!---->')
expect(vm.$children.length).toBe(0)
function next () {
expect(vm.$el.innerHTML).toBe('<div>hi</div>')
expect(vm.$children.length).toBe(1)
done()
}
})
describe('loading/error/timeout', () => {
it('with loading component', done => {
const vm = new Vue({
template: `<div><test/></div>`,
components: {
test: () => ({
component: new Promise(resolve => {
setTimeout(() => {
resolve({ template: '<div>hi</div>' })
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `<div>loading</div>` },
delay: 1
})
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<!---->')
let loadingAsserted = false
setTimeout(() => {
Vue.nextTick(() => {
loadingAsserted = true
expect(vm.$el.textContent).toBe('loading')
})
}, 1)
function next () {
expect(loadingAsserted).toBe(true)
expect(vm.$el.textContent).toBe('hi')
done()
}
})
it('with loading component (0 delay)', done => {
const vm = new Vue({
template: `<div><test/></div>`,
components: {
test: () => ({
component: new Promise(resolve => {
setTimeout(() => {
resolve({ template: '<div>hi</div>' })
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `<div>loading</div>` },
delay: 0
})
}
}).$mount()
expect(vm.$el.textContent).toBe('loading')
function next () {
expect(vm.$el.textContent).toBe('hi')
done()
}
})
it('with error component', done => {
const vm = new Vue({
template: `<div><test/></div>`,
components: {
test: () => ({
component: new Promise((resolve, reject) => {
setTimeout(() => {
reject()
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `<div>loading</div>` },
error: { template: `<div>error</div>` },
delay: 0
})
}
}).$mount()
expect(vm.$el.textContent).toBe('loading')
function next () {
expect(`Failed to resolve async component`).toHaveBeenWarned()
expect(vm.$el.textContent).toBe('error')
done()
}
})
it('with error component + timeout', done => {
const vm = new Vue({
template: `<div><test/></div>`,
components: {
test: () => ({
component: new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ template: '<div>hi</div>' })
// wait for promise resolve and then parent update
Promise.resolve().then(() => {
Vue.nextTick(next)
})
}, 50)
}),
loading: { template: `<div>loading</div>` },
error: { template: `<div>error</div>` },
delay: 0,
timeout: 1
})
}
}).$mount()
expect(vm.$el.textContent).toBe('loading')
setTimeout(() => {
Vue.nextTick(() => {
expect(`Failed to resolve async component`).toHaveBeenWarned()
expect(vm.$el.textContent).toBe('error')
})
}, 1)
function next () {
expect(vm.$el.textContent).toBe('error') // late resolve ignored
done()
}
})
it('should not trigger timeout if resolved', done => {
const vm = new Vue({
template: `<div><test/></div>`,
components: {
test: () => ({
component: new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ template: '<div>hi</div>' })
}, 10)
}),
error: { template: `<div>error</div>` },
timeout: 20
})
}
}).$mount()
setTimeout(() => {
expect(vm.$el.textContent).toBe('hi')
expect(`Failed to resolve async component`).not.toHaveBeenWarned()
done()
}, 50)
})
// #7107
it(`should work when resolving sync in sibling component's mounted hook`, done => {
let resolveTwo
const vm = new Vue({
template: `<div><one/> <two/></div>`,
components: {
one: {
template: `<div>one</div>`,
mounted () {
resolveTwo()
}
},
two: resolve => {
resolveTwo = () => {
resolve({
template: `<div>two</div>`
})
}
}
}
}).$mount()
expect(vm.$el.textContent).toBe('one ')
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('one two')
}).then(done)
})
})
})
| test/unit/features/component/component-async.spec.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.9885309934616089,
0.15802907943725586,
0.00016406243958044797,
0.0025219423696398735,
0.3088490664958954
] |
{
"id": 2,
"code_window": [
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n",
" if (!isAndroid) {\n",
" it('does not trigger extra input events with single compositionend', () => {\n",
" const spy = jasmine.createSpy()\n",
" const vm = new Vue({\n",
" data: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should not warn on input with dynamic type binding', () => {\n",
" new Vue({\n",
" data: {\n",
" type: 'checkbox',\n",
" test: 'foo'\n",
" },\n",
" template: '<input :type=\"type\" v-model=\"test\" :value=\"test\">'\n",
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n"
],
"file_path": "test/unit/features/directives/model-text.spec.js",
"type": "add",
"edit_start_line_idx": 291
} | /* @flow */
import config from '../config'
import Dep from '../observer/dep'
import Watcher from '../observer/watcher'
import { isUpdatingChildComponent } from './lifecycle'
import {
set,
del,
observe,
observerState,
defineReactive
} from '../observer/index'
import {
warn,
bind,
noop,
hasOwn,
hyphenate,
isReserved,
handleError,
nativeWatch,
validateProp,
isPlainObject,
isServerRendering,
isReservedAttribute
} from '../util/index'
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
function initProps (vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = vm._props = {}
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = vm.$options._propKeys = []
const isRoot = !vm.$parent
// root instance props should be converted
observerState.shouldConvert = isRoot
for (const key in propsOptions) {
keys.push(key)
const value = validateProp(key, propsOptions, propsData, vm)
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
const hyphenatedKey = hyphenate(key)
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
`"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
vm
)
}
defineReactive(props, key, value, () => {
if (vm.$parent && !isUpdatingChildComponent) {
warn(
`Avoid mutating a prop directly since the value will be ` +
`overwritten whenever the parent component re-renders. ` +
`Instead, use a data or computed property based on the prop's ` +
`value. Prop being mutated: "${key}"`,
vm
)
}
})
} else {
defineReactive(props, key, value)
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
observerState.shouldConvert = true
}
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
proxy(vm, `_data`, key)
}
}
// observe data
observe(data, true /* asRootData */)
}
export function getData (data: Function, vm: Component): any {
try {
return data.call(vm, vm)
} catch (e) {
handleError(e, vm, `data()`)
return {}
}
}
const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null)
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = typeof userDef === 'function' ? userDef : userDef.get
if (process.env.NODE_ENV !== 'production' && getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
)
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} else if (process.env.NODE_ENV !== 'production') {
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm)
} else if (vm.$options.props && key in vm.$options.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm)
}
}
}
}
export function defineComputed (
target: any,
key: string,
userDef: Object | Function
) {
const shouldCache = !isServerRendering()
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: userDef
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop
}
if (process.env.NODE_ENV !== 'production' &&
sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
}
function initMethods (vm: Component, methods: Object) {
const props = vm.$options.props
for (const key in methods) {
if (process.env.NODE_ENV !== 'production') {
if (methods[key] == null) {
warn(
`Method "${key}" has an undefined value in the component definition. ` +
`Did you reference the function correctly?`,
vm
)
}
if (props && hasOwn(props, key)) {
warn(
`Method "${key}" has already been defined as a prop.`,
vm
)
}
if ((key in vm) && isReserved(key)) {
warn(
`Method "${key}" conflicts with an existing Vue instance method. ` +
`Avoid defining component methods that start with _ or $.`
)
}
}
vm[key] = methods[key] == null ? noop : bind(methods[key], vm)
}
}
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}
function createWatcher (
vm: Component,
keyOrFn: string | Function,
handler: any,
options?: Object
) {
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
return vm.$watch(keyOrFn, handler, options)
}
export function stateMixin (Vue: Class<Component>) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData: Object) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
propsDef.set = function () {
warn(`$props is readonly.`, this)
}
}
Object.defineProperty(Vue.prototype, '$data', dataDef)
Object.defineProperty(Vue.prototype, '$props', propsDef)
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
cb.call(vm, watcher.value)
}
return function unwatchFn () {
watcher.teardown()
}
}
}
| src/core/instance/state.js | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.9872013330459595,
0.0818924531340599,
0.00016612715262454003,
0.00019679073011502624,
0.2536276578903198
] |
{
"id": 2,
"code_window": [
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n",
" if (!isAndroid) {\n",
" it('does not trigger extra input events with single compositionend', () => {\n",
" const spy = jasmine.createSpy()\n",
" const vm = new Vue({\n",
" data: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should not warn on input with dynamic type binding', () => {\n",
" new Vue({\n",
" data: {\n",
" type: 'checkbox',\n",
" test: 'foo'\n",
" },\n",
" template: '<input :type=\"type\" v-model=\"test\" :value=\"test\">'\n",
" }).$mount()\n",
" expect('conflicts with v-model').not.toHaveBeenWarned()\n",
" })\n",
"\n"
],
"file_path": "test/unit/features/directives/model-text.spec.js",
"type": "add",
"edit_start_line_idx": 291
} | import Vue from "../index";
import { PluginFunction, PluginObject } from "../index";
class Option {
prefix: string = "";
suffix: string = "";
}
const plugin: PluginObject<Option> = {
install(Vue, option) {
if (typeof option !== "undefined") {
const {prefix, suffix} = option;
}
}
}
const installer: PluginFunction<Option> = function(Vue, option) { }
Vue.use(plugin, new Option);
Vue.use(installer, new Option);
Vue.use(installer, new Option, new Option, new Option);
| types/test/plugin-test.ts | 0 | https://github.com/vuejs/vue/commit/1c0b4af5fd2f9e8173b8f4718018ee80a6313872 | [
0.00018419807020109147,
0.00017782504437491298,
0.00017263788322452456,
0.00017663916514720768,
0.000004793343123310478
] |
{
"id": 0,
"code_window": [
"\tconst extensionsOut = gulp.src('extensions/**/out/**/*.map', { base: '.' });\n",
"\tconst extensionsDist = gulp.src('extensions/**/dist/**/*.map', { base: '.' });\n",
"\n",
"\tconst res = es.merge(vs, extensionsOut, extensionsDist)\n",
"\t\t.pipe(es.through(function (data) {\n",
"\t\t\t// debug\n",
"\t\t\tconsole.log('Uploading Sourcemap', data.relative);\n",
"\t\t\tthis.emit('data', data);\n",
"\t\t}))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn es.merge(vs, extensionsOut, extensionsDist)\n"
],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 516
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
const gulp = require('gulp');
const fs = require('fs');
const os = require('os');
const cp = require('child_process');
const path = require('path');
const es = require('event-stream');
const azure = require('gulp-azure-storage');
const electron = require('gulp-atom-electron');
const vfs = require('vinyl-fs');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const filter = require('gulp-filter');
const json = require('gulp-json-editor');
const _ = require('underscore');
const util = require('./lib/util');
const ext = require('./lib/extensions');
const buildfile = require('../src/buildfile');
const common = require('./lib/optimize');
const root = path.dirname(__dirname);
const commit = util.getVersion(root);
const packageJson = require('../package.json');
const product = require('../product.json');
const crypto = require('crypto');
const i18n = require('./lib/i18n');
const deps = require('./dependencies');
const getElectronVersion = require('./lib/electron').getElectronVersion;
const createAsar = require('./lib/asar').createAsar;
const productionDependencies = deps.getProductionDependencies(path.dirname(__dirname));
// @ts-ignore
const baseModules = Object.keys(process.binding('natives')).filter(n => !/^_|\//.test(n));
const nodeModules = ['electron', 'original-fs']
// @ts-ignore JSON checking: dependencies property is optional
.concat(Object.keys(product.dependencies || {}))
.concat(_.uniq(productionDependencies.map(d => d.name)))
.concat(baseModules);
// Build
const vscodeEntryPoints = _.flatten([
buildfile.entrypoint('vs/workbench/workbench.main'),
buildfile.base,
buildfile.workbench,
buildfile.code
]);
const vscodeResources = [
'out-build/main.js',
'out-build/cli.js',
'out-build/driver.js',
'out-build/bootstrap.js',
'out-build/bootstrap-fork.js',
'out-build/bootstrap-amd.js',
'out-build/bootstrap-window.js',
'out-build/paths.js',
'out-build/vs/**/*.{svg,png,cur,html}',
'out-build/vs/base/common/performance.js',
'out-build/vs/base/node/{stdForkStart.js,terminateProcess.sh,cpuUsage.sh}',
'out-build/vs/base/browser/ui/octiconLabel/octicons/**',
'out-build/vs/workbench/browser/media/*-theme.css',
'out-build/vs/workbench/parts/debug/**/*.json',
'out-build/vs/workbench/parts/execution/**/*.scpt',
'out-build/vs/workbench/parts/webview/electron-browser/webview-pre.js',
'out-build/vs/**/markdown.css',
'out-build/vs/workbench/parts/tasks/**/*.json',
'out-build/vs/workbench/parts/welcome/walkThrough/**/*.md',
'out-build/vs/workbench/services/files/**/*.exe',
'out-build/vs/workbench/services/files/**/*.md',
'out-build/vs/code/electron-browser/workbench/**',
'out-build/vs/code/electron-browser/sharedProcess/sharedProcess.js',
'out-build/vs/code/electron-browser/issue/issueReporter.js',
'out-build/vs/code/electron-browser/processExplorer/processExplorer.js',
'!**/test/**'
];
const BUNDLED_FILE_HEADER = [
'/*!--------------------------------------------------------',
' * Copyright (C) Microsoft Corporation. All rights reserved.',
' *--------------------------------------------------------*/'
].join('\n');
gulp.task('clean-optimized-vscode', util.rimraf('out-vscode'));
gulp.task('optimize-vscode', ['clean-optimized-vscode', 'compile-build', 'compile-extensions-build'], common.optimizeTask({
src: 'out-build',
entryPoints: vscodeEntryPoints,
otherSources: [],
resources: vscodeResources,
loaderConfig: common.loaderConfig(nodeModules),
header: BUNDLED_FILE_HEADER,
out: 'out-vscode',
bundleInfo: undefined
}));
gulp.task('optimize-index-js', ['optimize-vscode'], () => {
const fullpath = path.join(process.cwd(), 'out-vscode/vs/code/electron-browser/workbench/workbench.js');
const contents = fs.readFileSync(fullpath).toString();
const newContents = contents.replace('[/*BUILD->INSERT_NODE_MODULES*/]', JSON.stringify(nodeModules));
fs.writeFileSync(fullpath, newContents);
});
const sourceMappingURLBase = `https://ticino.blob.core.windows.net/sourcemaps/${commit}`;
gulp.task('clean-minified-vscode', util.rimraf('out-vscode-min'));
gulp.task('minify-vscode', ['clean-minified-vscode', 'optimize-index-js'], common.minifyTask('out-vscode', `${sourceMappingURLBase}/core`));
// Package
// @ts-ignore JSON checking: darwinCredits is optional
const darwinCreditsTemplate = product.darwinCredits && _.template(fs.readFileSync(path.join(root, product.darwinCredits), 'utf8'));
function darwinBundleDocumentType(extensions, icon) {
return {
name: product.nameLong + ' document',
role: 'Editor',
ostypes: ["TEXT", "utxt", "TUTX", "****"],
extensions: extensions,
iconFile: icon
};
}
const config = {
version: getElectronVersion(),
productAppName: product.nameLong,
companyName: 'Microsoft Corporation',
copyright: 'Copyright (C) 2018 Microsoft. All rights reserved',
darwinIcon: 'resources/darwin/code.icns',
darwinBundleIdentifier: product.darwinBundleIdentifier,
darwinApplicationCategoryType: 'public.app-category.developer-tools',
darwinHelpBookFolder: 'VS Code HelpBook',
darwinHelpBookName: 'VS Code HelpBook',
darwinBundleDocumentTypes: [
darwinBundleDocumentType(["bat", "cmd"], 'resources/darwin/bat.icns'),
darwinBundleDocumentType(["bowerrc"], 'resources/darwin/bower.icns'),
darwinBundleDocumentType(["c", "h"], 'resources/darwin/c.icns'),
darwinBundleDocumentType(["config", "editorconfig", "gitattributes", "gitconfig", "gitignore", "ini"], 'resources/darwin/config.icns'),
darwinBundleDocumentType(["cc", "cpp", "cxx", "hh", "hpp", "hxx"], 'resources/darwin/cpp.icns'),
darwinBundleDocumentType(["cs", "csx"], 'resources/darwin/csharp.icns'),
darwinBundleDocumentType(["css"], 'resources/darwin/css.icns'),
darwinBundleDocumentType(["go"], 'resources/darwin/go.icns'),
darwinBundleDocumentType(["asp", "aspx", "cshtml", "htm", "html", "jshtm", "jsp", "phtml", "shtml"], 'resources/darwin/html.icns'),
darwinBundleDocumentType(["jade"], 'resources/darwin/jade.icns'),
darwinBundleDocumentType(["jav", "java"], 'resources/darwin/java.icns'),
darwinBundleDocumentType(["js", "jscsrc", "jshintrc", "mjs"], 'resources/darwin/javascript.icns'),
darwinBundleDocumentType(["json"], 'resources/darwin/json.icns'),
darwinBundleDocumentType(["less"], 'resources/darwin/less.icns'),
darwinBundleDocumentType(["markdown", "md", "mdoc", "mdown", "mdtext", "mdtxt", "mdwn", "mkd", "mkdn"], 'resources/darwin/markdown.icns'),
darwinBundleDocumentType(["php"], 'resources/darwin/php.icns'),
darwinBundleDocumentType(["ps1", "psd1", "psm1"], 'resources/darwin/powershell.icns'),
darwinBundleDocumentType(["py"], 'resources/darwin/python.icns'),
darwinBundleDocumentType(["gemspec", "rb"], 'resources/darwin/ruby.icns'),
darwinBundleDocumentType(["scss"], 'resources/darwin/scss.icns'),
darwinBundleDocumentType(["bash", "bash_login", "bash_logout", "bash_profile", "bashrc", "profile", "rhistory", "rprofile", "sh", "zlogin", "zlogout", "zprofile", "zsh", "zshenv", "zshrc"], 'resources/darwin/shell.icns'),
darwinBundleDocumentType(["sql"], 'resources/darwin/sql.icns'),
darwinBundleDocumentType(["ts"], 'resources/darwin/typescript.icns'),
darwinBundleDocumentType(["tsx", "jsx"], 'resources/darwin/react.icns'),
darwinBundleDocumentType(["vue"], 'resources/darwin/vue.icns'),
darwinBundleDocumentType(["ascx", "csproj", "dtd", "wxi", "wxl", "wxs", "xml", "xaml"], 'resources/darwin/xml.icns'),
darwinBundleDocumentType(["eyaml", "eyml", "yaml", "yml"], 'resources/darwin/yaml.icns'),
darwinBundleDocumentType(["clj", "cljs", "cljx", "clojure", "code-workspace", "coffee", "ctp", "dockerfile", "dot", "edn", "fs", "fsi", "fsscript", "fsx", "handlebars", "hbs", "lua", "m", "makefile", "ml", "mli", "pl", "pl6", "pm", "pm6", "pod", "pp", "properties", "psgi", "pug", "r", "rs", "rt", "svg", "svgz", "t", "txt", "vb", "xcodeproj", "xcworkspace"], 'resources/darwin/default.icns')
],
darwinBundleURLTypes: [{
role: 'Viewer',
name: product.nameLong,
urlSchemes: [product.urlProtocol]
}],
darwinCredits: darwinCreditsTemplate ? Buffer.from(darwinCreditsTemplate({ commit: commit, date: new Date().toISOString() })) : void 0,
linuxExecutableName: product.applicationName,
winIcon: 'resources/win32/code.ico',
token: process.env['VSCODE_MIXIN_PASSWORD'] || process.env['GITHUB_TOKEN'] || void 0,
// @ts-ignore JSON checking: electronRepository is optional
repo: product.electronRepository || void 0
};
function getElectron(arch) {
return () => {
const electronOpts = _.extend({}, config, {
platform: process.platform,
arch,
ffmpegChromium: true,
keepDefaultApp: true
});
return gulp.src('package.json')
.pipe(json({ name: product.nameShort }))
.pipe(electron(electronOpts))
.pipe(filter(['**', '!**/app/package.json']))
.pipe(vfs.dest('.build/electron'));
};
}
gulp.task('clean-electron', util.rimraf('.build/electron'));
gulp.task('electron', ['clean-electron'], getElectron(process.arch));
gulp.task('electron-ia32', ['clean-electron'], getElectron('ia32'));
gulp.task('electron-x64', ['clean-electron'], getElectron('x64'));
gulp.task('electron-arm', ['clean-electron'], getElectron('arm'));
gulp.task('electron-arm64', ['clean-electron'], getElectron('arm64'));
/**
* Compute checksums for some files.
*
* @param {string} out The out folder to read the file from.
* @param {string[]} filenames The paths to compute a checksum for.
* @return {Object} A map of paths to checksums.
*/
function computeChecksums(out, filenames) {
var result = {};
filenames.forEach(function (filename) {
var fullPath = path.join(process.cwd(), out, filename);
result[filename] = computeChecksum(fullPath);
});
return result;
}
/**
* Compute checksum for a file.
*
* @param {string} filename The absolute path to a filename.
* @return {string} The checksum for `filename`.
*/
function computeChecksum(filename) {
var contents = fs.readFileSync(filename);
var hash = crypto
.createHash('md5')
.update(contents)
.digest('base64')
.replace(/=+$/, '');
return hash;
}
function packageTask(platform, arch, opts) {
opts = opts || {};
const destination = path.join(path.dirname(root), 'VSCode') + (platform ? '-' + platform : '') + (arch ? '-' + arch : '');
platform = platform || process.platform;
return () => {
const out = opts.minified ? 'out-vscode-min' : 'out-vscode';
const checksums = computeChecksums(out, [
'vs/workbench/workbench.main.js',
'vs/workbench/workbench.main.css',
'vs/code/electron-browser/workbench/workbench.html',
'vs/code/electron-browser/workbench/workbench.js'
]);
const src = gulp.src(out + '/**', { base: '.' })
.pipe(rename(function (path) { path.dirname = path.dirname.replace(new RegExp('^' + out), 'out'); }))
.pipe(util.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map']));
const root = path.resolve(path.join(__dirname, '..'));
const sources = es.merge(src, ext.packageExtensionsStream({
sourceMappingURLBase: sourceMappingURLBase
}));
let version = packageJson.version;
// @ts-ignore JSON checking: quality is optional
const quality = product.quality;
if (quality && quality !== 'stable') {
version += '-' + quality;
}
const name = product.nameShort;
const packageJsonUpdates = { name, version };
// for linux url handling
if (platform === 'linux') {
packageJsonUpdates.desktopName = `${product.applicationName}-url-handler.desktop`;
}
const packageJsonStream = gulp.src(['package.json'], { base: '.' })
.pipe(json(packageJsonUpdates));
const date = new Date().toISOString();
const productJsonUpdate = { commit, date, checksums };
if (shouldSetupSettingsSearch()) {
productJsonUpdate.settingsSearchBuildId = getSettingsSearchBuildId(packageJson);
}
const productJsonStream = gulp.src(['product.json'], { base: '.' })
.pipe(json(productJsonUpdate));
const license = gulp.src(['LICENSES.chromium.html', 'LICENSE.txt', 'ThirdPartyNotices.txt', 'licenses/**'], { base: '.' });
const watermark = gulp.src(['resources/letterpress.svg', 'resources/letterpress-dark.svg', 'resources/letterpress-hc.svg'], { base: '.' });
// TODO the API should be copied to `out` during compile, not here
const api = gulp.src('src/vs/vscode.d.ts').pipe(rename('out/vs/vscode.d.ts'));
const depsSrc = [
..._.flatten(productionDependencies.map(d => path.relative(root, d.path)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`])),
// @ts-ignore JSON checking: dependencies is optional
..._.flatten(Object.keys(product.dependencies || {}).map(d => [`node_modules/${d}/**`, `!node_modules/${d}/**/{test,tests}/**`]))
];
const deps = gulp.src(depsSrc, { base: '.', dot: true })
.pipe(filter(['**', '!**/package-lock.json']))
.pipe(util.cleanNodeModule('fsevents', ['binding.gyp', 'fsevents.cc', 'build/**', 'src/**', 'test/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('oniguruma', ['binding.gyp', 'build/**', 'src/**', 'deps/**'], ['**/*.node', 'src/*.js']))
.pipe(util.cleanNodeModule('windows-mutex', ['binding.gyp', 'build/**', 'src/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('native-keymap', ['binding.gyp', 'build/**', 'src/**', 'deps/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('native-is-elevated', ['binding.gyp', 'build/**', 'src/**', 'deps/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('native-watchdog', ['binding.gyp', 'build/**', 'src/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('spdlog', ['binding.gyp', 'build/**', 'deps/**', 'src/**', 'test/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('jschardet', ['dist/**']))
.pipe(util.cleanNodeModule('windows-foreground-love', ['binding.gyp', 'build/**', 'src/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('windows-process-tree', ['binding.gyp', 'build/**', 'src/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('gc-signals', ['binding.gyp', 'build/**', 'src/**', 'deps/**'], ['**/*.node', 'src/index.js']))
.pipe(util.cleanNodeModule('keytar', ['binding.gyp', 'build/**', 'src/**', 'script/**', 'node_modules/**'], ['**/*.node']))
.pipe(util.cleanNodeModule('node-pty', ['binding.gyp', 'build/**', 'src/**', 'tools/**'], ['build/Release/*.exe', 'build/Release/*.dll', 'build/Release/*.node']))
.pipe(util.cleanNodeModule('vscode-nsfw', ['binding.gyp', 'build/**', 'src/**', 'openpa/**', 'includes/**'], ['**/*.node', '**/*.a']))
.pipe(util.cleanNodeModule('vsda', ['binding.gyp', 'README.md', 'build/**', '*.bat', '*.sh', '*.cpp', '*.h'], ['build/Release/vsda.node']))
.pipe(createAsar(path.join(process.cwd(), 'node_modules'), ['**/*.node', '**/vscode-ripgrep/bin/*', '**/node-pty/build/Release/*'], 'app/node_modules.asar'));
let all = es.merge(
packageJsonStream,
productJsonStream,
license,
watermark,
api,
sources,
deps
);
if (platform === 'win32') {
all = es.merge(all, gulp.src([
'resources/win32/bower.ico',
'resources/win32/c.ico',
'resources/win32/config.ico',
'resources/win32/cpp.ico',
'resources/win32/csharp.ico',
'resources/win32/css.ico',
'resources/win32/default.ico',
'resources/win32/go.ico',
'resources/win32/html.ico',
'resources/win32/jade.ico',
'resources/win32/java.ico',
'resources/win32/javascript.ico',
'resources/win32/json.ico',
'resources/win32/less.ico',
'resources/win32/markdown.ico',
'resources/win32/php.ico',
'resources/win32/powershell.ico',
'resources/win32/python.ico',
'resources/win32/react.ico',
'resources/win32/ruby.ico',
'resources/win32/sass.ico',
'resources/win32/shell.ico',
'resources/win32/sql.ico',
'resources/win32/typescript.ico',
'resources/win32/vue.ico',
'resources/win32/xml.ico',
'resources/win32/yaml.ico',
'resources/win32/code_70x70.png',
'resources/win32/code_150x150.png'
], { base: '.' }));
} else if (platform === 'linux') {
all = es.merge(all, gulp.src('resources/linux/code.png', { base: '.' }));
} else if (platform === 'darwin') {
const shortcut = gulp.src('resources/darwin/bin/code.sh')
.pipe(rename('bin/code'));
all = es.merge(all, shortcut);
}
let result = all
.pipe(util.skipDirectories())
.pipe(util.fixWin32DirectoryPermissions())
.pipe(electron(_.extend({}, config, { platform, arch, ffmpegChromium: true })))
.pipe(filter(['**', '!LICENSE', '!LICENSES.chromium.html', '!version']));
if (platform === 'win32') {
result = es.merge(result, gulp.src('resources/win32/bin/code.js', { base: 'resources/win32' }));
result = es.merge(result, gulp.src('resources/win32/bin/code.cmd', { base: 'resources/win32' })
.pipe(replace('@@NAME@@', product.nameShort))
.pipe(rename(function (f) { f.basename = product.applicationName; })));
result = es.merge(result, gulp.src('resources/win32/bin/code.sh', { base: 'resources/win32' })
.pipe(replace('@@NAME@@', product.nameShort))
.pipe(rename(function (f) { f.basename = product.applicationName; f.extname = ''; })));
result = es.merge(result, gulp.src('resources/win32/VisualElementsManifest.xml', { base: 'resources/win32' })
.pipe(rename(product.nameShort + '.VisualElementsManifest.xml')));
} else if (platform === 'linux') {
result = es.merge(result, gulp.src('resources/linux/bin/code.sh', { base: '.' })
.pipe(replace('@@NAME@@', product.applicationName))
.pipe(rename('bin/' + product.applicationName)));
}
// submit all stats that have been collected
// during the build phase
if (opts.stats) {
result.on('end', () => {
const { submitAllStats } = require('./lib/stats');
submitAllStats(product, commit).then(() => console.log('Submitted bundle stats!'));
});
}
return result.pipe(vfs.dest(destination));
};
}
const buildRoot = path.dirname(root);
gulp.task('clean-vscode-win32-ia32', util.rimraf(path.join(buildRoot, 'VSCode-win32-ia32')));
gulp.task('clean-vscode-win32-x64', util.rimraf(path.join(buildRoot, 'VSCode-win32-x64')));
gulp.task('clean-vscode-darwin', util.rimraf(path.join(buildRoot, 'VSCode-darwin')));
gulp.task('clean-vscode-linux-ia32', util.rimraf(path.join(buildRoot, 'VSCode-linux-ia32')));
gulp.task('clean-vscode-linux-x64', util.rimraf(path.join(buildRoot, 'VSCode-linux-x64')));
gulp.task('clean-vscode-linux-arm', util.rimraf(path.join(buildRoot, 'VSCode-linux-arm')));
gulp.task('clean-vscode-linux-arm64', util.rimraf(path.join(buildRoot, 'VSCode-linux-arm64')));
gulp.task('vscode-win32-ia32', ['optimize-vscode', 'clean-vscode-win32-ia32'], packageTask('win32', 'ia32'));
gulp.task('vscode-win32-x64', ['optimize-vscode', 'clean-vscode-win32-x64'], packageTask('win32', 'x64'));
gulp.task('vscode-darwin', ['optimize-vscode', 'clean-vscode-darwin'], packageTask('darwin', null, { stats: true }));
gulp.task('vscode-linux-ia32', ['optimize-vscode', 'clean-vscode-linux-ia32'], packageTask('linux', 'ia32'));
gulp.task('vscode-linux-x64', ['optimize-vscode', 'clean-vscode-linux-x64'], packageTask('linux', 'x64'));
gulp.task('vscode-linux-arm', ['optimize-vscode', 'clean-vscode-linux-arm'], packageTask('linux', 'arm'));
gulp.task('vscode-linux-arm64', ['optimize-vscode', 'clean-vscode-linux-arm64'], packageTask('linux', 'arm64'));
gulp.task('vscode-win32-ia32-min', ['minify-vscode', 'clean-vscode-win32-ia32'], packageTask('win32', 'ia32', { minified: true }));
gulp.task('vscode-win32-x64-min', ['minify-vscode', 'clean-vscode-win32-x64'], packageTask('win32', 'x64', { minified: true }));
gulp.task('vscode-darwin-min', ['minify-vscode', 'clean-vscode-darwin'], packageTask('darwin', null, { minified: true, stats: true }));
gulp.task('vscode-linux-ia32-min', ['minify-vscode', 'clean-vscode-linux-ia32'], packageTask('linux', 'ia32', { minified: true }));
gulp.task('vscode-linux-x64-min', ['minify-vscode', 'clean-vscode-linux-x64'], packageTask('linux', 'x64', { minified: true }));
gulp.task('vscode-linux-arm-min', ['minify-vscode', 'clean-vscode-linux-arm'], packageTask('linux', 'arm', { minified: true }));
gulp.task('vscode-linux-arm64-min', ['minify-vscode', 'clean-vscode-linux-arm64'], packageTask('linux', 'arm64', { minified: true }));
// Transifex Localizations
const innoSetupConfig = {
'zh-cn': { codePage: 'CP936', defaultInfo: { name: 'Simplified Chinese', id: '$0804', } },
'zh-tw': { codePage: 'CP950', defaultInfo: { name: 'Traditional Chinese', id: '$0404' } },
'ko': { codePage: 'CP949', defaultInfo: { name: 'Korean', id: '$0412' } },
'ja': { codePage: 'CP932' },
'de': { codePage: 'CP1252' },
'fr': { codePage: 'CP1252' },
'es': { codePage: 'CP1252' },
'ru': { codePage: 'CP1251' },
'it': { codePage: 'CP1252' },
'pt-br': { codePage: 'CP1252' },
'hu': { codePage: 'CP1250' },
'tr': { codePage: 'CP1254' }
};
const apiHostname = process.env.TRANSIFEX_API_URL;
const apiName = process.env.TRANSIFEX_API_NAME;
const apiToken = process.env.TRANSIFEX_API_TOKEN;
gulp.task('vscode-translations-push', ['optimize-vscode'], function () {
const pathToMetadata = './out-vscode/nls.metadata.json';
const pathToExtensions = './extensions/*';
const pathToSetup = 'build/win32/**/{Default.isl,messages.en.isl}';
return es.merge(
gulp.src(pathToMetadata).pipe(i18n.createXlfFilesForCoreBundle()),
gulp.src(pathToSetup).pipe(i18n.createXlfFilesForIsl()),
gulp.src(pathToExtensions).pipe(i18n.createXlfFilesForExtensions())
).pipe(i18n.findObsoleteResources(apiHostname, apiName, apiToken)
).pipe(i18n.pushXlfFiles(apiHostname, apiName, apiToken));
});
gulp.task('vscode-translations-push-test', ['optimize-vscode'], function () {
const pathToMetadata = './out-vscode/nls.metadata.json';
const pathToExtensions = './extensions/*';
const pathToSetup = 'build/win32/**/{Default.isl,messages.en.isl}';
return es.merge(
gulp.src(pathToMetadata).pipe(i18n.createXlfFilesForCoreBundle()),
gulp.src(pathToSetup).pipe(i18n.createXlfFilesForIsl()),
gulp.src(pathToExtensions).pipe(i18n.createXlfFilesForExtensions())
).pipe(i18n.findObsoleteResources(apiHostname, apiName, apiToken)
).pipe(vfs.dest('../vscode-transifex-input'));
});
gulp.task('vscode-translations-pull', function () {
return es.merge([...i18n.defaultLanguages, ...i18n.extraLanguages].map(language => {
let includeDefault = !!innoSetupConfig[language.id].defaultInfo;
return i18n.pullSetupXlfFiles(apiHostname, apiName, apiToken, language, includeDefault).pipe(vfs.dest(`../vscode-localization/${language.id}/setup`));
}));
});
gulp.task('vscode-translations-import', function () {
return es.merge([...i18n.defaultLanguages, ...i18n.extraLanguages].map(language => {
return gulp.src(`../vscode-localization/${language.id}/setup/*/*.xlf`)
.pipe(i18n.prepareIslFiles(language, innoSetupConfig[language.id]))
.pipe(vfs.dest(`./build/win32/i18n`));
}));
});
// Sourcemaps
gulp.task('upload-vscode-sourcemaps', ['vscode-darwin-min', 'minify-vscode'], () => {
const vs = gulp.src('out-vscode-min/**/*.map', { base: 'out-vscode-min' })
.pipe(es.mapSync(f => {
f.path = `${f.base}/core/${f.relative}`;
return f;
}));
const extensionsOut = gulp.src('extensions/**/out/**/*.map', { base: '.' });
const extensionsDist = gulp.src('extensions/**/dist/**/*.map', { base: '.' });
const res = es.merge(vs, extensionsOut, extensionsDist)
.pipe(es.through(function (data) {
// debug
console.log('Uploading Sourcemap', data.relative);
this.emit('data', data);
}))
.pipe(azure.upload({
account: process.env.AZURE_STORAGE_ACCOUNT,
key: process.env.AZURE_STORAGE_ACCESS_KEY,
container: 'sourcemaps',
prefix: commit + '/'
}));
res.on('error', (err) => {
console.log('ERROR uploading sourcemaps');
console.error(err);
});
res.on('end', () => {
console.log('Completed uploading sourcemaps');
});
return res;
});
const allConfigDetailsPath = path.join(os.tmpdir(), 'configuration.json');
gulp.task('upload-vscode-configuration', ['generate-vscode-configuration'], () => {
if (!shouldSetupSettingsSearch()) {
const branch = process.env.BUILD_SOURCEBRANCH;
console.log(`Only runs on master and release branches, not ${branch}`);
return;
}
if (!fs.existsSync(allConfigDetailsPath)) {
throw new Error(`configuration file at ${allConfigDetailsPath} does not exist`);
}
const settingsSearchBuildId = getSettingsSearchBuildId(packageJson);
if (!settingsSearchBuildId) {
throw new Error('Failed to compute build number');
}
return gulp.src(allConfigDetailsPath)
.pipe(azure.upload({
account: process.env.AZURE_STORAGE_ACCOUNT,
key: process.env.AZURE_STORAGE_ACCESS_KEY,
container: 'configuration',
prefix: `${settingsSearchBuildId}/${commit}/`
}));
});
function shouldSetupSettingsSearch() {
const branch = process.env.BUILD_SOURCEBRANCH;
return branch && (/\/master$/.test(branch) || branch.indexOf('/release/') >= 0);
}
function getSettingsSearchBuildId(packageJson) {
try {
const branch = process.env.BUILD_SOURCEBRANCH;
const branchId = branch.indexOf('/release/') >= 0 ? 0 :
/\/master$/.test(branch) ? 1 :
2; // Some unexpected branch
const out = cp.execSync(`git rev-list HEAD --count`);
const count = parseInt(out.toString());
// <version number><commit count><branchId (avoid unlikely conflicts)>
// 1.25.1, 1,234,567 commits, master = 1250112345671
return util.versionStringToNumber(packageJson.version) * 1e8 + count * 10 + branchId;
} catch (e) {
throw new Error('Could not determine build number: ' + e.toString());
}
}
// This task is only run for the MacOS build
gulp.task('generate-vscode-configuration', () => {
return new Promise((resolve, reject) => {
const buildDir = process.env['AGENT_BUILDDIRECTORY'];
if (!buildDir) {
return reject(new Error('$AGENT_BUILDDIRECTORY not set'));
}
if (process.env.VSCODE_QUALITY !== 'insider' && process.env.VSCODE_QUALITY !== 'stable') {
return resolve();
}
const userDataDir = path.join(os.tmpdir(), 'tmpuserdata');
const extensionsDir = path.join(os.tmpdir(), 'tmpextdir');
const appName = process.env.VSCODE_QUALITY === 'insider' ? 'Visual\\ Studio\\ Code\\ -\\ Insiders.app' : 'Visual\\ Studio\\ Code.app';
const appPath = path.join(buildDir, `VSCode-darwin/${appName}/Contents/Resources/app/bin/code`);
const codeProc = cp.exec(`${appPath} --export-default-configuration='${allConfigDetailsPath}' --wait --user-data-dir='${userDataDir}' --extensions-dir='${extensionsDir}'`);
const timer = setTimeout(() => {
codeProc.kill();
reject(new Error('export-default-configuration process timed out'));
}, 10 * 1000);
codeProc.stdout.on('data', d => console.log(d.toString()));
codeProc.stderr.on('data', d => console.log(d.toString()));
codeProc.on('exit', () => {
clearTimeout(timer);
resolve();
});
codeProc.on('error', err => {
clearTimeout(timer);
reject(err);
});
});
});
| build/gulpfile.vscode.js | 1 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.9985218644142151,
0.0478220172226429,
0.00016183749539777637,
0.00017101150297094136,
0.21227221190929413
] |
{
"id": 0,
"code_window": [
"\tconst extensionsOut = gulp.src('extensions/**/out/**/*.map', { base: '.' });\n",
"\tconst extensionsDist = gulp.src('extensions/**/dist/**/*.map', { base: '.' });\n",
"\n",
"\tconst res = es.merge(vs, extensionsOut, extensionsDist)\n",
"\t\t.pipe(es.through(function (data) {\n",
"\t\t\t// debug\n",
"\t\t\tconsole.log('Uploading Sourcemap', data.relative);\n",
"\t\t\tthis.emit('data', data);\n",
"\t\t}))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn es.merge(vs, extensionsOut, extensionsDist)\n"
],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 516
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
var assert = require("assert");
var i18n = require("../i18n");
suite('XLF Parser Tests', function () {
var sampleXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &</source></trans-unit></body></file></xliff>';
var sampleTranslatedXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" target-language="ru" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source><target>Кнопка #1</target></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &</source><target>Кнопка #2 &</target></trans-unit></body></file></xliff>';
var originalFilePath = 'vs/base/common/keybinding';
var keys = ['key1', 'key2'];
var messages = ['Key #1', 'Key #2 &'];
var translatedMessages = { key1: 'Кнопка #1', key2: 'Кнопка #2 &' };
test('Keys & messages to XLF conversion', function () {
var xlf = new i18n.XLF('vscode-workbench');
xlf.addFile(originalFilePath, keys, messages);
var xlfString = xlf.toString();
assert.strictEqual(xlfString.replace(/\s{2,}/g, ''), sampleXlf);
});
test('XLF to keys & messages conversion', function () {
i18n.XLF.parse(sampleTranslatedXlf).then(function (resolvedFiles) {
assert.deepEqual(resolvedFiles[0].messages, translatedMessages);
assert.strictEqual(resolvedFiles[0].originalFilePath, originalFilePath);
});
});
test('JSON file source path to Transifex resource match', function () {
var editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench';
var platform = { name: 'vs/platform', project: editorProject }, editorContrib = { name: 'vs/editor/contrib', project: editorProject }, editor = { name: 'vs/editor', project: editorProject }, base = { name: 'vs/base', project: editorProject }, code = { name: 'vs/code', project: workbenchProject }, workbenchParts = { name: 'vs/workbench/parts/html', project: workbenchProject }, workbenchServices = { name: 'vs/workbench/services/files', project: workbenchProject }, workbench = { name: 'vs/workbench', project: workbenchProject };
assert.deepEqual(i18n.getResource('vs/platform/actions/browser/menusExtensionPoint'), platform);
assert.deepEqual(i18n.getResource('vs/editor/contrib/clipboard/browser/clipboard'), editorContrib);
assert.deepEqual(i18n.getResource('vs/editor/common/modes/modesRegistry'), editor);
assert.deepEqual(i18n.getResource('vs/base/common/errorMessage'), base);
assert.deepEqual(i18n.getResource('vs/code/electron-main/window'), code);
assert.deepEqual(i18n.getResource('vs/workbench/parts/html/browser/webview'), workbenchParts);
assert.deepEqual(i18n.getResource('vs/workbench/services/files/node/fileService'), workbenchServices);
assert.deepEqual(i18n.getResource('vs/workbench/browser/parts/panel/panelActions'), workbench);
});
});
| build/lib/test/i18n.test.js | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017383114027325064,
0.0001712004013825208,
0.0001687888434389606,
0.00017154618399217725,
0.0000018160538957090466
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.