hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
" return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);\n",
" }\n",
"\n",
" @Method()\n",
" activateFromTab() {\n",
" return activateFromTabImpl(this);\n",
" }\n",
"\n",
" canSwipeBack(): boolean {\n",
" return (this.swipeBackEnabled &&\n",
" // this.childNavs.length === 0 &&\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" activateFromTab(tabAlreadySelected: boolean) {\n",
" return activateFromTabImpl(this, tabAlreadySelected);\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 267
} | @import "../../themes/ionic.globals.md";
$back-button-md-button-color: $toolbar-md-text-color !default;
| packages/core/src/components/back-button/back-button.md.vars.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.0001755752309691161,
0.0001755752309691161,
0.0001755752309691161,
0.0001755752309691161,
0
]
|
{
"id": 0,
"code_window": [
" return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);\n",
" }\n",
"\n",
" @Method()\n",
" activateFromTab() {\n",
" return activateFromTabImpl(this);\n",
" }\n",
"\n",
" canSwipeBack(): boolean {\n",
" return (this.swipeBackEnabled &&\n",
" // this.childNavs.length === 0 &&\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" activateFromTab(tabAlreadySelected: boolean) {\n",
" return activateFromTabImpl(this, tabAlreadySelected);\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 267
} | @import "../../themes/ionic.globals.ios";
// iOS Title
// --------------------------------------------------
/// @prop - Font size of the toolbar title
$toolbar-ios-title-font-size: 17px !default;
/// @prop - Font weight of the toolbar title
$toolbar-ios-title-font-weight: 600 !default;
/// @prop - Text alignment of the toolbar title
$toolbar-ios-title-text-align: center !default;
/// @prop - Text color of the toolbar title
$toolbar-ios-title-text-color: $toolbar-ios-text-color !default;
| packages/core/src/components/title/title.ios.vars.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.00017740785551723093,
0.00017674369155429304,
0.00017607952759135514,
0.00017674369155429304,
6.641639629378915e-7
]
|
{
"id": 1,
"code_window": [
" }\n",
" return nav.routerDelegate.pushUrlState(url);\n",
"}\n",
"\n",
"export function activateFromTabImpl(nav: Nav): Promise<any> {\n",
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function activateFromTabImpl(nav: Nav, tabAlreadySelected: boolean): Promise<any> {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 630
} | import { Component, Element, Event, EventEmitter, Listen, Method, Prop, Watch } from '@stencil/core';
import {
Animation,
AnimationController,
AnimationOptions,
ComponentDataPair,
Config,
EscapeHatch,
ExternalNavData,
FrameworkDelegate,
NavOptions,
NavOutlet,
NavResult,
PublicNav,
PublicViewController,
RouterDelegate,
RouterEntries,
Transition,
TransitionInstruction,
} from '../../index';
import { ViewController } from './view-controller';
import {
DIRECTION_BACK,
DIRECTION_FORWARD,
STATE_ATTACHED,
STATE_DESTROYED,
STATE_NEW,
VIEW_ID_START,
destroyTransition,
getActiveImpl,
getFirstView,
getHydratedTransition,
getLastView,
getNextNavId,
getNextTransitionId,
getParentTransitionId,
getPreviousImpl,
getViews,
isViewController,
setZIndex,
toggleHidden,
transitionFactory
} from './nav-utils';
import { DomFrameworkDelegate } from '../../utils/dom-framework-delegate';
import { DomRouterDelegate } from '../../utils/dom-router-delegate';
import {
assert,
focusOutActiveElement,
isDef,
isNumber,
isParentTab,
normalizeUrl,
} from '../../utils/helpers';
import { buildIOSTransition } from './transitions/transition.ios';
import { buildMdTransition } from './transitions/transition.md';
import { GestureDetail } from '../gesture/gesture';
const transitionQueue = new Map<number, TransitionInstruction[]>();
const allTransitionsCompleteHandlerQueue = new Map<number, Function[]>();
/* it is very important to keep this class in sync with ./nav-interface interface */
@Component({
tag: 'ion-nav',
styleUrl: 'nav.scss'
})
export class Nav implements PublicNav, NavOutlet {
@Element() element: HTMLElement;
@Event() navInit: EventEmitter<NavEventDetail>;
@Event() ionNavChanged: EventEmitter<NavEventDetail>;
useRouter = false;
navId = getNextNavId();
routes: RouterEntries = [];
parent: Nav = null;
views: ViewController[] = [];
transitioning = false;
destroyed = false;
transitionId = NOT_TRANSITIONING_TRANSITION_ID;
initialized = false;
sbTrns: any; // TODO Transition
childNavs?: Nav[];
urlExternalNavMap = new Map<string, ExternalNavData>();
@Prop() mode: string;
@Prop() root: any;
@Prop() delegate: FrameworkDelegate;
@Prop() routerDelegate: RouterDelegate;
@Prop() useUrls = false;
@Prop({ context: 'config' }) config: Config;
@Prop({ connect: 'ion-animation-controller' }) animationCtrl: AnimationController;
@Prop() lazy = false;
@Prop() swipeBackEnabled = true;
constructor() {
this.navId = getNextNavId();
}
componentDidLoad() {
return componentDidLoadImpl(this);
}
@Watch('root')
updateRootComponent(): Promise<NavResult> {
if (this.initialized) {
return this.setRoot(this.root);
}
return Promise.resolve(null);
}
@Method()
getViews(): PublicViewController[] {
return getViews(this);
}
@Method()
push(component: any, data?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return pushImpl(this, component, data, opts, escapeHatch);
}
@Method()
pop(opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popImpl(this, opts, escapeHatch);
}
@Method()
setRoot(component: any, data?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return setRootImpl(this, component, data, opts, escapeHatch);
}
@Method()
insert(insertIndex: number, page: any, params?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return insertImpl(this, insertIndex, page, params, opts, escapeHatch);
}
@Method()
insertPages(insertIndex: number, insertPages: any[], opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return insertPagesImpl(this, insertIndex, insertPages, opts, escapeHatch);
}
@Method()
popToRoot(opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popToRootImpl(this, opts, escapeHatch);
}
@Method()
popTo(indexOrViewCtrl: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popToImpl(this, indexOrViewCtrl, opts, escapeHatch);
}
@Method()
removeIndex(startIndex: number, removeCount?: number, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return removeImpl(this, startIndex, removeCount, opts, escapeHatch);
}
@Method()
removeView(viewController: PublicViewController, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return removeViewImpl(this, viewController, opts, escapeHatch);
}
@Method()
setPages(componentDataPairs: ComponentDataPair[], opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return setPagesImpl(this, componentDataPairs, opts, escapeHatch);
}
@Method()
getActive(): PublicViewController {
return getActiveImpl(this);
}
@Method()
getPrevious(view?: PublicViewController): PublicViewController {
return getPreviousImpl(this, view as ViewController);
}
@Method()
canGoBack(): boolean {
return canGoBackImpl(this);
}
@Method()
first(): PublicViewController {
return getFirstView(this);
}
@Method()
last(): PublicViewController {
return getLastView(this);
}
@Method()
setRouteId(id: string, _: any = {}, direction: number): Promise<boolean> {
const active = this.getActive();
if (active && active.component === id) {
return Promise.resolve(false);
}
if (direction === 1) {
return this.push(id).then(() => true);
} else if (direction === -1 && this._canGoBack(id)) {
return this.pop().then(() => true);
}
return this.setRoot(id).then(() => true);
}
private _canGoBack(id: any) {
if (!this.canGoBack()) {
return false;
}
const view = this.views[this.views.length - 1];
return view.component === id;
}
@Method()
getRouteId(): string | null {
const element = this.getContentElement();
if (element) {
return element.tagName;
}
return null;
}
@Method()
getContentElement(): HTMLElement {
const active = getActiveImpl(this);
if (active) {
return active.element;
}
return null;
}
@Method()
getChildNavs(): PublicNav[] {
return this.childNavs || [];
}
@Method()
isTransitioning() {
return this.transitionId >= 0;
}
@Method()
getId() {
return this.navId;
}
@Method()
setParent(parent: Nav) {
this.parent = parent;
}
@Method()
onAllTransitionsComplete() {
return allTransitionsCompleteImpl(this);
}
@Method()
reconcileFromExternalRouter(component: any, data: any = {}, escapeHatch: EscapeHatch, isTopLevel: boolean) {
return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);
}
@Method()
activateFromTab() {
return activateFromTabImpl(this);
}
canSwipeBack(): boolean {
return (this.swipeBackEnabled &&
// this.childNavs.length === 0 &&
!this.isTransitioning() &&
// this._app.isEnabled() &&
this.canGoBack());
}
swipeBackStart() {
// default the direction to "back";
const opts: NavOptions = {
direction: DIRECTION_BACK,
progressAnimation: true
};
return popImpl(this, opts, {});
}
swipeBackProgress(detail: GestureDetail) {
if (!this.sbTrns) {
return;
}
// continue to disable the app while actively dragging
// this._app.setEnabled(false, ACTIVE_TRANSITION_DEFAULT);
// this.setTransitioning(true);
const delta = detail.deltaX;
const stepValue = delta / window.innerWidth;
// set the transition animation's progress
this.sbTrns.progressStep(stepValue);
}
swipeBackEnd(detail: GestureDetail) {
if (!this.sbTrns) {
return;
}
// the swipe back gesture has ended
const delta = detail.deltaX;
const width = window.innerWidth;
const stepValue = delta / width;
const velocity = detail.velocityX;
const z = width / 2.0;
const shouldComplete = (velocity >= 0)
&& (velocity > 0.2 || detail.deltaX > z);
const missing = shouldComplete ? 1 - stepValue : stepValue;
const missingDistance = missing * width;
let realDur = 0;
if (missingDistance > 5) {
const dur = missingDistance / Math.abs(velocity);
realDur = Math.min(dur, 300);
}
this.sbTrns.progressEnd(shouldComplete, stepValue, realDur);
}
@Listen('navInit')
navInitialized(event: NavEvent) {
navInitializedImpl(this, event);
}
render() {
const dom = [];
if (this.swipeBackEnabled) {
dom.push(<ion-gesture
canStart={this.canSwipeBack.bind(this)}
onStart={this.swipeBackStart.bind(this)}
onMove={this.swipeBackProgress.bind(this)}
onEnd={this.swipeBackEnd.bind(this)}
gestureName='goback-swipe'
gesturePriority={10}
type='pan'
direction='x'
threshold={10}
attachTo='body'/>);
}
if (this.mode === 'ios') {
dom.push(<div class='nav-decor'/>);
}
dom.push(<slot></slot>);
return dom;
}
}
export function componentDidLoadImpl(nav: Nav) {
if (nav.initialized) {
return;
}
nav.initialized = true;
nav.navInit.emit();
if (!nav.useRouter) {
if (nav.root && !nav.lazy) {
nav.setRoot(nav.root);
}
}
}
export async function pushImpl(nav: Nav, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return push(nav, nav.delegate, animation, component, data, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function popImpl(nav: Nav, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return pop(nav, nav.delegate, animation, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function setRootImpl(nav: Nav, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return setRoot(nav, nav.delegate, animation, component, data, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function insertImpl(nav: Nav, insertIndex: number, page: any, params: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return insert(nav, nav.delegate, animation, insertIndex, page, params, opts, escapeHatch);
}
export async function insertPagesImpl(nav: Nav, insertIndex: number, pagesToInsert: any[], opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return insertPages(nav, nav.delegate, animation, insertIndex, pagesToInsert, opts, escapeHatch);
}
export async function popToRootImpl(nav: Nav, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return popToRoot(nav, nav.delegate, animation, opts, escapeHatch);
}
export async function popToImpl(nav: Nav, indexOrViewCtrl: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return popTo(nav, nav.delegate, animation, indexOrViewCtrl, opts, escapeHatch);
}
export async function removeImpl(nav: Nav, startIndex: number, removeCount: number, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return remove(nav, nav.delegate, animation, startIndex, removeCount, opts, escapeHatch);
}
export async function removeViewImpl(nav: Nav, viewController: PublicViewController, opts: NavOptions, escapeHatch?: any) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return removeView(nav, nav.delegate, animation, viewController as ViewController, opts, escapeHatch);
}
export async function setPagesImpl(nav: Nav, componentDataPairs: ComponentDataPair[], opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return setPages(nav, nav.delegate, animation, componentDataPairs, opts, escapeHatch, null);
}
export function canGoBackImpl(nav: Nav) {
return nav.views && nav.views.length > 1;
}
export function navInitializedImpl(potentialParent: Nav, event: NavEvent) {
if ((potentialParent.element as any as HTMLIonNavElement) !== event.target) {
// set the parent on the child nav that dispatched the event
event.target.setParent(potentialParent);
if (!potentialParent.childNavs) {
potentialParent.childNavs = [];
}
potentialParent.childNavs.push((event.detail as Nav));
// kill the event so it doesn't propagate further
event.stopPropagation();
}
}
export function hydrateAnimationController(animationController: AnimationController): Promise<Animation> {
return animationController.create();
}
// public api
export function push(nav: Nav, delegate: FrameworkDelegate, animation: Animation, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: component,
insertStart: -1,
insertViews: [{component, data}],
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: PUSH
});
}
export function insert(nav: Nav, delegate: FrameworkDelegate, animation: Animation, insertIndex: number, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: component,
insertStart: insertIndex,
insertViews: [{ component, data }],
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'insert'
});
}
export function insertPages(nav: Nav, delegate: FrameworkDelegate, animation: Animation, insertIndex: number, insertPages: any[], opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
insertStart: insertIndex,
insertViews: insertPages,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'insertPages'
});
}
export function pop(nav: Nav, delegate: FrameworkDelegate, animation: Animation, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: -1,
removeCount: 1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: POP
});
}
export function popToRoot(nav: Nav, delegate: FrameworkDelegate, animation: Animation, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: 1,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'popToRoot'
});
}
export function popTo(nav: Nav, delegate: FrameworkDelegate, animation: Animation, indexOrViewCtrl: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
const config: TransitionInstruction = {
component: null,
removeStart: -1,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'popTo'
};
if (isViewController(indexOrViewCtrl)) {
config.removeView = indexOrViewCtrl;
config.removeStart = 1;
} else if (isNumber(indexOrViewCtrl)) {
config.removeStart = indexOrViewCtrl + 1;
}
return preprocessTransaction(config);
}
export function remove(nav: Nav, delegate: FrameworkDelegate, animation: Animation, startIndex: number, removeCount = 1, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: startIndex,
removeCount: removeCount,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'remove'
});
}
export function removeView(nav: Nav, delegate: FrameworkDelegate, animation: Animation, viewController: ViewController, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeView: viewController,
removeStart: 0,
removeCount: 1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'removeView'
});
}
export function setRoot(nav: Nav, delegate: FrameworkDelegate, animation: Animation, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return setPages(nav, delegate, animation, [{ component, data }], opts, escapeHatch, SET_ROOT);
}
export function setPages(nav: Nav, delegate: FrameworkDelegate, animation: Animation, componentDataPairs: ComponentDataPair[], opts: NavOptions, escapeHatch: EscapeHatch, methodName: string): Promise<NavResult> {
if (!isDef(opts)) {
opts = {};
}
if (opts.animate !== true) {
opts.animate = false;
}
return preprocessTransaction({
component: componentDataPairs.length === 1 ? componentDataPairs[0].component : null,
insertStart: 0,
insertViews: componentDataPairs,
removeStart: 0,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: methodName ? methodName : 'setPages'
});
}
export function preprocessTransaction(ti: TransitionInstruction): Promise<NavResult> {
if (isUrl(ti.component)) {
if (ti.method === PUSH || ti.method === POP || ti.method === SET_ROOT) {
return navigateToUrl(ti.nav, normalizeUrl(ti.component), ti.method);
} else {
return Promise.reject(new Error('only push, pop, and setRoot methods support urls'));
}
}
const response = checkIfPopRedirectRequired(ti);
if (response.required) {
return navigateToUrl(ti.nav, response.url, POP);
}
return queueTransaction(ti);
}
export function isUrl(component: any): boolean {
return typeof component === 'string' && component.charAt(0) === '/';
}
export function navigateToUrl(nav: Nav, url: string, _method: string): Promise<any> {
if (!nav.routerDelegate) {
nav.routerDelegate = new DomRouterDelegate();
}
return nav.routerDelegate.pushUrlState(url);
}
export function activateFromTabImpl(nav: Nav): Promise<any> {
return nav.onAllTransitionsComplete().then(() => {
// if there is not a view set and it's not transitioning,
// go ahead and set the root
if (nav.getViews().length === 0 && !nav.isTransitioning()) {
return nav.setRoot(nav.root);
}
// okay, we have a view here, and it's almost certainly the correct view
// so what we need to do is update the browsers url to match what's in the top view
const viewController = nav.getActive() as ViewController;
return viewController && viewController.url ? navigateToUrl(nav, viewController.url, null) : Promise.resolve();
});
}
export function queueTransaction(ti: TransitionInstruction): Promise<NavResult> {
const promise = new Promise<NavResult>((resolve, reject) => {
ti.resolve = resolve;
ti.reject = reject;
});
if (!ti.delegate) {
ti.delegate = new DomFrameworkDelegate();
}
// Normalize empty
if (ti.insertViews && ti.insertViews.length === 0) {
ti.insertViews = undefined;
}
// Normalize empty
if (ti.insertViews && ti.insertViews.length === 0) {
ti.insertViews = undefined;
}
// Enqueue transition instruction
addToQueue(ti);
// if there isn't a transition already happening
// then this will kick off this transition
nextTransaction(ti.nav);
return promise;
}
export function nextTransaction(nav: Nav): Promise<any> {
if (nav.transitioning) {
return Promise.resolve();
}
const topTransaction = getTopTransaction(nav.navId);
if (!topTransaction) {
// cool, there are no transitions going for this nav
processAllTransitionCompleteQueue(nav.navId);
return Promise.resolve();
}
return doNav(nav, topTransaction);
}
export function checkIfPopRedirectRequired(ti: TransitionInstruction): IsRedirectRequired {
if (ti.method === POP) {
if (ti.escapeHatch.fromExternalRouter) {
// if the pop method is called from a router, that means the redirect already happened
// so just do a normal pop because the url is in a good place. Basically, the router is telling us to
// pop
return {
required: false
};
}
// check if we need to redirect to a url for the pop operation
const popToIndex = ti.nav.views.length - 2;
if (popToIndex >= 0) {
const viewController = ti.nav.views[popToIndex];
return {
required: viewController.fromExternalRouter,
url: viewController.url
};
}
}
return {
required: false,
};
}
export function processAllTransitionCompleteQueue(navId: number) {
const queue = allTransitionsCompleteHandlerQueue.get(navId) || [];
for (const callback of queue) {
callback();
}
allTransitionsCompleteHandlerQueue.set(navId, []);
}
export function allTransitionsCompleteImpl(nav: Nav) {
return new Promise((resolve) => {
const queue = transitionQueue.get(nav.navId) || [];
if (queue.length) {
// there are pending transitions, so queue it up and we'll be notified when it's done
const handlers = allTransitionsCompleteHandlerQueue.get(nav.navId) || [];
handlers.push(resolve);
return allTransitionsCompleteHandlerQueue.set(nav.navId, handlers);
}
// there are no pending transitions, so just resolve right away
return resolve();
});
}
export function doNav(nav: Nav, ti: TransitionInstruction) {
let enteringView: ViewController;
let leavingView: ViewController;
return initializeViewBeforeTransition(ti).then(([_enteringView, _leavingView]) => {
enteringView = _enteringView;
leavingView = _leavingView;
return attachViewToDom(nav, enteringView, ti);
}).then(() => {
return loadViewAndTransition(nav, enteringView, leavingView, ti);
}).then(() => {
nav.ionNavChanged.emit({ isPop: ti.method === 'pop' });
return successfullyTransitioned(ti);
}).catch((err: Error) => {
return transitionFailed(err, ti);
});
}
export function successfullyTransitioned(ti: TransitionInstruction) {
const queue = getQueue(ti.id);
if (!queue) {
// TODO, make throw error in the future
return fireError(new Error('Queue is null, the nav must have been destroyed'), ti);
}
ti.nav.initialized = true;
ti.nav.transitionId = NOT_TRANSITIONING_TRANSITION_ID;
ti.nav.transitioning = false;
// TODO - check if it's a swipe back
// kick off next transition for this nav I guess
nextTransaction(ti.nav);
ti.resolve({
successful: true,
mountingData: ti.mountingData
});
}
export function transitionFailed(error: Error, ti: TransitionInstruction) {
const queue = getQueue(ti.nav.navId);
if (!queue) {
// TODO, make throw error in the future
return fireError(new Error('Queue is null, the nav must have been destroyed'), ti);
}
ti.nav.transitionId = null;
resetQueue(ti.nav.navId);
ti.nav.transitioning = false;
// TODO - check if it's a swipe back
// kick off next transition for this nav I guess
nextTransaction(ti.nav);
fireError(error, ti);
}
export function fireError(error: Error, ti: TransitionInstruction) {
if (ti.reject && !ti.nav.destroyed) {
ti.reject(error);
} else {
ti.resolve({
successful: false,
mountingData: ti.mountingData
});
}
}
export function loadViewAndTransition(nav: Nav, enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction) {
if (!ti.requiresTransition) {
// transition is not required, so we are already done!
// they're inserting/removing the views somewhere in the middle or
// beginning, so visually nothing needs to animate/transition
// resolve immediately because there's no animation that's happening
return Promise.resolve();
}
const transitionId = getParentTransitionId(nav);
nav.transitionId = transitionId >= 0 ? transitionId : getNextTransitionId();
// create the transition options
const animationOpts: AnimationOptions = {
animation: ti.opts.animation,
direction: ti.opts.direction,
duration: (ti.opts.animate === false ? 0 : ti.opts.duration),
easing: ti.opts.easing,
isRTL: false, // TODO
ev: ti.opts.event,
};
const emptyTransition = transitionFactory(ti.animation);
return getHydratedTransition(animationOpts.animation, nav.config, nav.transitionId, emptyTransition, enteringView, leavingView, animationOpts, getDefaultTransition(nav.config))
.then((transition) => {
if (nav.sbTrns) {
nav.sbTrns.destroy();
nav.sbTrns = null;
}
// it's a swipe to go back transition
if (transition.isRoot() && ti.opts.progressAnimation) {
nav.sbTrns = transition;
}
transition.start();
return executeAsyncTransition(nav, transition, enteringView, leavingView, ti.delegate, ti.opts, ti.nav.config.getBoolean('animate'));
});
}
export function executeAsyncTransition(nav: Nav, transition: Transition, enteringView: ViewController, leavingView: ViewController, delegate: FrameworkDelegate, opts: NavOptions, configShouldAnimate: boolean): Promise<void> {
assert(nav.transitioning, 'must be transitioning');
nav.transitionId = NOT_TRANSITIONING_TRANSITION_ID;
setZIndex(nav, enteringView, leavingView, opts.direction);
// always ensure the entering view is viewable
// ******** DOM WRITE ****************
// TODO, figure out where we want to read this data from
enteringView && toggleHidden(enteringView.element, false);
// always ensure the leaving view is viewable
// ******** DOM WRITE ****************
leavingView && toggleHidden(leavingView.element, false);
const isFirstPage = !nav.initialized && nav.views.length === 1;
const shouldNotAnimate = isFirstPage;
if (configShouldAnimate || shouldNotAnimate) {
opts.animate = false;
}
if (opts.animate === false) {
// if it was somehow set to not animation, then make the duration zero
transition.duration(0);
}
transition.beforeAddRead(() => {
fireViewWillLifecycles(enteringView, leavingView);
});
// get the set duration of this transition
const duration = transition.getDuration();
// create a callback for when the animation is done
const transitionCompletePromise = new Promise(resolve => {
transition.onFinish(resolve);
});
if (transition.isRoot()) {
if (duration > DISABLE_APP_MINIMUM_DURATION && opts.disableApp !== false) {
// if this transition has a duration and this is the root transition
// then set that the app is actively disabled
// this._app.setEnabled(false, duration + ACTIVE_TRANSITION_OFFSET, opts.minClickBlockDuration);
} else {
console.debug('transition is running but app has not been disabled');
}
if (opts.progressAnimation) {
// this is a swipe to go back, just get the transition progress ready
// kick off the swipe animation start
transition.progressStart();
} else {
// only the top level transition should actually start "play"
// kick it off and let it play through
// ******** DOM WRITE ****************
transition.play();
}
}
return transitionCompletePromise.then(() => {
return transitionFinish(nav, transition, delegate, opts);
});
}
export function transitionFinish(nav: Nav, transition: Transition, delegate: FrameworkDelegate, opts: NavOptions): Promise<any> {
let promise: Promise<any> = null;
if (transition.hasCompleted) {
transition.enteringView && transition.enteringView.didEnter();
transition.leavingView && transition.leavingView.didLeave();
promise = cleanUpView(nav, delegate, transition.enteringView);
} else {
promise = cleanUpView(nav, delegate, transition.leavingView);
}
return promise.then(() => {
if (transition.isRoot()) {
destroyTransition(transition.transitionId);
// TODO - enable app
nav.transitioning = false;
// TODO - navChange on the deep linker used to be called here
if (opts.keyboardClose !== false) {
focusOutActiveElement();
}
}
});
}
export function cleanUpView(nav: Nav, delegate: FrameworkDelegate, activeViewController: ViewController): Promise<any> {
if (nav.destroyed) {
return Promise.resolve();
}
const activeIndex = nav.views.indexOf(activeViewController);
const promises: Promise<any>[] = [];
for (let i = nav.views.length - 1; i >= 0; i--) {
const inactiveViewController = nav.views[i];
if (i > activeIndex) {
// this view comes after the active view
inactiveViewController.willUnload();
promises.push(destroyView(nav, delegate, inactiveViewController));
} else if ( i < activeIndex) {
// this view comes before the active view
// and it is not a portal then ensure it is hidden
toggleHidden(inactiveViewController.element, true);
}
// TODO - review existing z index code!
}
return Promise.all(promises);
}
export function fireViewWillLifecycles(enteringView: ViewController, leavingView: ViewController) {
leavingView && leavingView.willLeave(!enteringView);
enteringView && enteringView.willEnter();
}
export function attachViewToDom(nav: Nav, enteringView: ViewController, ti: TransitionInstruction): Promise<any> {
if (enteringView && enteringView.state === STATE_NEW) {
return ti.delegate.attachViewToDom(nav.element, enteringView.component, enteringView.data, [], ti.escapeHatch).then((mountingData) => {
ti.mountingData = mountingData;
Object.assign(enteringView, mountingData);
enteringView.state = STATE_ATTACHED;
})
// implicit returns FTW
.then(() => waitForNewlyAttachedViewElementsToHydate(enteringView.element));
}
// it's in the wrong state, so don't attach and just return
return Promise.resolve();
}
export function waitForNewlyAttachedViewElementsToHydate(element: HTMLElement) {
// the element may or may not be a Stencil element
// so check if it has an `<ion-nav>`, `<ion-header>`, and `<ion-content>` for
// hydration
const promises: Promise<any>[] = [];
if ((element as any).componentOnReady) {
// it's a stencil element
promises.push((element as any).componentOnReady());
}
const navs = element.querySelectorAll('ion-nav');
for (let i = 0; i < navs.length; i++) {
const nav = navs.item(i);
promises.push((nav as any).componentOnReady());
}
// check for headers
const headers = element.querySelectorAll('ion-header');
for (let i = 0; i < headers.length; i++) {
const header = headers.item(i);
promises.push((header as any).componentOnReady());
}
// check for contents
const contents = element.querySelectorAll('ion-content');
for (let i = 0; i < contents.length; i++) {
const content = contents.item(i);
promises.push((content as any).componentOnReady());
}
// check for back buttons
const backButtons = element.querySelectorAll('ion-back-button');
for (let i = 0; i < backButtons.length; i++) {
const backButton = backButtons.item(i);
promises.push((backButton as any).componentOnReady());
}
return Promise.all(promises);
}
export function initializeViewBeforeTransition(ti: TransitionInstruction): Promise<ViewController[]> {
let leavingView: ViewController = null;
let enteringView: ViewController = null;
return startTransaction(ti).then(() => {
const viewControllers = convertComponentToViewController(ti);
ti.viewControllers = viewControllers;
leavingView = ti.nav.getActive() as ViewController;
enteringView = getEnteringView(ti, ti.nav, leavingView);
if (!leavingView && !enteringView) {
return Promise.reject(new Error('No views in the stack to remove'));
}
// mark state as initialized
// enteringView.state = STATE_INITIALIZED;
ti.requiresTransition = (ti.enteringRequiresTransition || ti.leavingRequiresTransition) && enteringView !== leavingView;
return testIfViewsCanLeaveAndEnter(enteringView, leavingView, ti);
}).then(() => {
return updateNavStacks(enteringView, leavingView, ti);
}).then(() => {
return [enteringView, leavingView];
});
}
export function updateNavStacks(enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction): Promise<any> {
return Promise.resolve().then(() => {
assert(!!(leavingView || enteringView), 'Both leavingView and enteringView are null');
assert(!!ti.resolve, 'resolve must be valid');
assert(!!ti.reject, 'reject must be valid');
const destroyQueue: ViewController[] = [];
ti.opts = ti.opts || {};
if (isDef(ti.removeStart)) {
assert(ti.removeStart >= 0, 'removeStart can not be negative');
assert(ti.removeStart >= 0, 'removeCount can not be negative');
for (let i = 0; i < ti.removeCount; i++) {
const view = ti.nav.views[i + ti.removeStart];
if (view && view !== enteringView && view !== leavingView) {
destroyQueue.push(view);
}
}
ti.opts.direction = ti.opts.direction || DIRECTION_BACK;
}
const finalBalance = ti.nav.views.length + (ti.insertViews ? ti.insertViews.length : 0) - (ti.removeCount ? ti.removeCount : 0);
assert(finalBalance >= 0, 'final balance can not be negative');
if (finalBalance === 0) {
console.warn(`You can't remove all the pages in the navigation stack. nav.pop() is probably called too many times.`);
throw new Error('Navigation stack needs at least one root page');
}
// At this point the transition can not be rejected, any throw should be an error
// there are views to insert
if (ti.viewControllers) {
// manually set the new view's id if an id was passed in the options
if (isDef(ti.opts.id)) {
enteringView.id = ti.opts.id;
}
// add the views to the stack
for (let i = 0; i < ti.viewControllers.length; i++) {
insertViewIntoNav(ti.nav, ti.viewControllers[i], ti.insertStart + i);
}
if (ti.enteringRequiresTransition) {
// default to forward if not already set
ti.opts.direction = ti.opts.direction || DIRECTION_FORWARD;
}
}
// if the views to be removed are in the beginning or middle
// and there is not a view that needs to visually transition out
// then just destroy them and don't transition anything
// batch all of lifecycles together
if (destroyQueue && destroyQueue.length) {
// TODO, figure out how the zone stuff should work in angular
for (const view of destroyQueue) {
view.willLeave(true);
view.didLeave();
view.willUnload();
}
const destroyQueuePromises: Promise<any>[] = [];
for (const viewController of destroyQueue) {
destroyQueuePromises.push(destroyView(ti.nav, ti.delegate, viewController));
}
return Promise.all(destroyQueuePromises);
}
return null;
})/*.then(() => {
// set which animation it should use if it wasn't set yet
if (ti.requiresTransition && !ti.opts.animation) {
ti.opts.animation = isDef(ti.removeStart)
? (leavingView || enteringView).getTransitionName(ti.opts.direction)
: (enteringView || leavingView).getTransitionName(ti.opts.direction);
}
});
*/
}
export function destroyView(nav: Nav, delegate: FrameworkDelegate, viewController: ViewController) {
return viewController.destroy(delegate).then(() => {
return removeViewFromList(nav, viewController);
});
}
export function removeViewFromList(nav: Nav, viewController: ViewController) {
assert(viewController.state === STATE_ATTACHED || viewController.state === STATE_DESTROYED, 'view state should be loaded or destroyed');
const index = nav.views.indexOf(viewController);
assert(index > -1, 'view must be part of the stack');
if (index >= 0) {
nav.views.splice(index, 1);
}
}
export function insertViewIntoNav(nav: Nav, view: ViewController, index: number) {
const existingIndex = nav.views.indexOf(view);
if (existingIndex > -1) {
// this view is already in the stack!!
// move it to its new location
assert(view.nav === nav, 'view is not part of the nav');
nav.views.splice(index, 0, nav.views.splice(existingIndex, 1)[0]);
} else {
assert(!view.nav, 'nav is used');
// this is a new view to add to the stack
// create the new entering view
view.nav = nav;
// give this inserted view an ID
viewIds++;
if (!view.id) {
view.id = `${nav.navId}-${viewIds}`;
}
// insert the entering view into the correct index in the stack
nav.views.splice(index, 0, view);
}
}
export function testIfViewsCanLeaveAndEnter(enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction) {
if (!ti.requiresTransition) {
return Promise.resolve();
}
const promises: Promise<any>[] = [];
if (leavingView) {
promises.push(lifeCycleTest(leavingView, 'Leave'));
}
if (enteringView) {
promises.push(lifeCycleTest(enteringView, 'Enter'));
}
if (promises.length === 0) {
return Promise.resolve();
}
// darn, async promises, gotta wait for them to resolve
return Promise.all(promises).then((values: any[]) => {
if (values.some(result => result === false)) {
ti.reject = null;
throw new Error('canEnter/Leave returned false');
}
});
}
export function lifeCycleTest(viewController: ViewController, enterOrLeave: string) {
const methodName = `ionViewCan${enterOrLeave}`;
if (viewController.instance && viewController.instance[methodName]) {
try {
const result = viewController.instance[methodName];
if (result instanceof Promise) {
return result;
}
return Promise.resolve(result !== false);
} catch (e) {
return Promise.reject(new Error(`Unexpected error when calling ${methodName}: ${e.message}`));
}
}
return Promise.resolve(true);
}
export function startTransaction(ti: TransitionInstruction): Promise<any> {
const viewsLength = ti.nav.views ? ti.nav.views.length : 0;
if (isDef(ti.removeView)) {
assert(isDef(ti.removeStart), 'removeView needs removeStart');
assert(isDef(ti.removeCount), 'removeView needs removeCount');
const index = ti.nav.views.indexOf(ti.removeView());
if (index < 0) {
return Promise.reject(new Error('The removeView was not found'));
}
ti.removeStart += index;
}
if (isDef(ti.removeStart)) {
if (ti.removeStart < 0) {
ti.removeStart = (viewsLength - 1);
}
if (ti.removeCount < 0) {
ti.removeCount = (viewsLength - ti.removeStart);
}
ti.leavingRequiresTransition = (ti.removeCount > 0) && ((ti.removeStart + ti.removeCount) === viewsLength);
}
if (isDef(ti.insertViews)) {
// allow -1 to be passed in to auto push it on the end
// and clean up the index if it's larger then the size of the stack
if (ti.insertStart < 0 || ti.insertStart > viewsLength) {
ti.insertStart = viewsLength;
}
ti.enteringRequiresTransition = (ti.insertStart === viewsLength);
}
ti.nav.transitioning = true;
return Promise.resolve();
}
export function getEnteringView(ti: TransitionInstruction, nav: Nav, leavingView: ViewController): ViewController {
if (ti.viewControllers && ti.viewControllers.length) {
// grab the very last view of the views to be inserted
// and initialize it as the new entering view
return ti.viewControllers[ti.viewControllers.length - 1];
}
if (isDef(ti.removeStart)) {
const removeEnd = ti.removeStart + ti.removeCount;
for (let i = nav.views.length - 1; i >= 0; i--) {
if ((i < ti.removeStart || i >= removeEnd) && nav.views[i] !== leavingView) {
return nav.views[i];
}
}
}
return null;
}
export function convertViewsToViewControllers(pairs: ComponentDataPair[], escapeHatch: EscapeHatch): ViewController[] {
return pairs.filter(pair => !!pair)
.map(pair => {
const applyEscapeHatch = pair === pairs[pairs.length - 1];
return new ViewController(pair.component, pair.data, applyEscapeHatch ? escapeHatch.fromExternalRouter : false, applyEscapeHatch ? escapeHatch.url : null);
});
}
export function convertComponentToViewController(ti: TransitionInstruction): ViewController[] {
if (ti.insertViews) {
assert(ti.insertViews.length > 0, 'length can not be zero');
const viewControllers = convertViewsToViewControllers(ti.insertViews, ti.escapeHatch);
assert(ti.insertViews.length === viewControllers.length, 'lengths does not match');
if (viewControllers.length === 0) {
throw new Error('No views to insert');
}
for (const viewController of viewControllers) {
if (viewController.nav && viewController.nav.navId !== ti.id) {
throw new Error('The view has already inserted into a different nav');
}
if (viewController.state === STATE_DESTROYED) {
throw new Error('The view has already been destroyed');
}
}
return viewControllers;
}
return [];
}
export function addToQueue(ti: TransitionInstruction) {
const list = transitionQueue.get(ti.id) || [];
list.push(ti);
transitionQueue.set(ti.id, list);
}
export function getQueue(id: number) {
return transitionQueue.get(id) || [];
}
export function resetQueue(id: number) {
transitionQueue.set(id, []);
}
export function getTopTransaction(id: number) {
const queue = getQueue(id);
if (!queue.length) {
return null;
}
const tmp = queue.concat();
const toReturn = tmp.shift();
transitionQueue.set(id, tmp);
return toReturn;
}
export function getDefaultTransition(config: Config) {
return config.get('mode') === 'ios' ? buildIOSTransition : buildMdTransition;
}
let viewIds = VIEW_ID_START;
const DISABLE_APP_MINIMUM_DURATION = 64;
const NOT_TRANSITIONING_TRANSITION_ID = -1;
export interface NavEvent extends CustomEvent {
target: HTMLIonNavElement;
detail: NavEventDetail;
}
export interface NavEventDetail {
isPop?: boolean;
}
export function getDefaultEscapeHatch(): EscapeHatch {
return {
fromExternalRouter: false,
};
}
export function reconcileFromExternalRouterImpl(nav: Nav, component: any, data: any = {}, escapeHatch: EscapeHatch, isTopLevel: boolean): Promise<NavResult> {
// check if the nav has an `<ion-tab>` as a parent
if (isParentTab(nav.element as any)) {
// check if the tab is selected
return updateTab(nav, component, data, escapeHatch, isTopLevel);
} else {
return updateNav(nav, component, data, escapeHatch, isTopLevel);
}
}
export function updateTab(nav: Nav, component: any, data: any, escapeHatch: EscapeHatch, isTopLevel: boolean) {
const tab = nav.element.parentElement as HTMLIonTabElement;
// yeah yeah, I know this is kind of ugly but oh well, I know the internal structure of <ion-tabs>
const tabs = tab.parentElement.parentElement as HTMLIonTabsElement;
return isTabSelected(tabs, tab).then((isSelected) => {
if (!isSelected) {
const promise = updateNav(nav, component, data, escapeHatch, false);
const app = document.querySelector('ion-app');
return app.componentOnReady().then(() => {
app.setExternalNavPromise(promise);
// okay, the tab is not selected, so we need to do a "switch" transition
// basically, we should update the nav, and then swap the tabs
return promise.then((navResult) => {
return tabs.select(tab).then(() => {
app.setExternalNavPromise(null);
return navResult;
});
});
});
}
// okay cool, the tab is already selected, so we want to see a transition
return updateNav(nav, component, data, escapeHatch, isTopLevel);
});
}
export function isTabSelected(tabsElement: HTMLIonTabsElement, tabElement: HTMLIonTabElement ): Promise<boolean> {
const promises: Promise<any>[] = [];
promises.push(tabsElement.componentOnReady());
promises.push(tabElement.componentOnReady());
return Promise.all(promises).then(() => {
return tabsElement.getSelected() === tabElement;
});
}
export function updateNav(nav: Nav,
component: any, data: any, escapeHatch: EscapeHatch, isTopLevel: boolean): Promise<NavResult> {
const url = location.pathname;
// check if the component is the top view
const activeViews = nav.getViews() as ViewController[];
if (activeViews.length === 0) {
// there isn't a view in the stack, so push one
return nav.setRoot(component, data, {}, escapeHatch);
}
const currentView = activeViews[activeViews.length - 1];
if (currentView.url === url) {
// the top view is already the component being activated, so there is no change needed
return Promise.resolve(null);
}
// check if the component is the previous view, if so, pop back to it
if (activeViews.length > 1) {
// there's at least two views in the stack
const previousView = activeViews[activeViews.length - 2];
if (previousView.url === url) {
// cool, we match the previous view, so pop it
return nav.pop(null, escapeHatch);
}
}
// check if the component is already in the stack of views, in which case we pop back to it
for (const view of activeViews) {
if (view.url === url) {
// cool, we found the match, pop back to that bad boy
return nav.popTo(view, null, escapeHatch);
}
}
// it's the top level nav, and it's not one of those other behaviors, so do a push so the user gets a chill animation
return nav.push(component, data, { animate: isTopLevel }, escapeHatch);
}
export interface IsRedirectRequired {
required: boolean;
url?: string;
}
export const POP = 'pop';
export const PUSH = 'push';
export const SET_ROOT = 'setRoot';
| packages/core/src/components/nav/nav.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.9989953637123108,
0.05678947642445564,
0.00016381061868742108,
0.0014466559514403343,
0.18509455025196075
]
|
{
"id": 1,
"code_window": [
" }\n",
" return nav.routerDelegate.pushUrlState(url);\n",
"}\n",
"\n",
"export function activateFromTabImpl(nav: Nav): Promise<any> {\n",
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function activateFromTabImpl(nav: Nav, tabAlreadySelected: boolean): Promise<any> {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 630
} | import {
Event,
NavigationCancel,
NavigationEnd,
NavigationError,
RouterState,
UrlTree
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import { AsyncActivateRoutes } from './async-activated-routes';
export function monkeyPatchRouter(router: any) {
router.activateRoutes = (state: Observable<{appliedUrl: string, state: RouterState, shouldActivate: boolean}>, storedState: RouterState,
storedUrl: UrlTree, id: number, url: UrlTree, rawUrl: UrlTree, skipLocationChange: boolean, replaceUrl: boolean, resolvePromise: any, rejectPromise: any) => {
// applied the new router state
// this operation has side effects
let navigationIsSuccessful: boolean;
const routes: AsyncActivateRoutes[] = [];
state
.forEach(({appliedUrl, state, shouldActivate}: any) => {
if (!shouldActivate || id !== router.navigationId) {
navigationIsSuccessful = false;
return;
}
router.currentUrlTree = appliedUrl;
router.rawUrlTree = router.urlHandlingStrategy.merge(router.currentUrlTree, rawUrl);
(router as{routerState: RouterState}).routerState = state;
if (!skipLocationChange) {
const path = router.urlSerializer.serialize(router.rawUrlTree);
if (router.location.isCurrentPathEqualTo(path) || replaceUrl) {
router.location.replaceState(path, '');
} else {
router.location.go(path, '');
}
}
routes.push(new AsyncActivateRoutes(router.routeReuseStrategy, state, storedState, (evt: Event) => router.triggerEvent(evt)))
})
.then(
() => {
const promises = routes.map(activatedRoute => activatedRoute.activate(router.rootContexts));
return Promise.all(promises)
.then(
() => {
navigationIsSuccessful = true;
}
);
}
)
.then(
() => {
if (navigationIsSuccessful) {
router.navigated = true;
router.lastSuccessfulId = id;
(router.events as Subject<Event>)
.next(new NavigationEnd(
id, router.serializeUrl(url), router.serializeUrl(router.currentUrlTree)));
resolvePromise(true);
} else {
router.resetUrlToCurrentUrlTree();
(router.events as Subject<Event>)
.next(new NavigationCancel(id, router.serializeUrl(url), ''));
resolvePromise(false);
}
},
(e: any) => {
if (isNavigationCancelingError(e)) {
router.navigated = true;
router.resetStateAndUrl(storedState, storedUrl, rawUrl);
(router.events as Subject<Event>)
.next(new NavigationCancel(id, router.serializeUrl(url), e.message));
resolvePromise(false);
} else {
router.resetStateAndUrl(storedState, storedUrl, rawUrl);
(router.events as any as Subject<Event>)
.next(new NavigationError(id, router.serializeUrl(url), e));
try {
resolvePromise(router.errorHandler(e));
} catch (ee) {
rejectPromise(ee);
}
}
});
};
}
function isNavigationCancelingError(error: any) {
return error && (/** @type {?} */ (error))[NAVIGATION_CANCELING_ERROR];
}
const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError'; | packages/angular/src/router/monkey-patch-router.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.0015666725812479854,
0.0006597726605832577,
0.00021089008077979088,
0.0004091310256626457,
0.00046406747424043715
]
|
{
"id": 1,
"code_window": [
" }\n",
" return nav.routerDelegate.pushUrlState(url);\n",
"}\n",
"\n",
"export function activateFromTabImpl(nav: Nav): Promise<any> {\n",
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function activateFromTabImpl(nav: Nav, tabAlreadySelected: boolean): Promise<any> {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 630
} | **Ionic version:** (check one with "x")
[ ] **1.x** (For Ionic 1.x issues, please use https://github.com/ionic-team/ionic-v1)
[ ] **2.x**
[ ] **3.x**
**I'm submitting a ...** (check one with "x")
[ ] bug report
[ ] feature request
[ ] support request => Please do not submit support requests here, use one of these channels: https://forum.ionicframework.com/ or http://ionicworldwide.herokuapp.com/
**Current behavior:**
<!-- Describe how the bug manifests. -->
**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
**Steps to reproduce:**
<!-- If you are able to illustrate the bug or feature request with an example, please provide steps to reproduce and if possible a demo using one of the following templates:
For Ionic V1 issues - http://plnkr.co/edit/Xo1QyAUx35ny1Xf9ODHx?p=preview
For Ionic issues - http://plnkr.co/edit/z0DzVL?p=preview
-->
**Related code:**
```
insert any relevant code here
```
**Other information:**
<!-- List any other information that is relevant to your issue. Stack traces, related issues, suggestions on how to fix, Stack Overflow links, forum links, etc. -->
**Ionic info:** (run `ionic info` from a terminal/cmd prompt and paste output below):
```
insert the output from ionic info here
```
| .github/ISSUE_TEMPLATE.md | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.0001735519035719335,
0.00016874265566002578,
0.00016529618005733937,
0.00016665627481415868,
0.000003374331754457671
]
|
{
"id": 1,
"code_window": [
" }\n",
" return nav.routerDelegate.pushUrlState(url);\n",
"}\n",
"\n",
"export function activateFromTabImpl(nav: Nav): Promise<any> {\n",
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function activateFromTabImpl(nav: Nav, tabAlreadySelected: boolean): Promise<any> {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 630
} | import { Component } from '@angular/core';
@Component({
selector: 'app-badge-page',
template: `
<ion-app>
<ion-page class="show-page">
<ion-header>
<ion-toolbar>
<ion-title>Badges</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>Badges Right</ion-list-header>
<ion-item>
<ion-badge slot="end" color="primary">99</ion-badge>
<ion-label>Default Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="end" color="primary">99</ion-badge>
<ion-label>Primary Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="end" color="secondary">99</ion-badge>
<ion-label>Secondary Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="end" color="danger">99</ion-badge>
<ion-label>Danger Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="end" color="light">99</ion-badge>
<ion-label>Light Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="end" color="dark">99</ion-badge>
<ion-label>Dark Badge</ion-label>
</ion-item>
<ion-item (click)="toggleColor()">
<ion-badge slot="end" [color]="dynamicColor">{{dynamicColor}}</ion-badge>
<ion-label>Dynamic Badge Color (toggle)</ion-label>
</ion-item>
</ion-list>
<ion-list>
<ion-list-header>Badges Left</ion-list-header>
<ion-item>
<ion-badge slot="start" color="primary">99</ion-badge>
<ion-label>Default Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="start" color="primary">99</ion-badge>
<ion-label>Primary Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="start" color="secondary">99</ion-badge>
<ion-label>Secondary Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="start" color="danger">99</ion-badge>
<ion-label>Danger Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="start" color="light">99</ion-badge>
<ion-label>Light Badge</ion-label>
</ion-item>
<ion-item>
<ion-badge slot="start" color="dark">99</ion-badge>
<ion-label>Dark Badge</ion-label>
</ion-item>
</ion-list>
</ion-content>
</ion-page>
</ion-app>
`
})
export class BadgePageComponent {
dynamicColor = 'primary';
constructor() {
}
toggleColor() {
if (this.dynamicColor === 'primary') {
this.dynamicColor = 'secondary';
} else if (this.dynamicColor === 'secondary') {
this.dynamicColor = 'danger';
} else {
this.dynamicColor = 'primary';
}
}
}
| packages/demos/angular/src/app/badge/badge-page.component.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.00017611293878871948,
0.0001723025634419173,
0.00016763083112891763,
0.00017258507432416081,
0.0000029303769224497955
]
|
{
"id": 2,
"code_window": [
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n",
" if (nav.getViews().length === 0 && !nav.isTransitioning()) {\n",
" return nav.setRoot(nav.root);\n",
" }\n",
"\n",
" // okay, we have a view here, and it's almost certainly the correct view\n",
" // so what we need to do is update the browsers url to match what's in the top view\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if ( (nav.getViews().length === 0 || tabAlreadySelected) && !nav.isTransitioning()) {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 634
} | import { Component, Element, Event, EventEmitter, Listen, Method, Prop, Watch } from '@stencil/core';
import {
Animation,
AnimationController,
AnimationOptions,
ComponentDataPair,
Config,
EscapeHatch,
ExternalNavData,
FrameworkDelegate,
NavOptions,
NavOutlet,
NavResult,
PublicNav,
PublicViewController,
RouterDelegate,
RouterEntries,
Transition,
TransitionInstruction,
} from '../../index';
import { ViewController } from './view-controller';
import {
DIRECTION_BACK,
DIRECTION_FORWARD,
STATE_ATTACHED,
STATE_DESTROYED,
STATE_NEW,
VIEW_ID_START,
destroyTransition,
getActiveImpl,
getFirstView,
getHydratedTransition,
getLastView,
getNextNavId,
getNextTransitionId,
getParentTransitionId,
getPreviousImpl,
getViews,
isViewController,
setZIndex,
toggleHidden,
transitionFactory
} from './nav-utils';
import { DomFrameworkDelegate } from '../../utils/dom-framework-delegate';
import { DomRouterDelegate } from '../../utils/dom-router-delegate';
import {
assert,
focusOutActiveElement,
isDef,
isNumber,
isParentTab,
normalizeUrl,
} from '../../utils/helpers';
import { buildIOSTransition } from './transitions/transition.ios';
import { buildMdTransition } from './transitions/transition.md';
import { GestureDetail } from '../gesture/gesture';
const transitionQueue = new Map<number, TransitionInstruction[]>();
const allTransitionsCompleteHandlerQueue = new Map<number, Function[]>();
/* it is very important to keep this class in sync with ./nav-interface interface */
@Component({
tag: 'ion-nav',
styleUrl: 'nav.scss'
})
export class Nav implements PublicNav, NavOutlet {
@Element() element: HTMLElement;
@Event() navInit: EventEmitter<NavEventDetail>;
@Event() ionNavChanged: EventEmitter<NavEventDetail>;
useRouter = false;
navId = getNextNavId();
routes: RouterEntries = [];
parent: Nav = null;
views: ViewController[] = [];
transitioning = false;
destroyed = false;
transitionId = NOT_TRANSITIONING_TRANSITION_ID;
initialized = false;
sbTrns: any; // TODO Transition
childNavs?: Nav[];
urlExternalNavMap = new Map<string, ExternalNavData>();
@Prop() mode: string;
@Prop() root: any;
@Prop() delegate: FrameworkDelegate;
@Prop() routerDelegate: RouterDelegate;
@Prop() useUrls = false;
@Prop({ context: 'config' }) config: Config;
@Prop({ connect: 'ion-animation-controller' }) animationCtrl: AnimationController;
@Prop() lazy = false;
@Prop() swipeBackEnabled = true;
constructor() {
this.navId = getNextNavId();
}
componentDidLoad() {
return componentDidLoadImpl(this);
}
@Watch('root')
updateRootComponent(): Promise<NavResult> {
if (this.initialized) {
return this.setRoot(this.root);
}
return Promise.resolve(null);
}
@Method()
getViews(): PublicViewController[] {
return getViews(this);
}
@Method()
push(component: any, data?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return pushImpl(this, component, data, opts, escapeHatch);
}
@Method()
pop(opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popImpl(this, opts, escapeHatch);
}
@Method()
setRoot(component: any, data?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return setRootImpl(this, component, data, opts, escapeHatch);
}
@Method()
insert(insertIndex: number, page: any, params?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return insertImpl(this, insertIndex, page, params, opts, escapeHatch);
}
@Method()
insertPages(insertIndex: number, insertPages: any[], opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return insertPagesImpl(this, insertIndex, insertPages, opts, escapeHatch);
}
@Method()
popToRoot(opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popToRootImpl(this, opts, escapeHatch);
}
@Method()
popTo(indexOrViewCtrl: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popToImpl(this, indexOrViewCtrl, opts, escapeHatch);
}
@Method()
removeIndex(startIndex: number, removeCount?: number, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return removeImpl(this, startIndex, removeCount, opts, escapeHatch);
}
@Method()
removeView(viewController: PublicViewController, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return removeViewImpl(this, viewController, opts, escapeHatch);
}
@Method()
setPages(componentDataPairs: ComponentDataPair[], opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return setPagesImpl(this, componentDataPairs, opts, escapeHatch);
}
@Method()
getActive(): PublicViewController {
return getActiveImpl(this);
}
@Method()
getPrevious(view?: PublicViewController): PublicViewController {
return getPreviousImpl(this, view as ViewController);
}
@Method()
canGoBack(): boolean {
return canGoBackImpl(this);
}
@Method()
first(): PublicViewController {
return getFirstView(this);
}
@Method()
last(): PublicViewController {
return getLastView(this);
}
@Method()
setRouteId(id: string, _: any = {}, direction: number): Promise<boolean> {
const active = this.getActive();
if (active && active.component === id) {
return Promise.resolve(false);
}
if (direction === 1) {
return this.push(id).then(() => true);
} else if (direction === -1 && this._canGoBack(id)) {
return this.pop().then(() => true);
}
return this.setRoot(id).then(() => true);
}
private _canGoBack(id: any) {
if (!this.canGoBack()) {
return false;
}
const view = this.views[this.views.length - 1];
return view.component === id;
}
@Method()
getRouteId(): string | null {
const element = this.getContentElement();
if (element) {
return element.tagName;
}
return null;
}
@Method()
getContentElement(): HTMLElement {
const active = getActiveImpl(this);
if (active) {
return active.element;
}
return null;
}
@Method()
getChildNavs(): PublicNav[] {
return this.childNavs || [];
}
@Method()
isTransitioning() {
return this.transitionId >= 0;
}
@Method()
getId() {
return this.navId;
}
@Method()
setParent(parent: Nav) {
this.parent = parent;
}
@Method()
onAllTransitionsComplete() {
return allTransitionsCompleteImpl(this);
}
@Method()
reconcileFromExternalRouter(component: any, data: any = {}, escapeHatch: EscapeHatch, isTopLevel: boolean) {
return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);
}
@Method()
activateFromTab() {
return activateFromTabImpl(this);
}
canSwipeBack(): boolean {
return (this.swipeBackEnabled &&
// this.childNavs.length === 0 &&
!this.isTransitioning() &&
// this._app.isEnabled() &&
this.canGoBack());
}
swipeBackStart() {
// default the direction to "back";
const opts: NavOptions = {
direction: DIRECTION_BACK,
progressAnimation: true
};
return popImpl(this, opts, {});
}
swipeBackProgress(detail: GestureDetail) {
if (!this.sbTrns) {
return;
}
// continue to disable the app while actively dragging
// this._app.setEnabled(false, ACTIVE_TRANSITION_DEFAULT);
// this.setTransitioning(true);
const delta = detail.deltaX;
const stepValue = delta / window.innerWidth;
// set the transition animation's progress
this.sbTrns.progressStep(stepValue);
}
swipeBackEnd(detail: GestureDetail) {
if (!this.sbTrns) {
return;
}
// the swipe back gesture has ended
const delta = detail.deltaX;
const width = window.innerWidth;
const stepValue = delta / width;
const velocity = detail.velocityX;
const z = width / 2.0;
const shouldComplete = (velocity >= 0)
&& (velocity > 0.2 || detail.deltaX > z);
const missing = shouldComplete ? 1 - stepValue : stepValue;
const missingDistance = missing * width;
let realDur = 0;
if (missingDistance > 5) {
const dur = missingDistance / Math.abs(velocity);
realDur = Math.min(dur, 300);
}
this.sbTrns.progressEnd(shouldComplete, stepValue, realDur);
}
@Listen('navInit')
navInitialized(event: NavEvent) {
navInitializedImpl(this, event);
}
render() {
const dom = [];
if (this.swipeBackEnabled) {
dom.push(<ion-gesture
canStart={this.canSwipeBack.bind(this)}
onStart={this.swipeBackStart.bind(this)}
onMove={this.swipeBackProgress.bind(this)}
onEnd={this.swipeBackEnd.bind(this)}
gestureName='goback-swipe'
gesturePriority={10}
type='pan'
direction='x'
threshold={10}
attachTo='body'/>);
}
if (this.mode === 'ios') {
dom.push(<div class='nav-decor'/>);
}
dom.push(<slot></slot>);
return dom;
}
}
export function componentDidLoadImpl(nav: Nav) {
if (nav.initialized) {
return;
}
nav.initialized = true;
nav.navInit.emit();
if (!nav.useRouter) {
if (nav.root && !nav.lazy) {
nav.setRoot(nav.root);
}
}
}
export async function pushImpl(nav: Nav, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return push(nav, nav.delegate, animation, component, data, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function popImpl(nav: Nav, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return pop(nav, nav.delegate, animation, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function setRootImpl(nav: Nav, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return setRoot(nav, nav.delegate, animation, component, data, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function insertImpl(nav: Nav, insertIndex: number, page: any, params: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return insert(nav, nav.delegate, animation, insertIndex, page, params, opts, escapeHatch);
}
export async function insertPagesImpl(nav: Nav, insertIndex: number, pagesToInsert: any[], opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return insertPages(nav, nav.delegate, animation, insertIndex, pagesToInsert, opts, escapeHatch);
}
export async function popToRootImpl(nav: Nav, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return popToRoot(nav, nav.delegate, animation, opts, escapeHatch);
}
export async function popToImpl(nav: Nav, indexOrViewCtrl: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return popTo(nav, nav.delegate, animation, indexOrViewCtrl, opts, escapeHatch);
}
export async function removeImpl(nav: Nav, startIndex: number, removeCount: number, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return remove(nav, nav.delegate, animation, startIndex, removeCount, opts, escapeHatch);
}
export async function removeViewImpl(nav: Nav, viewController: PublicViewController, opts: NavOptions, escapeHatch?: any) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return removeView(nav, nav.delegate, animation, viewController as ViewController, opts, escapeHatch);
}
export async function setPagesImpl(nav: Nav, componentDataPairs: ComponentDataPair[], opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return setPages(nav, nav.delegate, animation, componentDataPairs, opts, escapeHatch, null);
}
export function canGoBackImpl(nav: Nav) {
return nav.views && nav.views.length > 1;
}
export function navInitializedImpl(potentialParent: Nav, event: NavEvent) {
if ((potentialParent.element as any as HTMLIonNavElement) !== event.target) {
// set the parent on the child nav that dispatched the event
event.target.setParent(potentialParent);
if (!potentialParent.childNavs) {
potentialParent.childNavs = [];
}
potentialParent.childNavs.push((event.detail as Nav));
// kill the event so it doesn't propagate further
event.stopPropagation();
}
}
export function hydrateAnimationController(animationController: AnimationController): Promise<Animation> {
return animationController.create();
}
// public api
export function push(nav: Nav, delegate: FrameworkDelegate, animation: Animation, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: component,
insertStart: -1,
insertViews: [{component, data}],
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: PUSH
});
}
export function insert(nav: Nav, delegate: FrameworkDelegate, animation: Animation, insertIndex: number, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: component,
insertStart: insertIndex,
insertViews: [{ component, data }],
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'insert'
});
}
export function insertPages(nav: Nav, delegate: FrameworkDelegate, animation: Animation, insertIndex: number, insertPages: any[], opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
insertStart: insertIndex,
insertViews: insertPages,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'insertPages'
});
}
export function pop(nav: Nav, delegate: FrameworkDelegate, animation: Animation, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: -1,
removeCount: 1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: POP
});
}
export function popToRoot(nav: Nav, delegate: FrameworkDelegate, animation: Animation, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: 1,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'popToRoot'
});
}
export function popTo(nav: Nav, delegate: FrameworkDelegate, animation: Animation, indexOrViewCtrl: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
const config: TransitionInstruction = {
component: null,
removeStart: -1,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'popTo'
};
if (isViewController(indexOrViewCtrl)) {
config.removeView = indexOrViewCtrl;
config.removeStart = 1;
} else if (isNumber(indexOrViewCtrl)) {
config.removeStart = indexOrViewCtrl + 1;
}
return preprocessTransaction(config);
}
export function remove(nav: Nav, delegate: FrameworkDelegate, animation: Animation, startIndex: number, removeCount = 1, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: startIndex,
removeCount: removeCount,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'remove'
});
}
export function removeView(nav: Nav, delegate: FrameworkDelegate, animation: Animation, viewController: ViewController, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeView: viewController,
removeStart: 0,
removeCount: 1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'removeView'
});
}
export function setRoot(nav: Nav, delegate: FrameworkDelegate, animation: Animation, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return setPages(nav, delegate, animation, [{ component, data }], opts, escapeHatch, SET_ROOT);
}
export function setPages(nav: Nav, delegate: FrameworkDelegate, animation: Animation, componentDataPairs: ComponentDataPair[], opts: NavOptions, escapeHatch: EscapeHatch, methodName: string): Promise<NavResult> {
if (!isDef(opts)) {
opts = {};
}
if (opts.animate !== true) {
opts.animate = false;
}
return preprocessTransaction({
component: componentDataPairs.length === 1 ? componentDataPairs[0].component : null,
insertStart: 0,
insertViews: componentDataPairs,
removeStart: 0,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: methodName ? methodName : 'setPages'
});
}
export function preprocessTransaction(ti: TransitionInstruction): Promise<NavResult> {
if (isUrl(ti.component)) {
if (ti.method === PUSH || ti.method === POP || ti.method === SET_ROOT) {
return navigateToUrl(ti.nav, normalizeUrl(ti.component), ti.method);
} else {
return Promise.reject(new Error('only push, pop, and setRoot methods support urls'));
}
}
const response = checkIfPopRedirectRequired(ti);
if (response.required) {
return navigateToUrl(ti.nav, response.url, POP);
}
return queueTransaction(ti);
}
export function isUrl(component: any): boolean {
return typeof component === 'string' && component.charAt(0) === '/';
}
export function navigateToUrl(nav: Nav, url: string, _method: string): Promise<any> {
if (!nav.routerDelegate) {
nav.routerDelegate = new DomRouterDelegate();
}
return nav.routerDelegate.pushUrlState(url);
}
export function activateFromTabImpl(nav: Nav): Promise<any> {
return nav.onAllTransitionsComplete().then(() => {
// if there is not a view set and it's not transitioning,
// go ahead and set the root
if (nav.getViews().length === 0 && !nav.isTransitioning()) {
return nav.setRoot(nav.root);
}
// okay, we have a view here, and it's almost certainly the correct view
// so what we need to do is update the browsers url to match what's in the top view
const viewController = nav.getActive() as ViewController;
return viewController && viewController.url ? navigateToUrl(nav, viewController.url, null) : Promise.resolve();
});
}
export function queueTransaction(ti: TransitionInstruction): Promise<NavResult> {
const promise = new Promise<NavResult>((resolve, reject) => {
ti.resolve = resolve;
ti.reject = reject;
});
if (!ti.delegate) {
ti.delegate = new DomFrameworkDelegate();
}
// Normalize empty
if (ti.insertViews && ti.insertViews.length === 0) {
ti.insertViews = undefined;
}
// Normalize empty
if (ti.insertViews && ti.insertViews.length === 0) {
ti.insertViews = undefined;
}
// Enqueue transition instruction
addToQueue(ti);
// if there isn't a transition already happening
// then this will kick off this transition
nextTransaction(ti.nav);
return promise;
}
export function nextTransaction(nav: Nav): Promise<any> {
if (nav.transitioning) {
return Promise.resolve();
}
const topTransaction = getTopTransaction(nav.navId);
if (!topTransaction) {
// cool, there are no transitions going for this nav
processAllTransitionCompleteQueue(nav.navId);
return Promise.resolve();
}
return doNav(nav, topTransaction);
}
export function checkIfPopRedirectRequired(ti: TransitionInstruction): IsRedirectRequired {
if (ti.method === POP) {
if (ti.escapeHatch.fromExternalRouter) {
// if the pop method is called from a router, that means the redirect already happened
// so just do a normal pop because the url is in a good place. Basically, the router is telling us to
// pop
return {
required: false
};
}
// check if we need to redirect to a url for the pop operation
const popToIndex = ti.nav.views.length - 2;
if (popToIndex >= 0) {
const viewController = ti.nav.views[popToIndex];
return {
required: viewController.fromExternalRouter,
url: viewController.url
};
}
}
return {
required: false,
};
}
export function processAllTransitionCompleteQueue(navId: number) {
const queue = allTransitionsCompleteHandlerQueue.get(navId) || [];
for (const callback of queue) {
callback();
}
allTransitionsCompleteHandlerQueue.set(navId, []);
}
export function allTransitionsCompleteImpl(nav: Nav) {
return new Promise((resolve) => {
const queue = transitionQueue.get(nav.navId) || [];
if (queue.length) {
// there are pending transitions, so queue it up and we'll be notified when it's done
const handlers = allTransitionsCompleteHandlerQueue.get(nav.navId) || [];
handlers.push(resolve);
return allTransitionsCompleteHandlerQueue.set(nav.navId, handlers);
}
// there are no pending transitions, so just resolve right away
return resolve();
});
}
export function doNav(nav: Nav, ti: TransitionInstruction) {
let enteringView: ViewController;
let leavingView: ViewController;
return initializeViewBeforeTransition(ti).then(([_enteringView, _leavingView]) => {
enteringView = _enteringView;
leavingView = _leavingView;
return attachViewToDom(nav, enteringView, ti);
}).then(() => {
return loadViewAndTransition(nav, enteringView, leavingView, ti);
}).then(() => {
nav.ionNavChanged.emit({ isPop: ti.method === 'pop' });
return successfullyTransitioned(ti);
}).catch((err: Error) => {
return transitionFailed(err, ti);
});
}
export function successfullyTransitioned(ti: TransitionInstruction) {
const queue = getQueue(ti.id);
if (!queue) {
// TODO, make throw error in the future
return fireError(new Error('Queue is null, the nav must have been destroyed'), ti);
}
ti.nav.initialized = true;
ti.nav.transitionId = NOT_TRANSITIONING_TRANSITION_ID;
ti.nav.transitioning = false;
// TODO - check if it's a swipe back
// kick off next transition for this nav I guess
nextTransaction(ti.nav);
ti.resolve({
successful: true,
mountingData: ti.mountingData
});
}
export function transitionFailed(error: Error, ti: TransitionInstruction) {
const queue = getQueue(ti.nav.navId);
if (!queue) {
// TODO, make throw error in the future
return fireError(new Error('Queue is null, the nav must have been destroyed'), ti);
}
ti.nav.transitionId = null;
resetQueue(ti.nav.navId);
ti.nav.transitioning = false;
// TODO - check if it's a swipe back
// kick off next transition for this nav I guess
nextTransaction(ti.nav);
fireError(error, ti);
}
export function fireError(error: Error, ti: TransitionInstruction) {
if (ti.reject && !ti.nav.destroyed) {
ti.reject(error);
} else {
ti.resolve({
successful: false,
mountingData: ti.mountingData
});
}
}
export function loadViewAndTransition(nav: Nav, enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction) {
if (!ti.requiresTransition) {
// transition is not required, so we are already done!
// they're inserting/removing the views somewhere in the middle or
// beginning, so visually nothing needs to animate/transition
// resolve immediately because there's no animation that's happening
return Promise.resolve();
}
const transitionId = getParentTransitionId(nav);
nav.transitionId = transitionId >= 0 ? transitionId : getNextTransitionId();
// create the transition options
const animationOpts: AnimationOptions = {
animation: ti.opts.animation,
direction: ti.opts.direction,
duration: (ti.opts.animate === false ? 0 : ti.opts.duration),
easing: ti.opts.easing,
isRTL: false, // TODO
ev: ti.opts.event,
};
const emptyTransition = transitionFactory(ti.animation);
return getHydratedTransition(animationOpts.animation, nav.config, nav.transitionId, emptyTransition, enteringView, leavingView, animationOpts, getDefaultTransition(nav.config))
.then((transition) => {
if (nav.sbTrns) {
nav.sbTrns.destroy();
nav.sbTrns = null;
}
// it's a swipe to go back transition
if (transition.isRoot() && ti.opts.progressAnimation) {
nav.sbTrns = transition;
}
transition.start();
return executeAsyncTransition(nav, transition, enteringView, leavingView, ti.delegate, ti.opts, ti.nav.config.getBoolean('animate'));
});
}
export function executeAsyncTransition(nav: Nav, transition: Transition, enteringView: ViewController, leavingView: ViewController, delegate: FrameworkDelegate, opts: NavOptions, configShouldAnimate: boolean): Promise<void> {
assert(nav.transitioning, 'must be transitioning');
nav.transitionId = NOT_TRANSITIONING_TRANSITION_ID;
setZIndex(nav, enteringView, leavingView, opts.direction);
// always ensure the entering view is viewable
// ******** DOM WRITE ****************
// TODO, figure out where we want to read this data from
enteringView && toggleHidden(enteringView.element, false);
// always ensure the leaving view is viewable
// ******** DOM WRITE ****************
leavingView && toggleHidden(leavingView.element, false);
const isFirstPage = !nav.initialized && nav.views.length === 1;
const shouldNotAnimate = isFirstPage;
if (configShouldAnimate || shouldNotAnimate) {
opts.animate = false;
}
if (opts.animate === false) {
// if it was somehow set to not animation, then make the duration zero
transition.duration(0);
}
transition.beforeAddRead(() => {
fireViewWillLifecycles(enteringView, leavingView);
});
// get the set duration of this transition
const duration = transition.getDuration();
// create a callback for when the animation is done
const transitionCompletePromise = new Promise(resolve => {
transition.onFinish(resolve);
});
if (transition.isRoot()) {
if (duration > DISABLE_APP_MINIMUM_DURATION && opts.disableApp !== false) {
// if this transition has a duration and this is the root transition
// then set that the app is actively disabled
// this._app.setEnabled(false, duration + ACTIVE_TRANSITION_OFFSET, opts.minClickBlockDuration);
} else {
console.debug('transition is running but app has not been disabled');
}
if (opts.progressAnimation) {
// this is a swipe to go back, just get the transition progress ready
// kick off the swipe animation start
transition.progressStart();
} else {
// only the top level transition should actually start "play"
// kick it off and let it play through
// ******** DOM WRITE ****************
transition.play();
}
}
return transitionCompletePromise.then(() => {
return transitionFinish(nav, transition, delegate, opts);
});
}
export function transitionFinish(nav: Nav, transition: Transition, delegate: FrameworkDelegate, opts: NavOptions): Promise<any> {
let promise: Promise<any> = null;
if (transition.hasCompleted) {
transition.enteringView && transition.enteringView.didEnter();
transition.leavingView && transition.leavingView.didLeave();
promise = cleanUpView(nav, delegate, transition.enteringView);
} else {
promise = cleanUpView(nav, delegate, transition.leavingView);
}
return promise.then(() => {
if (transition.isRoot()) {
destroyTransition(transition.transitionId);
// TODO - enable app
nav.transitioning = false;
// TODO - navChange on the deep linker used to be called here
if (opts.keyboardClose !== false) {
focusOutActiveElement();
}
}
});
}
export function cleanUpView(nav: Nav, delegate: FrameworkDelegate, activeViewController: ViewController): Promise<any> {
if (nav.destroyed) {
return Promise.resolve();
}
const activeIndex = nav.views.indexOf(activeViewController);
const promises: Promise<any>[] = [];
for (let i = nav.views.length - 1; i >= 0; i--) {
const inactiveViewController = nav.views[i];
if (i > activeIndex) {
// this view comes after the active view
inactiveViewController.willUnload();
promises.push(destroyView(nav, delegate, inactiveViewController));
} else if ( i < activeIndex) {
// this view comes before the active view
// and it is not a portal then ensure it is hidden
toggleHidden(inactiveViewController.element, true);
}
// TODO - review existing z index code!
}
return Promise.all(promises);
}
export function fireViewWillLifecycles(enteringView: ViewController, leavingView: ViewController) {
leavingView && leavingView.willLeave(!enteringView);
enteringView && enteringView.willEnter();
}
export function attachViewToDom(nav: Nav, enteringView: ViewController, ti: TransitionInstruction): Promise<any> {
if (enteringView && enteringView.state === STATE_NEW) {
return ti.delegate.attachViewToDom(nav.element, enteringView.component, enteringView.data, [], ti.escapeHatch).then((mountingData) => {
ti.mountingData = mountingData;
Object.assign(enteringView, mountingData);
enteringView.state = STATE_ATTACHED;
})
// implicit returns FTW
.then(() => waitForNewlyAttachedViewElementsToHydate(enteringView.element));
}
// it's in the wrong state, so don't attach and just return
return Promise.resolve();
}
export function waitForNewlyAttachedViewElementsToHydate(element: HTMLElement) {
// the element may or may not be a Stencil element
// so check if it has an `<ion-nav>`, `<ion-header>`, and `<ion-content>` for
// hydration
const promises: Promise<any>[] = [];
if ((element as any).componentOnReady) {
// it's a stencil element
promises.push((element as any).componentOnReady());
}
const navs = element.querySelectorAll('ion-nav');
for (let i = 0; i < navs.length; i++) {
const nav = navs.item(i);
promises.push((nav as any).componentOnReady());
}
// check for headers
const headers = element.querySelectorAll('ion-header');
for (let i = 0; i < headers.length; i++) {
const header = headers.item(i);
promises.push((header as any).componentOnReady());
}
// check for contents
const contents = element.querySelectorAll('ion-content');
for (let i = 0; i < contents.length; i++) {
const content = contents.item(i);
promises.push((content as any).componentOnReady());
}
// check for back buttons
const backButtons = element.querySelectorAll('ion-back-button');
for (let i = 0; i < backButtons.length; i++) {
const backButton = backButtons.item(i);
promises.push((backButton as any).componentOnReady());
}
return Promise.all(promises);
}
export function initializeViewBeforeTransition(ti: TransitionInstruction): Promise<ViewController[]> {
let leavingView: ViewController = null;
let enteringView: ViewController = null;
return startTransaction(ti).then(() => {
const viewControllers = convertComponentToViewController(ti);
ti.viewControllers = viewControllers;
leavingView = ti.nav.getActive() as ViewController;
enteringView = getEnteringView(ti, ti.nav, leavingView);
if (!leavingView && !enteringView) {
return Promise.reject(new Error('No views in the stack to remove'));
}
// mark state as initialized
// enteringView.state = STATE_INITIALIZED;
ti.requiresTransition = (ti.enteringRequiresTransition || ti.leavingRequiresTransition) && enteringView !== leavingView;
return testIfViewsCanLeaveAndEnter(enteringView, leavingView, ti);
}).then(() => {
return updateNavStacks(enteringView, leavingView, ti);
}).then(() => {
return [enteringView, leavingView];
});
}
export function updateNavStacks(enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction): Promise<any> {
return Promise.resolve().then(() => {
assert(!!(leavingView || enteringView), 'Both leavingView and enteringView are null');
assert(!!ti.resolve, 'resolve must be valid');
assert(!!ti.reject, 'reject must be valid');
const destroyQueue: ViewController[] = [];
ti.opts = ti.opts || {};
if (isDef(ti.removeStart)) {
assert(ti.removeStart >= 0, 'removeStart can not be negative');
assert(ti.removeStart >= 0, 'removeCount can not be negative');
for (let i = 0; i < ti.removeCount; i++) {
const view = ti.nav.views[i + ti.removeStart];
if (view && view !== enteringView && view !== leavingView) {
destroyQueue.push(view);
}
}
ti.opts.direction = ti.opts.direction || DIRECTION_BACK;
}
const finalBalance = ti.nav.views.length + (ti.insertViews ? ti.insertViews.length : 0) - (ti.removeCount ? ti.removeCount : 0);
assert(finalBalance >= 0, 'final balance can not be negative');
if (finalBalance === 0) {
console.warn(`You can't remove all the pages in the navigation stack. nav.pop() is probably called too many times.`);
throw new Error('Navigation stack needs at least one root page');
}
// At this point the transition can not be rejected, any throw should be an error
// there are views to insert
if (ti.viewControllers) {
// manually set the new view's id if an id was passed in the options
if (isDef(ti.opts.id)) {
enteringView.id = ti.opts.id;
}
// add the views to the stack
for (let i = 0; i < ti.viewControllers.length; i++) {
insertViewIntoNav(ti.nav, ti.viewControllers[i], ti.insertStart + i);
}
if (ti.enteringRequiresTransition) {
// default to forward if not already set
ti.opts.direction = ti.opts.direction || DIRECTION_FORWARD;
}
}
// if the views to be removed are in the beginning or middle
// and there is not a view that needs to visually transition out
// then just destroy them and don't transition anything
// batch all of lifecycles together
if (destroyQueue && destroyQueue.length) {
// TODO, figure out how the zone stuff should work in angular
for (const view of destroyQueue) {
view.willLeave(true);
view.didLeave();
view.willUnload();
}
const destroyQueuePromises: Promise<any>[] = [];
for (const viewController of destroyQueue) {
destroyQueuePromises.push(destroyView(ti.nav, ti.delegate, viewController));
}
return Promise.all(destroyQueuePromises);
}
return null;
})/*.then(() => {
// set which animation it should use if it wasn't set yet
if (ti.requiresTransition && !ti.opts.animation) {
ti.opts.animation = isDef(ti.removeStart)
? (leavingView || enteringView).getTransitionName(ti.opts.direction)
: (enteringView || leavingView).getTransitionName(ti.opts.direction);
}
});
*/
}
export function destroyView(nav: Nav, delegate: FrameworkDelegate, viewController: ViewController) {
return viewController.destroy(delegate).then(() => {
return removeViewFromList(nav, viewController);
});
}
export function removeViewFromList(nav: Nav, viewController: ViewController) {
assert(viewController.state === STATE_ATTACHED || viewController.state === STATE_DESTROYED, 'view state should be loaded or destroyed');
const index = nav.views.indexOf(viewController);
assert(index > -1, 'view must be part of the stack');
if (index >= 0) {
nav.views.splice(index, 1);
}
}
export function insertViewIntoNav(nav: Nav, view: ViewController, index: number) {
const existingIndex = nav.views.indexOf(view);
if (existingIndex > -1) {
// this view is already in the stack!!
// move it to its new location
assert(view.nav === nav, 'view is not part of the nav');
nav.views.splice(index, 0, nav.views.splice(existingIndex, 1)[0]);
} else {
assert(!view.nav, 'nav is used');
// this is a new view to add to the stack
// create the new entering view
view.nav = nav;
// give this inserted view an ID
viewIds++;
if (!view.id) {
view.id = `${nav.navId}-${viewIds}`;
}
// insert the entering view into the correct index in the stack
nav.views.splice(index, 0, view);
}
}
export function testIfViewsCanLeaveAndEnter(enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction) {
if (!ti.requiresTransition) {
return Promise.resolve();
}
const promises: Promise<any>[] = [];
if (leavingView) {
promises.push(lifeCycleTest(leavingView, 'Leave'));
}
if (enteringView) {
promises.push(lifeCycleTest(enteringView, 'Enter'));
}
if (promises.length === 0) {
return Promise.resolve();
}
// darn, async promises, gotta wait for them to resolve
return Promise.all(promises).then((values: any[]) => {
if (values.some(result => result === false)) {
ti.reject = null;
throw new Error('canEnter/Leave returned false');
}
});
}
export function lifeCycleTest(viewController: ViewController, enterOrLeave: string) {
const methodName = `ionViewCan${enterOrLeave}`;
if (viewController.instance && viewController.instance[methodName]) {
try {
const result = viewController.instance[methodName];
if (result instanceof Promise) {
return result;
}
return Promise.resolve(result !== false);
} catch (e) {
return Promise.reject(new Error(`Unexpected error when calling ${methodName}: ${e.message}`));
}
}
return Promise.resolve(true);
}
export function startTransaction(ti: TransitionInstruction): Promise<any> {
const viewsLength = ti.nav.views ? ti.nav.views.length : 0;
if (isDef(ti.removeView)) {
assert(isDef(ti.removeStart), 'removeView needs removeStart');
assert(isDef(ti.removeCount), 'removeView needs removeCount');
const index = ti.nav.views.indexOf(ti.removeView());
if (index < 0) {
return Promise.reject(new Error('The removeView was not found'));
}
ti.removeStart += index;
}
if (isDef(ti.removeStart)) {
if (ti.removeStart < 0) {
ti.removeStart = (viewsLength - 1);
}
if (ti.removeCount < 0) {
ti.removeCount = (viewsLength - ti.removeStart);
}
ti.leavingRequiresTransition = (ti.removeCount > 0) && ((ti.removeStart + ti.removeCount) === viewsLength);
}
if (isDef(ti.insertViews)) {
// allow -1 to be passed in to auto push it on the end
// and clean up the index if it's larger then the size of the stack
if (ti.insertStart < 0 || ti.insertStart > viewsLength) {
ti.insertStart = viewsLength;
}
ti.enteringRequiresTransition = (ti.insertStart === viewsLength);
}
ti.nav.transitioning = true;
return Promise.resolve();
}
export function getEnteringView(ti: TransitionInstruction, nav: Nav, leavingView: ViewController): ViewController {
if (ti.viewControllers && ti.viewControllers.length) {
// grab the very last view of the views to be inserted
// and initialize it as the new entering view
return ti.viewControllers[ti.viewControllers.length - 1];
}
if (isDef(ti.removeStart)) {
const removeEnd = ti.removeStart + ti.removeCount;
for (let i = nav.views.length - 1; i >= 0; i--) {
if ((i < ti.removeStart || i >= removeEnd) && nav.views[i] !== leavingView) {
return nav.views[i];
}
}
}
return null;
}
export function convertViewsToViewControllers(pairs: ComponentDataPair[], escapeHatch: EscapeHatch): ViewController[] {
return pairs.filter(pair => !!pair)
.map(pair => {
const applyEscapeHatch = pair === pairs[pairs.length - 1];
return new ViewController(pair.component, pair.data, applyEscapeHatch ? escapeHatch.fromExternalRouter : false, applyEscapeHatch ? escapeHatch.url : null);
});
}
export function convertComponentToViewController(ti: TransitionInstruction): ViewController[] {
if (ti.insertViews) {
assert(ti.insertViews.length > 0, 'length can not be zero');
const viewControllers = convertViewsToViewControllers(ti.insertViews, ti.escapeHatch);
assert(ti.insertViews.length === viewControllers.length, 'lengths does not match');
if (viewControllers.length === 0) {
throw new Error('No views to insert');
}
for (const viewController of viewControllers) {
if (viewController.nav && viewController.nav.navId !== ti.id) {
throw new Error('The view has already inserted into a different nav');
}
if (viewController.state === STATE_DESTROYED) {
throw new Error('The view has already been destroyed');
}
}
return viewControllers;
}
return [];
}
export function addToQueue(ti: TransitionInstruction) {
const list = transitionQueue.get(ti.id) || [];
list.push(ti);
transitionQueue.set(ti.id, list);
}
export function getQueue(id: number) {
return transitionQueue.get(id) || [];
}
export function resetQueue(id: number) {
transitionQueue.set(id, []);
}
export function getTopTransaction(id: number) {
const queue = getQueue(id);
if (!queue.length) {
return null;
}
const tmp = queue.concat();
const toReturn = tmp.shift();
transitionQueue.set(id, tmp);
return toReturn;
}
export function getDefaultTransition(config: Config) {
return config.get('mode') === 'ios' ? buildIOSTransition : buildMdTransition;
}
let viewIds = VIEW_ID_START;
const DISABLE_APP_MINIMUM_DURATION = 64;
const NOT_TRANSITIONING_TRANSITION_ID = -1;
export interface NavEvent extends CustomEvent {
target: HTMLIonNavElement;
detail: NavEventDetail;
}
export interface NavEventDetail {
isPop?: boolean;
}
export function getDefaultEscapeHatch(): EscapeHatch {
return {
fromExternalRouter: false,
};
}
export function reconcileFromExternalRouterImpl(nav: Nav, component: any, data: any = {}, escapeHatch: EscapeHatch, isTopLevel: boolean): Promise<NavResult> {
// check if the nav has an `<ion-tab>` as a parent
if (isParentTab(nav.element as any)) {
// check if the tab is selected
return updateTab(nav, component, data, escapeHatch, isTopLevel);
} else {
return updateNav(nav, component, data, escapeHatch, isTopLevel);
}
}
export function updateTab(nav: Nav, component: any, data: any, escapeHatch: EscapeHatch, isTopLevel: boolean) {
const tab = nav.element.parentElement as HTMLIonTabElement;
// yeah yeah, I know this is kind of ugly but oh well, I know the internal structure of <ion-tabs>
const tabs = tab.parentElement.parentElement as HTMLIonTabsElement;
return isTabSelected(tabs, tab).then((isSelected) => {
if (!isSelected) {
const promise = updateNav(nav, component, data, escapeHatch, false);
const app = document.querySelector('ion-app');
return app.componentOnReady().then(() => {
app.setExternalNavPromise(promise);
// okay, the tab is not selected, so we need to do a "switch" transition
// basically, we should update the nav, and then swap the tabs
return promise.then((navResult) => {
return tabs.select(tab).then(() => {
app.setExternalNavPromise(null);
return navResult;
});
});
});
}
// okay cool, the tab is already selected, so we want to see a transition
return updateNav(nav, component, data, escapeHatch, isTopLevel);
});
}
export function isTabSelected(tabsElement: HTMLIonTabsElement, tabElement: HTMLIonTabElement ): Promise<boolean> {
const promises: Promise<any>[] = [];
promises.push(tabsElement.componentOnReady());
promises.push(tabElement.componentOnReady());
return Promise.all(promises).then(() => {
return tabsElement.getSelected() === tabElement;
});
}
export function updateNav(nav: Nav,
component: any, data: any, escapeHatch: EscapeHatch, isTopLevel: boolean): Promise<NavResult> {
const url = location.pathname;
// check if the component is the top view
const activeViews = nav.getViews() as ViewController[];
if (activeViews.length === 0) {
// there isn't a view in the stack, so push one
return nav.setRoot(component, data, {}, escapeHatch);
}
const currentView = activeViews[activeViews.length - 1];
if (currentView.url === url) {
// the top view is already the component being activated, so there is no change needed
return Promise.resolve(null);
}
// check if the component is the previous view, if so, pop back to it
if (activeViews.length > 1) {
// there's at least two views in the stack
const previousView = activeViews[activeViews.length - 2];
if (previousView.url === url) {
// cool, we match the previous view, so pop it
return nav.pop(null, escapeHatch);
}
}
// check if the component is already in the stack of views, in which case we pop back to it
for (const view of activeViews) {
if (view.url === url) {
// cool, we found the match, pop back to that bad boy
return nav.popTo(view, null, escapeHatch);
}
}
// it's the top level nav, and it's not one of those other behaviors, so do a push so the user gets a chill animation
return nav.push(component, data, { animate: isTopLevel }, escapeHatch);
}
export interface IsRedirectRequired {
required: boolean;
url?: string;
}
export const POP = 'pop';
export const PUSH = 'push';
export const SET_ROOT = 'setRoot';
| packages/core/src/components/nav/nav.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.9966127276420593,
0.016932249069213867,
0.00016464666987303644,
0.0010062225628644228,
0.08632916212081909
]
|
{
"id": 2,
"code_window": [
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n",
" if (nav.getViews().length === 0 && !nav.isTransitioning()) {\n",
" return nav.setRoot(nav.root);\n",
" }\n",
"\n",
" // okay, we have a view here, and it's almost certainly the correct view\n",
" // so what we need to do is update the browsers url to match what's in the top view\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if ( (nav.getViews().length === 0 || tabAlreadySelected) && !nav.isTransitioning()) {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 634
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Menu - Button</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<script src="/dist/ionic.js"></script>
</head>
<body>
<ion-app>
<ion-menu side="left" class="e2eLeftMenu">
<ion-header>
<ion-toolbar color="secondary">
<ion-title>Left Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item>Open Right Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
<ion-item>Close Menu</ion-item>
</ion-list>
</ion-content>
<ion-footer>
<ion-toolbar color="secondary">
<ion-title>Footer</ion-title>
</ion-toolbar>
</ion-footer>
</ion-menu>
<ion-page main>
<ion-header>
<ion-toolbar>
<ion-title>Menu Toggle - Button</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-menu-toggle>
<ion-button>Toggle Menu</ion-button>
</ion-menu-toggle>
</ion-content>
</ion-page>
</ion-app>
<ion-menu-controller></ion-menu-controller>
</body>
</html>
| packages/core/src/components/menu-toggle/test/button/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.0001771794632077217,
0.00017408537678420544,
0.0001700106222415343,
0.00017440174997318536,
0.0000023532552404503804
]
|
{
"id": 2,
"code_window": [
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n",
" if (nav.getViews().length === 0 && !nav.isTransitioning()) {\n",
" return nav.setRoot(nav.root);\n",
" }\n",
"\n",
" // okay, we have a view here, and it's almost certainly the correct view\n",
" // so what we need to do is update the browsers url to match what's in the top view\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if ( (nav.getViews().length === 0 || tabAlreadySelected) && !nav.isTransitioning()) {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 634
} | import { Color } from './components/Color';
export interface ThemeVariable {
property: string;
quickPick?: { text: string };
value?: Color | number | string;
computed?: { type: ComputedType, params: any };
}
export enum ComputedType {
rgblist = 'computed-rgblist',
step = 'computed-step'
}
export const THEME_VARIABLES: ThemeVariable[] = [
{
property: '--ion-alpha-md-activated'
},
{
property: '--ion-alpha-md-border-low'
},
{
property: '--ion-alpha-md-border-medium'
},
{
property: '--ion-alpha-md-border-high'
},
{
property: '--ion-alpha-md-disabled'
},
{
property: '--ion-alpha-md-focused'
},
{
property: '--ion-alpha-md-hover'
},
{
property: '--ion-alpha-md-lowest'
},
{
property: '--ion-alpha-md-low'
},
{
property: '--ion-alpha-md-medium'
},
{
property: '--ion-alpha-md-high'
},
{
property: '--ion-alpha-md-highest'
},
{
property: '--ion-color-primary',
quickPick: {text: 'p'}
},
{
property: '--ion-color-primary-contrast'
},
{
property: '--ion-color-primary-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-primary'}
}
},
{
property: '--ion-color-primary-shade'
},
{
property: '--ion-color-primary-tint'
},
{
property: '--ion-color-secondary',
quickPick: {text: 's'}
},
{
property: '--ion-color-secondary-contrast'
},
{
property: '--ion-color-secondary-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-secondary'}
}
},
{
property: '--ion-color-secondary-shade'
},
{
property: '--ion-color-secondary-tint'
},
{
property: '--ion-color-tertiary',
quickPick: {text: 't'}
},
{
property: '--ion-color-tertiary-contrast'
},
{
property: '--ion-color-tertiary-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-tertiary'}
}
},
{
property: '--ion-color-tertiary-shade'
},
{
property: '--ion-color-tertiary-tint'
},
{
property: '--ion-color-success',
quickPick: {text: 'ss'}
},
{
property: '--ion-color-success-contrast'
},
{
property: '--ion-color-success-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-success'}
}
},
{
property: '--ion-color-success-shade'
},
{
property: '--ion-color-success-tint'
},
{
property: '--ion-color-warning',
quickPick: {text: 'w'}
},
{
property: '--ion-color-warning-contrast'
},
{
property: '--ion-color-warning-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-warning'}
}
},
{
property: '--ion-color-warning-shade'
},
{
property: '--ion-color-warning-tint'
},
{
property: '--ion-color-danger',
quickPick: {text: 'd'}
},
{
property: '--ion-color-danger-contrast'
},
{
property: '--ion-color-danger-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-danger'}
}
},
{
property: '--ion-color-danger-shade'
},
{
property: '--ion-color-danger-tint'
},
{
property: '--ion-color-light',
quickPick: {text: 'l'}
},
{
property: '--ion-color-light-contrast'
},
{
property: '--ion-color-light-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-light'}
}
},
{
property: '--ion-color-light-shade'
},
{
property: '--ion-color-light-tint'
},
{
property: '--ion-color-medium',
quickPick: {text: 'm'}
},
{
property: '--ion-color-medium-contrast'
},
{
property: '--ion-color-medium-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-medium'}
}
},
{
property: '--ion-color-medium-shade'
},
{
property: '--ion-color-medium-tint'
},
{
property: '--ion-color-dark',
quickPick: {text: 'd'}
},
{
property: '--ion-color-dark-contrast'
},
{
property: '--ion-color-dark-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-color-dark'}
}
},
{
property: '--ion-color-dark-shade'
},
{
property: '--ion-color-dark-tint'
},
{
property: '--ion-backdrop-color'
},
{
property: '--ion-overlay-background-color'
},
{
property: '--ion-background-color',
quickPick: {
text: 'bg'
}
},
{
property: '--ion-background-color-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-background-color'}
}
},
{
property: '--ion-background-color-step-50',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .050, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-100',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .100, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-150',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .150, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-200',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .200, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-250',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .250, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-300',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .300, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-350',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .350, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-400',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .400, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-450',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .450, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-500',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .500, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-550',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .550, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-600',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .600, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-650',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .650, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-700',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .700, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-750',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .750, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-800',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .800, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-850',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .850, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-900',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .900, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-950',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: .950, from: '--ion-text-color'}
}
},
{
property: '--ion-background-color-step-1000',
computed: {
type: ComputedType.step,
params: {property: '--ion-background-color', amount: 1, from: '--ion-text-color'}
}
},
{
property: '--ion-border-color'
},
{
property: '--ion-box-shadow-color'
},
{
property: '--ion-text-color',
quickPick: {
text: 'txt'
}
},
{
property: '--ion-text-color-rgb',
computed: {
type: ComputedType.rgblist,
params: {property: '--ion-text-color'}
}
},
{
property: '--ion-text-color-step-50',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .050, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-100',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .100, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-150',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .150, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-200',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .200, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-250',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .250, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-300',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .300, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-350',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .350, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-400',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .400, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-450',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .450, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-500',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .500, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-550',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .550, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-600',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .600, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-650',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .650, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-700',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .700, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-750',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .750, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-800',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .800, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-850',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .850, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-900',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .900, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-950',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: .950, from: '--ion-background-color'}
}
},
{
property: '--ion-text-color-step-1000',
computed: {
type: ComputedType.step,
params: {property: '--ion-text-color', amount: 1, from: '--ion-background-color'}
}
},
{
property: '--ion-tabbar-background-color'
},
{
property: '--tabbar-background-color-focused'
},
{
property: '--ion-tabbar-border-color'
},
{
property: '--ion-tabbar-text-color'
},
{
property: '--ion-tabbar-text-color-active'
},
{
property: '--ion-toolbar-background-color'
},
{
property: '--ion-toolbar-border-color'
},
{
property: '--ion-toolbar-color-active'
},
{
property: '--ion-toolbar-color-inactive'
},
{
property: '--ion-toolbar-text-color'
},
{
property: '--ion-item-background-color'
},
{
property: '--ion-item-background-color-active'
},
{
property: '--ion-item-border-color'
},
{
property: '--ion-item-text-color'
},
{
property: '--ion-placeholder-text-color'
}
];
| packages/core/scripts/theme-builder/src/theme-variables.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.00022859165619593114,
0.0001768727961461991,
0.00017280933388974518,
0.00017649319488555193,
0.000006878874046378769
]
|
{
"id": 2,
"code_window": [
" return nav.onAllTransitionsComplete().then(() => {\n",
" // if there is not a view set and it's not transitioning,\n",
" // go ahead and set the root\n",
" if (nav.getViews().length === 0 && !nav.isTransitioning()) {\n",
" return nav.setRoot(nav.root);\n",
" }\n",
"\n",
" // okay, we have a view here, and it's almost certainly the correct view\n",
" // so what we need to do is update the browsers url to match what's in the top view\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if ( (nav.getViews().length === 0 || tabAlreadySelected) && !nav.isTransitioning()) {\n"
],
"file_path": "packages/core/src/components/nav/nav.tsx",
"type": "replace",
"edit_start_line_idx": 634
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Button Effect - Basic</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script src="/dist/ionic.js"></script>
<style>
.my-block {
position: relative;
background: blue;
color: white;
width: 300px;
height: 100px;
margin: 1rem;
}
</style>
</head>
<body>
<ion-app>
<ion-page>
<ion-header>
<ion-toolbar>
<ion-title>Button Effect - Basic</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding no-bounce>
<p>
<ion-button size="small">Small</ion-button>
</p>
<p>
<ion-button size="large">Large</ion-button>
</p>
<p>
<ion-button size="large" fill="outline">Large</ion-button>
</p>
<p>
<ion-button size="large" fill="clear">Large</ion-button>
</p>
<div class="my-block">
<ion-ripple-effect></ion-ripple-effect>
This is just a div + effect behind
<ion-button onclick="buttonClicked()">Nested button</ion-button>
</div>
<div class="my-block">
This is just a div + effect on top
<ion-button onclick="buttonClicked()">Nested button</ion-button>
<ion-ripple-effect></ion-ripple-effect>
</div>
<div class="my-block">
This is just a div + effect
<ion-ripple-effect></ion-ripple-effect>
</div>
</ion-content>
</ion-page>
</ion-app>
<script>
function blockClicked() {
console.log('block clicked');
return true;
}
function buttonClicked() {
console.log('button clicked');
}
</script>
</body>
</html>
| packages/core/src/components/tap-click/test/basic/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.00017776802997104824,
0.00017337223107460886,
0.00016963591042440385,
0.0001729463110677898,
0.000002981386842293432
]
|
{
"id": 3,
"code_window": [
"\n",
" // the tab's nav has not been initialized externally, so\n",
" // check if we need to initiailize it\n",
" return nav.componentOnReady()\n",
" .then(() => nav.activateFromTab());\n",
" });\n",
" }\n",
"\n",
" hostData() {\n",
" const hidden = !this.active || !this.selected;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .then(() => nav.activateFromTab(this.selected));\n"
],
"file_path": "packages/core/src/components/tab/tab.tsx",
"type": "replace",
"edit_start_line_idx": 132
} | import { Component, Element, Event, EventEmitter, Listen, Method, Prop, Watch } from '@stencil/core';
import {
Animation,
AnimationController,
AnimationOptions,
ComponentDataPair,
Config,
EscapeHatch,
ExternalNavData,
FrameworkDelegate,
NavOptions,
NavOutlet,
NavResult,
PublicNav,
PublicViewController,
RouterDelegate,
RouterEntries,
Transition,
TransitionInstruction,
} from '../../index';
import { ViewController } from './view-controller';
import {
DIRECTION_BACK,
DIRECTION_FORWARD,
STATE_ATTACHED,
STATE_DESTROYED,
STATE_NEW,
VIEW_ID_START,
destroyTransition,
getActiveImpl,
getFirstView,
getHydratedTransition,
getLastView,
getNextNavId,
getNextTransitionId,
getParentTransitionId,
getPreviousImpl,
getViews,
isViewController,
setZIndex,
toggleHidden,
transitionFactory
} from './nav-utils';
import { DomFrameworkDelegate } from '../../utils/dom-framework-delegate';
import { DomRouterDelegate } from '../../utils/dom-router-delegate';
import {
assert,
focusOutActiveElement,
isDef,
isNumber,
isParentTab,
normalizeUrl,
} from '../../utils/helpers';
import { buildIOSTransition } from './transitions/transition.ios';
import { buildMdTransition } from './transitions/transition.md';
import { GestureDetail } from '../gesture/gesture';
const transitionQueue = new Map<number, TransitionInstruction[]>();
const allTransitionsCompleteHandlerQueue = new Map<number, Function[]>();
/* it is very important to keep this class in sync with ./nav-interface interface */
@Component({
tag: 'ion-nav',
styleUrl: 'nav.scss'
})
export class Nav implements PublicNav, NavOutlet {
@Element() element: HTMLElement;
@Event() navInit: EventEmitter<NavEventDetail>;
@Event() ionNavChanged: EventEmitter<NavEventDetail>;
useRouter = false;
navId = getNextNavId();
routes: RouterEntries = [];
parent: Nav = null;
views: ViewController[] = [];
transitioning = false;
destroyed = false;
transitionId = NOT_TRANSITIONING_TRANSITION_ID;
initialized = false;
sbTrns: any; // TODO Transition
childNavs?: Nav[];
urlExternalNavMap = new Map<string, ExternalNavData>();
@Prop() mode: string;
@Prop() root: any;
@Prop() delegate: FrameworkDelegate;
@Prop() routerDelegate: RouterDelegate;
@Prop() useUrls = false;
@Prop({ context: 'config' }) config: Config;
@Prop({ connect: 'ion-animation-controller' }) animationCtrl: AnimationController;
@Prop() lazy = false;
@Prop() swipeBackEnabled = true;
constructor() {
this.navId = getNextNavId();
}
componentDidLoad() {
return componentDidLoadImpl(this);
}
@Watch('root')
updateRootComponent(): Promise<NavResult> {
if (this.initialized) {
return this.setRoot(this.root);
}
return Promise.resolve(null);
}
@Method()
getViews(): PublicViewController[] {
return getViews(this);
}
@Method()
push(component: any, data?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return pushImpl(this, component, data, opts, escapeHatch);
}
@Method()
pop(opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popImpl(this, opts, escapeHatch);
}
@Method()
setRoot(component: any, data?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return setRootImpl(this, component, data, opts, escapeHatch);
}
@Method()
insert(insertIndex: number, page: any, params?: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return insertImpl(this, insertIndex, page, params, opts, escapeHatch);
}
@Method()
insertPages(insertIndex: number, insertPages: any[], opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return insertPagesImpl(this, insertIndex, insertPages, opts, escapeHatch);
}
@Method()
popToRoot(opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popToRootImpl(this, opts, escapeHatch);
}
@Method()
popTo(indexOrViewCtrl: any, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return popToImpl(this, indexOrViewCtrl, opts, escapeHatch);
}
@Method()
removeIndex(startIndex: number, removeCount?: number, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return removeImpl(this, startIndex, removeCount, opts, escapeHatch);
}
@Method()
removeView(viewController: PublicViewController, opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return removeViewImpl(this, viewController, opts, escapeHatch);
}
@Method()
setPages(componentDataPairs: ComponentDataPair[], opts?: NavOptions, escapeHatch: EscapeHatch = getDefaultEscapeHatch()): Promise<NavResult> {
return setPagesImpl(this, componentDataPairs, opts, escapeHatch);
}
@Method()
getActive(): PublicViewController {
return getActiveImpl(this);
}
@Method()
getPrevious(view?: PublicViewController): PublicViewController {
return getPreviousImpl(this, view as ViewController);
}
@Method()
canGoBack(): boolean {
return canGoBackImpl(this);
}
@Method()
first(): PublicViewController {
return getFirstView(this);
}
@Method()
last(): PublicViewController {
return getLastView(this);
}
@Method()
setRouteId(id: string, _: any = {}, direction: number): Promise<boolean> {
const active = this.getActive();
if (active && active.component === id) {
return Promise.resolve(false);
}
if (direction === 1) {
return this.push(id).then(() => true);
} else if (direction === -1 && this._canGoBack(id)) {
return this.pop().then(() => true);
}
return this.setRoot(id).then(() => true);
}
private _canGoBack(id: any) {
if (!this.canGoBack()) {
return false;
}
const view = this.views[this.views.length - 1];
return view.component === id;
}
@Method()
getRouteId(): string | null {
const element = this.getContentElement();
if (element) {
return element.tagName;
}
return null;
}
@Method()
getContentElement(): HTMLElement {
const active = getActiveImpl(this);
if (active) {
return active.element;
}
return null;
}
@Method()
getChildNavs(): PublicNav[] {
return this.childNavs || [];
}
@Method()
isTransitioning() {
return this.transitionId >= 0;
}
@Method()
getId() {
return this.navId;
}
@Method()
setParent(parent: Nav) {
this.parent = parent;
}
@Method()
onAllTransitionsComplete() {
return allTransitionsCompleteImpl(this);
}
@Method()
reconcileFromExternalRouter(component: any, data: any = {}, escapeHatch: EscapeHatch, isTopLevel: boolean) {
return reconcileFromExternalRouterImpl(this, component, data, escapeHatch, isTopLevel);
}
@Method()
activateFromTab() {
return activateFromTabImpl(this);
}
canSwipeBack(): boolean {
return (this.swipeBackEnabled &&
// this.childNavs.length === 0 &&
!this.isTransitioning() &&
// this._app.isEnabled() &&
this.canGoBack());
}
swipeBackStart() {
// default the direction to "back";
const opts: NavOptions = {
direction: DIRECTION_BACK,
progressAnimation: true
};
return popImpl(this, opts, {});
}
swipeBackProgress(detail: GestureDetail) {
if (!this.sbTrns) {
return;
}
// continue to disable the app while actively dragging
// this._app.setEnabled(false, ACTIVE_TRANSITION_DEFAULT);
// this.setTransitioning(true);
const delta = detail.deltaX;
const stepValue = delta / window.innerWidth;
// set the transition animation's progress
this.sbTrns.progressStep(stepValue);
}
swipeBackEnd(detail: GestureDetail) {
if (!this.sbTrns) {
return;
}
// the swipe back gesture has ended
const delta = detail.deltaX;
const width = window.innerWidth;
const stepValue = delta / width;
const velocity = detail.velocityX;
const z = width / 2.0;
const shouldComplete = (velocity >= 0)
&& (velocity > 0.2 || detail.deltaX > z);
const missing = shouldComplete ? 1 - stepValue : stepValue;
const missingDistance = missing * width;
let realDur = 0;
if (missingDistance > 5) {
const dur = missingDistance / Math.abs(velocity);
realDur = Math.min(dur, 300);
}
this.sbTrns.progressEnd(shouldComplete, stepValue, realDur);
}
@Listen('navInit')
navInitialized(event: NavEvent) {
navInitializedImpl(this, event);
}
render() {
const dom = [];
if (this.swipeBackEnabled) {
dom.push(<ion-gesture
canStart={this.canSwipeBack.bind(this)}
onStart={this.swipeBackStart.bind(this)}
onMove={this.swipeBackProgress.bind(this)}
onEnd={this.swipeBackEnd.bind(this)}
gestureName='goback-swipe'
gesturePriority={10}
type='pan'
direction='x'
threshold={10}
attachTo='body'/>);
}
if (this.mode === 'ios') {
dom.push(<div class='nav-decor'/>);
}
dom.push(<slot></slot>);
return dom;
}
}
export function componentDidLoadImpl(nav: Nav) {
if (nav.initialized) {
return;
}
nav.initialized = true;
nav.navInit.emit();
if (!nav.useRouter) {
if (nav.root && !nav.lazy) {
nav.setRoot(nav.root);
}
}
}
export async function pushImpl(nav: Nav, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return push(nav, nav.delegate, animation, component, data, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function popImpl(nav: Nav, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return pop(nav, nav.delegate, animation, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function setRootImpl(nav: Nav, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return setRoot(nav, nav.delegate, animation, component, data, opts, escapeHatch).then((navResult) => {
return navResult;
});
}
export async function insertImpl(nav: Nav, insertIndex: number, page: any, params: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return insert(nav, nav.delegate, animation, insertIndex, page, params, opts, escapeHatch);
}
export async function insertPagesImpl(nav: Nav, insertIndex: number, pagesToInsert: any[], opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return insertPages(nav, nav.delegate, animation, insertIndex, pagesToInsert, opts, escapeHatch);
}
export async function popToRootImpl(nav: Nav, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return popToRoot(nav, nav.delegate, animation, opts, escapeHatch);
}
export async function popToImpl(nav: Nav, indexOrViewCtrl: any, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return popTo(nav, nav.delegate, animation, indexOrViewCtrl, opts, escapeHatch);
}
export async function removeImpl(nav: Nav, startIndex: number, removeCount: number, opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return remove(nav, nav.delegate, animation, startIndex, removeCount, opts, escapeHatch);
}
export async function removeViewImpl(nav: Nav, viewController: PublicViewController, opts: NavOptions, escapeHatch?: any) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return removeView(nav, nav.delegate, animation, viewController as ViewController, opts, escapeHatch);
}
export async function setPagesImpl(nav: Nav, componentDataPairs: ComponentDataPair[], opts: NavOptions, escapeHatch: EscapeHatch) {
const animation = await hydrateAnimationController(nav.animationCtrl);
return setPages(nav, nav.delegate, animation, componentDataPairs, opts, escapeHatch, null);
}
export function canGoBackImpl(nav: Nav) {
return nav.views && nav.views.length > 1;
}
export function navInitializedImpl(potentialParent: Nav, event: NavEvent) {
if ((potentialParent.element as any as HTMLIonNavElement) !== event.target) {
// set the parent on the child nav that dispatched the event
event.target.setParent(potentialParent);
if (!potentialParent.childNavs) {
potentialParent.childNavs = [];
}
potentialParent.childNavs.push((event.detail as Nav));
// kill the event so it doesn't propagate further
event.stopPropagation();
}
}
export function hydrateAnimationController(animationController: AnimationController): Promise<Animation> {
return animationController.create();
}
// public api
export function push(nav: Nav, delegate: FrameworkDelegate, animation: Animation, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: component,
insertStart: -1,
insertViews: [{component, data}],
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: PUSH
});
}
export function insert(nav: Nav, delegate: FrameworkDelegate, animation: Animation, insertIndex: number, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: component,
insertStart: insertIndex,
insertViews: [{ component, data }],
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'insert'
});
}
export function insertPages(nav: Nav, delegate: FrameworkDelegate, animation: Animation, insertIndex: number, insertPages: any[], opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
insertStart: insertIndex,
insertViews: insertPages,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'insertPages'
});
}
export function pop(nav: Nav, delegate: FrameworkDelegate, animation: Animation, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: -1,
removeCount: 1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: POP
});
}
export function popToRoot(nav: Nav, delegate: FrameworkDelegate, animation: Animation, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: 1,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'popToRoot'
});
}
export function popTo(nav: Nav, delegate: FrameworkDelegate, animation: Animation, indexOrViewCtrl: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
const config: TransitionInstruction = {
component: null,
removeStart: -1,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'popTo'
};
if (isViewController(indexOrViewCtrl)) {
config.removeView = indexOrViewCtrl;
config.removeStart = 1;
} else if (isNumber(indexOrViewCtrl)) {
config.removeStart = indexOrViewCtrl + 1;
}
return preprocessTransaction(config);
}
export function remove(nav: Nav, delegate: FrameworkDelegate, animation: Animation, startIndex: number, removeCount = 1, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeStart: startIndex,
removeCount: removeCount,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'remove'
});
}
export function removeView(nav: Nav, delegate: FrameworkDelegate, animation: Animation, viewController: ViewController, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return preprocessTransaction({
component: null,
removeView: viewController,
removeStart: 0,
removeCount: 1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: 'removeView'
});
}
export function setRoot(nav: Nav, delegate: FrameworkDelegate, animation: Animation, component: any, data: any, opts: NavOptions, escapeHatch: EscapeHatch): Promise<NavResult> {
return setPages(nav, delegate, animation, [{ component, data }], opts, escapeHatch, SET_ROOT);
}
export function setPages(nav: Nav, delegate: FrameworkDelegate, animation: Animation, componentDataPairs: ComponentDataPair[], opts: NavOptions, escapeHatch: EscapeHatch, methodName: string): Promise<NavResult> {
if (!isDef(opts)) {
opts = {};
}
if (opts.animate !== true) {
opts.animate = false;
}
return preprocessTransaction({
component: componentDataPairs.length === 1 ? componentDataPairs[0].component : null,
insertStart: 0,
insertViews: componentDataPairs,
removeStart: 0,
removeCount: -1,
opts,
nav,
delegate,
id: nav.navId,
animation,
escapeHatch,
method: methodName ? methodName : 'setPages'
});
}
export function preprocessTransaction(ti: TransitionInstruction): Promise<NavResult> {
if (isUrl(ti.component)) {
if (ti.method === PUSH || ti.method === POP || ti.method === SET_ROOT) {
return navigateToUrl(ti.nav, normalizeUrl(ti.component), ti.method);
} else {
return Promise.reject(new Error('only push, pop, and setRoot methods support urls'));
}
}
const response = checkIfPopRedirectRequired(ti);
if (response.required) {
return navigateToUrl(ti.nav, response.url, POP);
}
return queueTransaction(ti);
}
export function isUrl(component: any): boolean {
return typeof component === 'string' && component.charAt(0) === '/';
}
export function navigateToUrl(nav: Nav, url: string, _method: string): Promise<any> {
if (!nav.routerDelegate) {
nav.routerDelegate = new DomRouterDelegate();
}
return nav.routerDelegate.pushUrlState(url);
}
export function activateFromTabImpl(nav: Nav): Promise<any> {
return nav.onAllTransitionsComplete().then(() => {
// if there is not a view set and it's not transitioning,
// go ahead and set the root
if (nav.getViews().length === 0 && !nav.isTransitioning()) {
return nav.setRoot(nav.root);
}
// okay, we have a view here, and it's almost certainly the correct view
// so what we need to do is update the browsers url to match what's in the top view
const viewController = nav.getActive() as ViewController;
return viewController && viewController.url ? navigateToUrl(nav, viewController.url, null) : Promise.resolve();
});
}
export function queueTransaction(ti: TransitionInstruction): Promise<NavResult> {
const promise = new Promise<NavResult>((resolve, reject) => {
ti.resolve = resolve;
ti.reject = reject;
});
if (!ti.delegate) {
ti.delegate = new DomFrameworkDelegate();
}
// Normalize empty
if (ti.insertViews && ti.insertViews.length === 0) {
ti.insertViews = undefined;
}
// Normalize empty
if (ti.insertViews && ti.insertViews.length === 0) {
ti.insertViews = undefined;
}
// Enqueue transition instruction
addToQueue(ti);
// if there isn't a transition already happening
// then this will kick off this transition
nextTransaction(ti.nav);
return promise;
}
export function nextTransaction(nav: Nav): Promise<any> {
if (nav.transitioning) {
return Promise.resolve();
}
const topTransaction = getTopTransaction(nav.navId);
if (!topTransaction) {
// cool, there are no transitions going for this nav
processAllTransitionCompleteQueue(nav.navId);
return Promise.resolve();
}
return doNav(nav, topTransaction);
}
export function checkIfPopRedirectRequired(ti: TransitionInstruction): IsRedirectRequired {
if (ti.method === POP) {
if (ti.escapeHatch.fromExternalRouter) {
// if the pop method is called from a router, that means the redirect already happened
// so just do a normal pop because the url is in a good place. Basically, the router is telling us to
// pop
return {
required: false
};
}
// check if we need to redirect to a url for the pop operation
const popToIndex = ti.nav.views.length - 2;
if (popToIndex >= 0) {
const viewController = ti.nav.views[popToIndex];
return {
required: viewController.fromExternalRouter,
url: viewController.url
};
}
}
return {
required: false,
};
}
export function processAllTransitionCompleteQueue(navId: number) {
const queue = allTransitionsCompleteHandlerQueue.get(navId) || [];
for (const callback of queue) {
callback();
}
allTransitionsCompleteHandlerQueue.set(navId, []);
}
export function allTransitionsCompleteImpl(nav: Nav) {
return new Promise((resolve) => {
const queue = transitionQueue.get(nav.navId) || [];
if (queue.length) {
// there are pending transitions, so queue it up and we'll be notified when it's done
const handlers = allTransitionsCompleteHandlerQueue.get(nav.navId) || [];
handlers.push(resolve);
return allTransitionsCompleteHandlerQueue.set(nav.navId, handlers);
}
// there are no pending transitions, so just resolve right away
return resolve();
});
}
export function doNav(nav: Nav, ti: TransitionInstruction) {
let enteringView: ViewController;
let leavingView: ViewController;
return initializeViewBeforeTransition(ti).then(([_enteringView, _leavingView]) => {
enteringView = _enteringView;
leavingView = _leavingView;
return attachViewToDom(nav, enteringView, ti);
}).then(() => {
return loadViewAndTransition(nav, enteringView, leavingView, ti);
}).then(() => {
nav.ionNavChanged.emit({ isPop: ti.method === 'pop' });
return successfullyTransitioned(ti);
}).catch((err: Error) => {
return transitionFailed(err, ti);
});
}
export function successfullyTransitioned(ti: TransitionInstruction) {
const queue = getQueue(ti.id);
if (!queue) {
// TODO, make throw error in the future
return fireError(new Error('Queue is null, the nav must have been destroyed'), ti);
}
ti.nav.initialized = true;
ti.nav.transitionId = NOT_TRANSITIONING_TRANSITION_ID;
ti.nav.transitioning = false;
// TODO - check if it's a swipe back
// kick off next transition for this nav I guess
nextTransaction(ti.nav);
ti.resolve({
successful: true,
mountingData: ti.mountingData
});
}
export function transitionFailed(error: Error, ti: TransitionInstruction) {
const queue = getQueue(ti.nav.navId);
if (!queue) {
// TODO, make throw error in the future
return fireError(new Error('Queue is null, the nav must have been destroyed'), ti);
}
ti.nav.transitionId = null;
resetQueue(ti.nav.navId);
ti.nav.transitioning = false;
// TODO - check if it's a swipe back
// kick off next transition for this nav I guess
nextTransaction(ti.nav);
fireError(error, ti);
}
export function fireError(error: Error, ti: TransitionInstruction) {
if (ti.reject && !ti.nav.destroyed) {
ti.reject(error);
} else {
ti.resolve({
successful: false,
mountingData: ti.mountingData
});
}
}
export function loadViewAndTransition(nav: Nav, enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction) {
if (!ti.requiresTransition) {
// transition is not required, so we are already done!
// they're inserting/removing the views somewhere in the middle or
// beginning, so visually nothing needs to animate/transition
// resolve immediately because there's no animation that's happening
return Promise.resolve();
}
const transitionId = getParentTransitionId(nav);
nav.transitionId = transitionId >= 0 ? transitionId : getNextTransitionId();
// create the transition options
const animationOpts: AnimationOptions = {
animation: ti.opts.animation,
direction: ti.opts.direction,
duration: (ti.opts.animate === false ? 0 : ti.opts.duration),
easing: ti.opts.easing,
isRTL: false, // TODO
ev: ti.opts.event,
};
const emptyTransition = transitionFactory(ti.animation);
return getHydratedTransition(animationOpts.animation, nav.config, nav.transitionId, emptyTransition, enteringView, leavingView, animationOpts, getDefaultTransition(nav.config))
.then((transition) => {
if (nav.sbTrns) {
nav.sbTrns.destroy();
nav.sbTrns = null;
}
// it's a swipe to go back transition
if (transition.isRoot() && ti.opts.progressAnimation) {
nav.sbTrns = transition;
}
transition.start();
return executeAsyncTransition(nav, transition, enteringView, leavingView, ti.delegate, ti.opts, ti.nav.config.getBoolean('animate'));
});
}
export function executeAsyncTransition(nav: Nav, transition: Transition, enteringView: ViewController, leavingView: ViewController, delegate: FrameworkDelegate, opts: NavOptions, configShouldAnimate: boolean): Promise<void> {
assert(nav.transitioning, 'must be transitioning');
nav.transitionId = NOT_TRANSITIONING_TRANSITION_ID;
setZIndex(nav, enteringView, leavingView, opts.direction);
// always ensure the entering view is viewable
// ******** DOM WRITE ****************
// TODO, figure out where we want to read this data from
enteringView && toggleHidden(enteringView.element, false);
// always ensure the leaving view is viewable
// ******** DOM WRITE ****************
leavingView && toggleHidden(leavingView.element, false);
const isFirstPage = !nav.initialized && nav.views.length === 1;
const shouldNotAnimate = isFirstPage;
if (configShouldAnimate || shouldNotAnimate) {
opts.animate = false;
}
if (opts.animate === false) {
// if it was somehow set to not animation, then make the duration zero
transition.duration(0);
}
transition.beforeAddRead(() => {
fireViewWillLifecycles(enteringView, leavingView);
});
// get the set duration of this transition
const duration = transition.getDuration();
// create a callback for when the animation is done
const transitionCompletePromise = new Promise(resolve => {
transition.onFinish(resolve);
});
if (transition.isRoot()) {
if (duration > DISABLE_APP_MINIMUM_DURATION && opts.disableApp !== false) {
// if this transition has a duration and this is the root transition
// then set that the app is actively disabled
// this._app.setEnabled(false, duration + ACTIVE_TRANSITION_OFFSET, opts.minClickBlockDuration);
} else {
console.debug('transition is running but app has not been disabled');
}
if (opts.progressAnimation) {
// this is a swipe to go back, just get the transition progress ready
// kick off the swipe animation start
transition.progressStart();
} else {
// only the top level transition should actually start "play"
// kick it off and let it play through
// ******** DOM WRITE ****************
transition.play();
}
}
return transitionCompletePromise.then(() => {
return transitionFinish(nav, transition, delegate, opts);
});
}
export function transitionFinish(nav: Nav, transition: Transition, delegate: FrameworkDelegate, opts: NavOptions): Promise<any> {
let promise: Promise<any> = null;
if (transition.hasCompleted) {
transition.enteringView && transition.enteringView.didEnter();
transition.leavingView && transition.leavingView.didLeave();
promise = cleanUpView(nav, delegate, transition.enteringView);
} else {
promise = cleanUpView(nav, delegate, transition.leavingView);
}
return promise.then(() => {
if (transition.isRoot()) {
destroyTransition(transition.transitionId);
// TODO - enable app
nav.transitioning = false;
// TODO - navChange on the deep linker used to be called here
if (opts.keyboardClose !== false) {
focusOutActiveElement();
}
}
});
}
export function cleanUpView(nav: Nav, delegate: FrameworkDelegate, activeViewController: ViewController): Promise<any> {
if (nav.destroyed) {
return Promise.resolve();
}
const activeIndex = nav.views.indexOf(activeViewController);
const promises: Promise<any>[] = [];
for (let i = nav.views.length - 1; i >= 0; i--) {
const inactiveViewController = nav.views[i];
if (i > activeIndex) {
// this view comes after the active view
inactiveViewController.willUnload();
promises.push(destroyView(nav, delegate, inactiveViewController));
} else if ( i < activeIndex) {
// this view comes before the active view
// and it is not a portal then ensure it is hidden
toggleHidden(inactiveViewController.element, true);
}
// TODO - review existing z index code!
}
return Promise.all(promises);
}
export function fireViewWillLifecycles(enteringView: ViewController, leavingView: ViewController) {
leavingView && leavingView.willLeave(!enteringView);
enteringView && enteringView.willEnter();
}
export function attachViewToDom(nav: Nav, enteringView: ViewController, ti: TransitionInstruction): Promise<any> {
if (enteringView && enteringView.state === STATE_NEW) {
return ti.delegate.attachViewToDom(nav.element, enteringView.component, enteringView.data, [], ti.escapeHatch).then((mountingData) => {
ti.mountingData = mountingData;
Object.assign(enteringView, mountingData);
enteringView.state = STATE_ATTACHED;
})
// implicit returns FTW
.then(() => waitForNewlyAttachedViewElementsToHydate(enteringView.element));
}
// it's in the wrong state, so don't attach and just return
return Promise.resolve();
}
export function waitForNewlyAttachedViewElementsToHydate(element: HTMLElement) {
// the element may or may not be a Stencil element
// so check if it has an `<ion-nav>`, `<ion-header>`, and `<ion-content>` for
// hydration
const promises: Promise<any>[] = [];
if ((element as any).componentOnReady) {
// it's a stencil element
promises.push((element as any).componentOnReady());
}
const navs = element.querySelectorAll('ion-nav');
for (let i = 0; i < navs.length; i++) {
const nav = navs.item(i);
promises.push((nav as any).componentOnReady());
}
// check for headers
const headers = element.querySelectorAll('ion-header');
for (let i = 0; i < headers.length; i++) {
const header = headers.item(i);
promises.push((header as any).componentOnReady());
}
// check for contents
const contents = element.querySelectorAll('ion-content');
for (let i = 0; i < contents.length; i++) {
const content = contents.item(i);
promises.push((content as any).componentOnReady());
}
// check for back buttons
const backButtons = element.querySelectorAll('ion-back-button');
for (let i = 0; i < backButtons.length; i++) {
const backButton = backButtons.item(i);
promises.push((backButton as any).componentOnReady());
}
return Promise.all(promises);
}
export function initializeViewBeforeTransition(ti: TransitionInstruction): Promise<ViewController[]> {
let leavingView: ViewController = null;
let enteringView: ViewController = null;
return startTransaction(ti).then(() => {
const viewControllers = convertComponentToViewController(ti);
ti.viewControllers = viewControllers;
leavingView = ti.nav.getActive() as ViewController;
enteringView = getEnteringView(ti, ti.nav, leavingView);
if (!leavingView && !enteringView) {
return Promise.reject(new Error('No views in the stack to remove'));
}
// mark state as initialized
// enteringView.state = STATE_INITIALIZED;
ti.requiresTransition = (ti.enteringRequiresTransition || ti.leavingRequiresTransition) && enteringView !== leavingView;
return testIfViewsCanLeaveAndEnter(enteringView, leavingView, ti);
}).then(() => {
return updateNavStacks(enteringView, leavingView, ti);
}).then(() => {
return [enteringView, leavingView];
});
}
export function updateNavStacks(enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction): Promise<any> {
return Promise.resolve().then(() => {
assert(!!(leavingView || enteringView), 'Both leavingView and enteringView are null');
assert(!!ti.resolve, 'resolve must be valid');
assert(!!ti.reject, 'reject must be valid');
const destroyQueue: ViewController[] = [];
ti.opts = ti.opts || {};
if (isDef(ti.removeStart)) {
assert(ti.removeStart >= 0, 'removeStart can not be negative');
assert(ti.removeStart >= 0, 'removeCount can not be negative');
for (let i = 0; i < ti.removeCount; i++) {
const view = ti.nav.views[i + ti.removeStart];
if (view && view !== enteringView && view !== leavingView) {
destroyQueue.push(view);
}
}
ti.opts.direction = ti.opts.direction || DIRECTION_BACK;
}
const finalBalance = ti.nav.views.length + (ti.insertViews ? ti.insertViews.length : 0) - (ti.removeCount ? ti.removeCount : 0);
assert(finalBalance >= 0, 'final balance can not be negative');
if (finalBalance === 0) {
console.warn(`You can't remove all the pages in the navigation stack. nav.pop() is probably called too many times.`);
throw new Error('Navigation stack needs at least one root page');
}
// At this point the transition can not be rejected, any throw should be an error
// there are views to insert
if (ti.viewControllers) {
// manually set the new view's id if an id was passed in the options
if (isDef(ti.opts.id)) {
enteringView.id = ti.opts.id;
}
// add the views to the stack
for (let i = 0; i < ti.viewControllers.length; i++) {
insertViewIntoNav(ti.nav, ti.viewControllers[i], ti.insertStart + i);
}
if (ti.enteringRequiresTransition) {
// default to forward if not already set
ti.opts.direction = ti.opts.direction || DIRECTION_FORWARD;
}
}
// if the views to be removed are in the beginning or middle
// and there is not a view that needs to visually transition out
// then just destroy them and don't transition anything
// batch all of lifecycles together
if (destroyQueue && destroyQueue.length) {
// TODO, figure out how the zone stuff should work in angular
for (const view of destroyQueue) {
view.willLeave(true);
view.didLeave();
view.willUnload();
}
const destroyQueuePromises: Promise<any>[] = [];
for (const viewController of destroyQueue) {
destroyQueuePromises.push(destroyView(ti.nav, ti.delegate, viewController));
}
return Promise.all(destroyQueuePromises);
}
return null;
})/*.then(() => {
// set which animation it should use if it wasn't set yet
if (ti.requiresTransition && !ti.opts.animation) {
ti.opts.animation = isDef(ti.removeStart)
? (leavingView || enteringView).getTransitionName(ti.opts.direction)
: (enteringView || leavingView).getTransitionName(ti.opts.direction);
}
});
*/
}
export function destroyView(nav: Nav, delegate: FrameworkDelegate, viewController: ViewController) {
return viewController.destroy(delegate).then(() => {
return removeViewFromList(nav, viewController);
});
}
export function removeViewFromList(nav: Nav, viewController: ViewController) {
assert(viewController.state === STATE_ATTACHED || viewController.state === STATE_DESTROYED, 'view state should be loaded or destroyed');
const index = nav.views.indexOf(viewController);
assert(index > -1, 'view must be part of the stack');
if (index >= 0) {
nav.views.splice(index, 1);
}
}
export function insertViewIntoNav(nav: Nav, view: ViewController, index: number) {
const existingIndex = nav.views.indexOf(view);
if (existingIndex > -1) {
// this view is already in the stack!!
// move it to its new location
assert(view.nav === nav, 'view is not part of the nav');
nav.views.splice(index, 0, nav.views.splice(existingIndex, 1)[0]);
} else {
assert(!view.nav, 'nav is used');
// this is a new view to add to the stack
// create the new entering view
view.nav = nav;
// give this inserted view an ID
viewIds++;
if (!view.id) {
view.id = `${nav.navId}-${viewIds}`;
}
// insert the entering view into the correct index in the stack
nav.views.splice(index, 0, view);
}
}
export function testIfViewsCanLeaveAndEnter(enteringView: ViewController, leavingView: ViewController, ti: TransitionInstruction) {
if (!ti.requiresTransition) {
return Promise.resolve();
}
const promises: Promise<any>[] = [];
if (leavingView) {
promises.push(lifeCycleTest(leavingView, 'Leave'));
}
if (enteringView) {
promises.push(lifeCycleTest(enteringView, 'Enter'));
}
if (promises.length === 0) {
return Promise.resolve();
}
// darn, async promises, gotta wait for them to resolve
return Promise.all(promises).then((values: any[]) => {
if (values.some(result => result === false)) {
ti.reject = null;
throw new Error('canEnter/Leave returned false');
}
});
}
export function lifeCycleTest(viewController: ViewController, enterOrLeave: string) {
const methodName = `ionViewCan${enterOrLeave}`;
if (viewController.instance && viewController.instance[methodName]) {
try {
const result = viewController.instance[methodName];
if (result instanceof Promise) {
return result;
}
return Promise.resolve(result !== false);
} catch (e) {
return Promise.reject(new Error(`Unexpected error when calling ${methodName}: ${e.message}`));
}
}
return Promise.resolve(true);
}
export function startTransaction(ti: TransitionInstruction): Promise<any> {
const viewsLength = ti.nav.views ? ti.nav.views.length : 0;
if (isDef(ti.removeView)) {
assert(isDef(ti.removeStart), 'removeView needs removeStart');
assert(isDef(ti.removeCount), 'removeView needs removeCount');
const index = ti.nav.views.indexOf(ti.removeView());
if (index < 0) {
return Promise.reject(new Error('The removeView was not found'));
}
ti.removeStart += index;
}
if (isDef(ti.removeStart)) {
if (ti.removeStart < 0) {
ti.removeStart = (viewsLength - 1);
}
if (ti.removeCount < 0) {
ti.removeCount = (viewsLength - ti.removeStart);
}
ti.leavingRequiresTransition = (ti.removeCount > 0) && ((ti.removeStart + ti.removeCount) === viewsLength);
}
if (isDef(ti.insertViews)) {
// allow -1 to be passed in to auto push it on the end
// and clean up the index if it's larger then the size of the stack
if (ti.insertStart < 0 || ti.insertStart > viewsLength) {
ti.insertStart = viewsLength;
}
ti.enteringRequiresTransition = (ti.insertStart === viewsLength);
}
ti.nav.transitioning = true;
return Promise.resolve();
}
export function getEnteringView(ti: TransitionInstruction, nav: Nav, leavingView: ViewController): ViewController {
if (ti.viewControllers && ti.viewControllers.length) {
// grab the very last view of the views to be inserted
// and initialize it as the new entering view
return ti.viewControllers[ti.viewControllers.length - 1];
}
if (isDef(ti.removeStart)) {
const removeEnd = ti.removeStart + ti.removeCount;
for (let i = nav.views.length - 1; i >= 0; i--) {
if ((i < ti.removeStart || i >= removeEnd) && nav.views[i] !== leavingView) {
return nav.views[i];
}
}
}
return null;
}
export function convertViewsToViewControllers(pairs: ComponentDataPair[], escapeHatch: EscapeHatch): ViewController[] {
return pairs.filter(pair => !!pair)
.map(pair => {
const applyEscapeHatch = pair === pairs[pairs.length - 1];
return new ViewController(pair.component, pair.data, applyEscapeHatch ? escapeHatch.fromExternalRouter : false, applyEscapeHatch ? escapeHatch.url : null);
});
}
export function convertComponentToViewController(ti: TransitionInstruction): ViewController[] {
if (ti.insertViews) {
assert(ti.insertViews.length > 0, 'length can not be zero');
const viewControllers = convertViewsToViewControllers(ti.insertViews, ti.escapeHatch);
assert(ti.insertViews.length === viewControllers.length, 'lengths does not match');
if (viewControllers.length === 0) {
throw new Error('No views to insert');
}
for (const viewController of viewControllers) {
if (viewController.nav && viewController.nav.navId !== ti.id) {
throw new Error('The view has already inserted into a different nav');
}
if (viewController.state === STATE_DESTROYED) {
throw new Error('The view has already been destroyed');
}
}
return viewControllers;
}
return [];
}
export function addToQueue(ti: TransitionInstruction) {
const list = transitionQueue.get(ti.id) || [];
list.push(ti);
transitionQueue.set(ti.id, list);
}
export function getQueue(id: number) {
return transitionQueue.get(id) || [];
}
export function resetQueue(id: number) {
transitionQueue.set(id, []);
}
export function getTopTransaction(id: number) {
const queue = getQueue(id);
if (!queue.length) {
return null;
}
const tmp = queue.concat();
const toReturn = tmp.shift();
transitionQueue.set(id, tmp);
return toReturn;
}
export function getDefaultTransition(config: Config) {
return config.get('mode') === 'ios' ? buildIOSTransition : buildMdTransition;
}
let viewIds = VIEW_ID_START;
const DISABLE_APP_MINIMUM_DURATION = 64;
const NOT_TRANSITIONING_TRANSITION_ID = -1;
export interface NavEvent extends CustomEvent {
target: HTMLIonNavElement;
detail: NavEventDetail;
}
export interface NavEventDetail {
isPop?: boolean;
}
export function getDefaultEscapeHatch(): EscapeHatch {
return {
fromExternalRouter: false,
};
}
export function reconcileFromExternalRouterImpl(nav: Nav, component: any, data: any = {}, escapeHatch: EscapeHatch, isTopLevel: boolean): Promise<NavResult> {
// check if the nav has an `<ion-tab>` as a parent
if (isParentTab(nav.element as any)) {
// check if the tab is selected
return updateTab(nav, component, data, escapeHatch, isTopLevel);
} else {
return updateNav(nav, component, data, escapeHatch, isTopLevel);
}
}
export function updateTab(nav: Nav, component: any, data: any, escapeHatch: EscapeHatch, isTopLevel: boolean) {
const tab = nav.element.parentElement as HTMLIonTabElement;
// yeah yeah, I know this is kind of ugly but oh well, I know the internal structure of <ion-tabs>
const tabs = tab.parentElement.parentElement as HTMLIonTabsElement;
return isTabSelected(tabs, tab).then((isSelected) => {
if (!isSelected) {
const promise = updateNav(nav, component, data, escapeHatch, false);
const app = document.querySelector('ion-app');
return app.componentOnReady().then(() => {
app.setExternalNavPromise(promise);
// okay, the tab is not selected, so we need to do a "switch" transition
// basically, we should update the nav, and then swap the tabs
return promise.then((navResult) => {
return tabs.select(tab).then(() => {
app.setExternalNavPromise(null);
return navResult;
});
});
});
}
// okay cool, the tab is already selected, so we want to see a transition
return updateNav(nav, component, data, escapeHatch, isTopLevel);
});
}
export function isTabSelected(tabsElement: HTMLIonTabsElement, tabElement: HTMLIonTabElement ): Promise<boolean> {
const promises: Promise<any>[] = [];
promises.push(tabsElement.componentOnReady());
promises.push(tabElement.componentOnReady());
return Promise.all(promises).then(() => {
return tabsElement.getSelected() === tabElement;
});
}
export function updateNav(nav: Nav,
component: any, data: any, escapeHatch: EscapeHatch, isTopLevel: boolean): Promise<NavResult> {
const url = location.pathname;
// check if the component is the top view
const activeViews = nav.getViews() as ViewController[];
if (activeViews.length === 0) {
// there isn't a view in the stack, so push one
return nav.setRoot(component, data, {}, escapeHatch);
}
const currentView = activeViews[activeViews.length - 1];
if (currentView.url === url) {
// the top view is already the component being activated, so there is no change needed
return Promise.resolve(null);
}
// check if the component is the previous view, if so, pop back to it
if (activeViews.length > 1) {
// there's at least two views in the stack
const previousView = activeViews[activeViews.length - 2];
if (previousView.url === url) {
// cool, we match the previous view, so pop it
return nav.pop(null, escapeHatch);
}
}
// check if the component is already in the stack of views, in which case we pop back to it
for (const view of activeViews) {
if (view.url === url) {
// cool, we found the match, pop back to that bad boy
return nav.popTo(view, null, escapeHatch);
}
}
// it's the top level nav, and it's not one of those other behaviors, so do a push so the user gets a chill animation
return nav.push(component, data, { animate: isTopLevel }, escapeHatch);
}
export interface IsRedirectRequired {
required: boolean;
url?: string;
}
export const POP = 'pop';
export const PUSH = 'push';
export const SET_ROOT = 'setRoot';
| packages/core/src/components/nav/nav.tsx | 1 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.049221016466617584,
0.0027152765542268753,
0.00016487762331962585,
0.0003209572460036725,
0.006193695589900017
]
|
{
"id": 3,
"code_window": [
"\n",
" // the tab's nav has not been initialized externally, so\n",
" // check if we need to initiailize it\n",
" return nav.componentOnReady()\n",
" .then(() => nav.activateFromTab());\n",
" });\n",
" }\n",
"\n",
" hostData() {\n",
" const hidden = !this.active || !this.selected;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .then(() => nav.activateFromTab(this.selected));\n"
],
"file_path": "packages/core/src/components/tab/tab.tsx",
"type": "replace",
"edit_start_line_idx": 132
} | /* tslint:disable:directive-selector */
/* tslint:disable:component-selector */
/* tslint:disable:use-host-property-decorator */
/* tslint:disable:no-input-rename */
// export for convenience.
export { ActivatedRoute, Router, RouterLink, RouterOutlet} from '@angular/router';
import { Component, Directive, Injectable, Input } from '@angular/core';
import { NavigationExtras } from '@angular/router';
@Directive({
selector: '[routerLink]',
host: {
'(click)': 'onClick()'
}
})
export class RouterLinkStubDirective {
@Input('routerLink') linkParams: any;
navigatedTo: any = null;
onClick() {
this.navigatedTo = this.linkParams;
}
}
@Component({selector: 'router-outlet', template: ''})
export class RouterOutletStubComponent { }
@Injectable()
export class RouterStub {
navigate(commands: any[], extras?: NavigationExtras) { }
}
// Only implements params and part of snapshot.params
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class ActivatedRouteStub {
// ActivatedRoute.params is Observable
private subject = new BehaviorSubject(this.testParams);
params = this.subject.asObservable();
// Test parameters
private _testParams: {};
get testParams() { return this._testParams; }
set testParams(params: {}) {
this._testParams = params;
this.subject.next(params);
}
// ActivatedRoute.snapshot.params
get snapshot() {
return { params: this.testParams };
}
}
| packages/demos/angular/testing/router-stubs.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.00017761079652700573,
0.000170454615727067,
0.000163198375958018,
0.0001694013481028378,
0.000005302980298438342
]
|
{
"id": 3,
"code_window": [
"\n",
" // the tab's nav has not been initialized externally, so\n",
" // check if we need to initiailize it\n",
" return nav.componentOnReady()\n",
" .then(() => nav.activateFromTab());\n",
" });\n",
" }\n",
"\n",
" hostData() {\n",
" const hidden = !this.active || !this.selected;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .then(() => nav.activateFromTab(this.selected));\n"
],
"file_path": "packages/core/src/components/tab/tab.tsx",
"type": "replace",
"edit_start_line_idx": 132
} | <!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="UTF-8">
<title>Hide When - Basic</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<script src="/dist/ionic.js"></script>
</head>
<body>
<ion-app>
<ion-page>
<ion-header>
<ion-toolbar>
<ion-title>Hide when - Basic</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<h2>Mode Tests</h2>
<ion-hide-when mode="md, ios">
<div>Hides on MD, iOS</div>
</ion-hide-when>
<ion-hide-when mode="md">
<div>Hides on MD only</div>
</ion-hide-when>
<ion-hide-when mode="ios">
<div>Hides on iOS only</div>
</ion-hide-when>
<h2>Orientation Tests</h2>
<ion-hide-when orientation="portrait">
<div>Hides on portrait orientation</div>
</ion-hide-when>
<ion-hide-when orientation="landscape">
<div>Hides on landscape orientation</div>
</ion-hide-when>
<h2>Platform Tests</h2>
<ion-hide-when platform="android,ios">
<div>Hides on Android and iOS</div>
</ion-hide-when>
<ion-hide-when platform="ios">
<div>Only hide on iOS</div>
</ion-hide-when>
<ion-hide-when platform="android">
<div>Only hide on Android</div>
</ion-hide-when>
<ion-hide-when platform="ipad">
<div>Only hide on ipad</div>
</ion-hide-when>
<ion-hide-when platform="phablet">
<div>Only hide on phablet</div>
</ion-hide-when>
<ion-hide-when platform="iphone">
<div>Only hide on phone</div>
</ion-hide-when>
<h2>Size Tests</h2>
<ion-hide-when size="xs">
<div>Only hide on xs</div>
</ion-hide-when>
<ion-hide-when size="sm">
<div>Only hide on sm</div>
</ion-hide-when>
<ion-hide-when size="md">
<div>Only hide on md</div>
</ion-hide-when>
<ion-hide-when size="lg">
<div>Only hide on lg</div>
</ion-hide-when>
<ion-hide-when size="xl">
<div>Only hide on xl</div>
</ion-hide-when>
<ion-hide-when size="xs, m">
<div>Only hide on XS or m</div>
</ion-hide-when>
</ion-content>
</ion-page>
</ion-app>
<script>
</script>
</body>
</html>
| packages/core/src/components/hide-when/test/basic/index.html | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.0001779925951268524,
0.00017586258763913065,
0.00017321878112852573,
0.00017628463683649898,
0.0000013690679452338372
]
|
{
"id": 3,
"code_window": [
"\n",
" // the tab's nav has not been initialized externally, so\n",
" // check if we need to initiailize it\n",
" return nav.componentOnReady()\n",
" .then(() => nav.activateFromTab());\n",
" });\n",
" }\n",
"\n",
" hostData() {\n",
" const hidden = !this.active || !this.selected;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .then(() => nav.activateFromTab(this.selected));\n"
],
"file_path": "packages/core/src/components/tab/tab.tsx",
"type": "replace",
"edit_start_line_idx": 132
} | /*! Built with http://stenciljs.com */
const { h, Context } = window.App;
class Thumbnail {
render() {
return h("slot", null);
}
static get is() { return "ion-thumbnail"; }
static get host() { return { "theme": "thumbnail" }; }
static get style() { return "ion-thumbnail {\n display: block;\n}\n\nion-thumbnail img {\n width: 100%;\n height: 100%;\n}\n\n.thumbnail-ios {\n border-radius: 0;\n width: 48px;\n height: 48px;\n}\n\n.thumbnail-ios ion-img,\n.thumbnail-ios img {\n border-radius: 0;\n overflow: hidden;\n}"; }
static get styleMode() { return "ios"; }
}
export { Thumbnail as IonThumbnail };
| packages/core/www/build/app/ion-thumbnail.ios.js | 0 | https://github.com/ionic-team/ionic-framework/commit/cc1fc2e03221c51967e9b599d4e39fedaf289dcf | [
0.00017794047016650438,
0.00017597843543626368,
0.00017401638615410775,
0.00017597843543626368,
0.000001962042006198317
]
|
{
"id": 0,
"code_window": [
" },\n",
" \"scripts\": {\n",
" \"start\": \"node webpack.dev.server.js\",\n",
" \"build\": \"cross-env NODE_ENV=production webpack --config webpack.prod.config.js\"\n",
" },\n",
" \"devDependencies\": {\n",
" \"babel-cli\": \"^6.18.0\",\n",
" \"babel-loader\": \"^6.2.8\",\n",
" \"babel-preset-es2015\": \"^6.18.0\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"build\": \"npm run clean && cross-env NODE_ENV=production webpack --config webpack.prod.config.js\",\n",
" \"clean\": \"rimraf build\"\n"
],
"file_path": "docs/site/package.json",
"type": "replace",
"edit_start_line_idx": 11
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.(jpg|gif|png)$/,
loader: 'file!img',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| docs/site/webpack.dev.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.001164628192782402,
0.0003121898043900728,
0.00016541837248951197,
0.00016688510368112475,
0.0003480785235296935
]
|
{
"id": 0,
"code_window": [
" },\n",
" \"scripts\": {\n",
" \"start\": \"node webpack.dev.server.js\",\n",
" \"build\": \"cross-env NODE_ENV=production webpack --config webpack.prod.config.js\"\n",
" },\n",
" \"devDependencies\": {\n",
" \"babel-cli\": \"^6.18.0\",\n",
" \"babel-loader\": \"^6.2.8\",\n",
" \"babel-preset-es2015\": \"^6.18.0\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"build\": \"npm run clean && cross-env NODE_ENV=production webpack --config webpack.prod.config.js\",\n",
" \"clean\": \"rimraf build\"\n"
],
"file_path": "docs/site/package.json",
"type": "replace",
"edit_start_line_idx": 11
} | // @flow weak
const defaultConstants = {
fontFamily: '"Roboto","Helvetica","Arial",sans-serif',
fontSize: 14,
fontWeightLight: 300,
fontWeightRegular: 400,
fontWeightMedium: 500,
};
export default function createTypography(palette, constants = defaultConstants) {
return {
...constants,
display4: {
fontSize: 112,
fontWeight: constants.fontWeightLight,
fontFamily: constants.fontFamily,
margin: '0.1em 0 0.2em',
},
display3: {
fontSize: 56,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
margin: '0.1em 0 0.2em',
},
display2: {
fontSize: 45,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
margin: '0.1em 0 0.2em',
},
display1: {
fontSize: 34,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
margin: '0.1em 0 0.2em',
},
headline: {
fontSize: 24,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
margin: '0.1em 0 0.2em',
},
title: {
fontSize: 21,
fontWeight: constants.fontWeightMedium,
fontFamily: constants.fontFamily,
},
subheading: {
fontSize: 16,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
},
body2: {
fontSize: 14,
fontWeight: constants.fontWeightMedium,
fontFamily: constants.fontFamily,
},
body1: {
fontSize: 14,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
},
caption: {
fontSize: 12,
fontWeight: constants.fontWeightRegular,
fontFamily: constants.fontFamily,
color: palette.text.secondary,
},
materialIcon: {
fontFamily: 'Material Icons',
fontWeight: 'normal',
fontStyle: 'normal',
fontSize: 24,
display: 'inline-block',
lineHeight: 1,
textTransform: 'none',
},
};
}
| src/styles/typography.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001719065912766382,
0.00016999332001432776,
0.00016621097165625542,
0.00017062497499864548,
0.0000017340921658615116
]
|
{
"id": 0,
"code_window": [
" },\n",
" \"scripts\": {\n",
" \"start\": \"node webpack.dev.server.js\",\n",
" \"build\": \"cross-env NODE_ENV=production webpack --config webpack.prod.config.js\"\n",
" },\n",
" \"devDependencies\": {\n",
" \"babel-cli\": \"^6.18.0\",\n",
" \"babel-loader\": \"^6.2.8\",\n",
" \"babel-preset-es2015\": \"^6.18.0\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"build\": \"npm run clean && cross-env NODE_ENV=production webpack --config webpack.prod.config.js\",\n",
" \"clean\": \"rimraf build\"\n"
],
"file_path": "docs/site/package.json",
"type": "replace",
"edit_start_line_idx": 11
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import { ListItem } from 'material-ui/List';
import Button from 'material-ui/Button';
import Collapse from 'material-ui/transitions/Collapse';
export const styleSheet = createStyleSheet('AppDrawerNavItem', (theme) => {
return {
button: theme.mixins.gutters({
borderRadius: 0,
justifyContent: 'flex-start',
textTransform: 'none',
width: '100%',
'&:hover': {
textDecoration: 'none',
},
}),
navItem: {
...theme.typography.body2,
display: 'block',
paddingTop: 0,
paddingBottom: 0,
},
navLink: {
fontWeight: 400,
display: 'flex',
paddingTop: 0,
paddingBottom: 0,
},
navLinkButton: {
color: theme.palette.text.secondary,
textIndent: 24,
fontSize: 13,
},
activeButton: {
color: theme.palette.text.primary,
},
};
});
export default class AppDrawerNavItem extends Component {
static propTypes = {
children: PropTypes.node,
onClick: PropTypes.func,
openImmediately: PropTypes.bool,
title: PropTypes.string,
to: PropTypes.string,
};
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
state = {
open: false,
};
componentWillMount() {
if (this.props.openImmediately) {
this.setState({ open: true });
}
}
render() {
const { children, title, to } = this.props;
const classes = this.context.styleManager.render(styleSheet);
if (to) {
return (
<ListItem
className={classes.navLink}
gutters={false}
>
<Button
component={Link}
to={to}
className={classNames(classes.button, classes.navLinkButton)}
activeClassName={classes.activeButton}
ripple={false}
onClick={this.props.onClick}
>
{title}
</Button>
</ListItem>
);
}
return (
<ListItem className={classes.navItem} gutters={false}>
<Button
className={classes.button}
onClick={() => this.setState({ open: !this.state.open })}
>
{title}
</Button>
<Collapse in={this.state.open} transitionDuration="auto" unmountOnExit>
{children}
</Collapse>
</ListItem>
);
}
}
| docs/site/src/components/AppDrawerNavItem.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001824116479838267,
0.000170080951647833,
0.00016489994595758617,
0.000169283666764386,
0.0000043166096475033555
]
|
{
"id": 0,
"code_window": [
" },\n",
" \"scripts\": {\n",
" \"start\": \"node webpack.dev.server.js\",\n",
" \"build\": \"cross-env NODE_ENV=production webpack --config webpack.prod.config.js\"\n",
" },\n",
" \"devDependencies\": {\n",
" \"babel-cli\": \"^6.18.0\",\n",
" \"babel-loader\": \"^6.2.8\",\n",
" \"babel-preset-es2015\": \"^6.18.0\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"build\": \"npm run clean && cross-env NODE_ENV=production webpack --config webpack.prod.config.js\",\n",
" \"clean\": \"rimraf build\"\n"
],
"file_path": "docs/site/package.json",
"type": "replace",
"edit_start_line_idx": 11
} | // @flow weak
import { AppContainer } from 'react-hot-loader';
import RedBox from 'redbox-react';
import React from 'react';
import { render } from 'react-dom';
import App from './App';
const rootEl = document.getElementById('app');
render(
<AppContainer errorReporter={RedBox}>
<App />
</AppContainer>,
rootEl,
);
if (module.hot) {
module.hot.accept('./App', () => {
const NextApp = require('./App').default; // eslint-disable-line global-require
render(
<AppContainer errorReporter={RedBox}>
<NextApp />
</AppContainer>,
rootEl,
);
});
}
| test/regressions/site/src/index.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017049649613909423,
0.00016948161646723747,
0.0001685746101429686,
0.00016937375767156482,
7.883051011958742e-7
]
|
{
"id": 1,
"code_window": [
" \"marked\": \"^0.3.5\",\n",
" \"object-assign\": \"^4.1.0\",\n",
" \"raw-loader\": \"^0.5.1\",\n",
" \"react-hot-loader\": \"^3.0.0-beta.2\",\n",
" \"rimraf\": \"^2.5.2\",\n",
" \"style-loader\": \"^0.13.1\",\n",
" \"webpack\": \"^1.13.3\",\n",
" \"webpack-dev-server\": \"^1.16.2\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"redbox-react\": \"^1.3.1\",\n"
],
"file_path": "docs/site/package.json",
"type": "add",
"edit_start_line_idx": 28
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.(jpg|gif|png)$/,
loader: 'file!img',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| docs/site/webpack.dev.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00024352638865821064,
0.00018156169971916825,
0.00016853379202075303,
0.0001717257109703496,
0.000025331280994578265
]
|
{
"id": 1,
"code_window": [
" \"marked\": \"^0.3.5\",\n",
" \"object-assign\": \"^4.1.0\",\n",
" \"raw-loader\": \"^0.5.1\",\n",
" \"react-hot-loader\": \"^3.0.0-beta.2\",\n",
" \"rimraf\": \"^2.5.2\",\n",
" \"style-loader\": \"^0.13.1\",\n",
" \"webpack\": \"^1.13.3\",\n",
" \"webpack-dev-server\": \"^1.16.2\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"redbox-react\": \"^1.3.1\",\n"
],
"file_path": "docs/site/package.json",
"type": "add",
"edit_start_line_idx": 28
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
],
},
resolve: {
alias: {
'material-ui': path.resolve(__dirname, '../../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| test/regressions/site/webpack.dev.config.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00024352638865821064,
0.0001852278655860573,
0.00016853379202075303,
0.00017137370014097542,
0.000029171485948609188
]
|
{
"id": 1,
"code_window": [
" \"marked\": \"^0.3.5\",\n",
" \"object-assign\": \"^4.1.0\",\n",
" \"raw-loader\": \"^0.5.1\",\n",
" \"react-hot-loader\": \"^3.0.0-beta.2\",\n",
" \"rimraf\": \"^2.5.2\",\n",
" \"style-loader\": \"^0.13.1\",\n",
" \"webpack\": \"^1.13.3\",\n",
" \"webpack-dev-server\": \"^1.16.2\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"redbox-react\": \"^1.3.1\",\n"
],
"file_path": "docs/site/package.json",
"type": "add",
"edit_start_line_idx": 28
} | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { spy } from 'sinon';
import { createShallowWithContext } from 'test/utils';
import Collapse, { styleSheet } from './Collapse';
describe('<Collapse />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a Transition', () => {
const wrapper = shallow(<Collapse />);
assert.strictEqual(wrapper.is('Transition'), true, 'is a Transition component');
});
it('should render a container around the wrapper', () => {
const wrapper = shallow(<Collapse containerClassName="woof" />);
assert.strictEqual(wrapper.childAt(0).is('div'), true, 'should be a div');
assert.strictEqual(wrapper.childAt(0).hasClass(classes.container), true,
'should have the container class');
assert.strictEqual(wrapper.childAt(0).hasClass('woof'), true, 'should have the user class');
});
it('should render a wrapper around the children', () => {
const children = <h1>Hello</h1>;
const wrapper = shallow(<Collapse>{children}</Collapse>);
assert.strictEqual(wrapper.childAt(0).childAt(0).is('div'), true, 'should be a div');
assert.strictEqual(wrapper.childAt(0).childAt(0).children().equals(children), true,
'should wrap the children');
});
describe('event callbacks', () => {
it('should fire event callbacks', () => {
const events = [
'onEnter',
'onEntering',
'onEntered',
'onExit',
'onExiting',
'onExited',
];
const handlers = events.reduce((result, n) => {
result[n] = spy();
return result;
}, {});
const wrapper = shallow(<Collapse {...handlers} />);
events.forEach((n) => {
const event = n.charAt(2).toLowerCase() + n.slice(3);
wrapper.simulate(event, { style: {} });
assert.strictEqual(handlers[n].callCount, 1, `should have called the ${n} handler`);
});
});
});
describe('transition lifecycle', () => {
let wrapper;
let instance;
before(() => {
wrapper = shallow(<Collapse />);
instance = wrapper.instance();
});
describe('handleEnter()', () => {
let element;
before(() => {
element = { style: { height: 32 } };
instance.handleEnter(element);
});
it('should set element height to 0 initially', () => {
assert.strictEqual(element.style.height, '0px', 'should set the height to 0');
});
});
describe('handleEntering()', () => {
let element;
before(() => {
element = { style: { height: 0 } };
instance.wrapper = { clientHeight: 666 };
instance.handleEntering(element);
});
it('should set element transition duration', () => {
assert.strictEqual(element.style.transitionDuration, '300ms',
'should have the default 300ms duration');
});
it('should set height to the wrapper height', () => {
assert.strictEqual(element.style.height, '666px', 'should have 666px height');
});
});
describe('handleEntered()', () => {
let element;
before(() => {
element = { style: { height: 666, transitionDuration: '500ms' } };
instance.handleEntered(element);
});
it('should set element transition duration to 0 to fix a safari bug', () => {
assert.strictEqual(element.style.transitionDuration, '0ms', 'should have 0ms duration');
});
it('should set height to auto', () => {
assert.strictEqual(element.style.height, 'auto', 'should have auto height');
});
});
describe('handleExit()', () => {
let element;
before(() => {
element = { style: { height: 'auto' } };
instance.wrapper = { clientHeight: 666 };
instance.handleExit(element);
});
it('should set height to the wrapper height', () => {
assert.strictEqual(element.style.height, '666px', 'should have 666px height');
});
});
describe('handleExiting()', () => {
let element;
before(() => {
element = { style: { height: 666 } };
instance.handleExiting(element);
});
it('should set height to the 0', () => {
assert.strictEqual(element.style.height, '0px', 'should have 0px height');
});
});
});
});
| src/transitions/Collapse.spec.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017496940563432872,
0.00017079600365832448,
0.000166758632985875,
0.0001709888456389308,
0.0000024571450012444984
]
|
{
"id": 1,
"code_window": [
" \"marked\": \"^0.3.5\",\n",
" \"object-assign\": \"^4.1.0\",\n",
" \"raw-loader\": \"^0.5.1\",\n",
" \"react-hot-loader\": \"^3.0.0-beta.2\",\n",
" \"rimraf\": \"^2.5.2\",\n",
" \"style-loader\": \"^0.13.1\",\n",
" \"webpack\": \"^1.13.3\",\n",
" \"webpack-dev-server\": \"^1.16.2\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"redbox-react\": \"^1.3.1\",\n"
],
"file_path": "docs/site/package.json",
"type": "add",
"edit_start_line_idx": 28
} | // @flow weak
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import SwitchBase from '../internal/SwitchBase';
export const styleSheet = createStyleSheet('Radio', (theme) => {
return {
default: {
color: theme.palette.text.secondary,
},
checked: {
color: theme.palette.accent[500],
},
label: {
marginLeft: -12,
display: 'flex',
alignItems: 'center',
cursor: 'pointer',
},
};
});
export default function Radio(props, context) {
const {
className,
checkedClassName,
label,
labelClassName,
onChange,
value,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
const switchProps = {
className: classNames(classes.default, className),
checkedClassName: classNames(classes.checked, checkedClassName),
icon: 'radio_button_unchecked',
checkedIcon: 'radio_button_checked',
type: 'radio',
value,
onChange,
...other,
};
if (label) {
switchProps['aria-label'] = label;
return (
<label className={classNames(classes.label, labelClassName)} role="presentation">
<SwitchBase {...switchProps} />
<span aria-hidden="true" role="presentation">{label}</span>
</label>
);
}
return <SwitchBase {...switchProps} />;
}
Radio.propTypes = {
checkedClassName: PropTypes.string,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
label: PropTypes.string,
labelClassName: PropTypes.string,
name: PropTypes.string,
onChange: PropTypes.func,
value: PropTypes.string,
};
Radio.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
| src/Radio/Radio.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001762901956681162,
0.00017234421102330089,
0.00016902817878872156,
0.00017227910575456917,
0.000002397955995547818
]
|
{
"id": 2,
"code_window": [
" loaders: ['babel'],\n",
" },\n",
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 33
} | {
"name": "material-ui-docs",
"private": true,
"version": "0.16.0",
"description": "Documentation site for material-ui",
"repository": {
"type": "git",
"url": "https://github.com/callemall/material-ui.git"
},
"scripts": {
"start": "node webpack.dev.server.js",
"build": "cross-env NODE_ENV=production webpack --config webpack.prod.config.js"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-1": "^6.5.0",
"cross-env": "^3.1.3",
"css-loader": "^0.26.0",
"file-loader": "^0.9.0",
"highlight.js": "^9.8.0",
"img-loader": "^1.3.1",
"marked": "^0.3.5",
"object-assign": "^4.1.0",
"raw-loader": "^0.5.1",
"react-hot-loader": "^3.0.0-beta.2",
"rimraf": "^2.5.2",
"style-loader": "^0.13.1",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"prismjs": "^1.5.1",
"react-redux": "^4.4.6",
"react-router": "^3.0.0",
"redux": "^3.5.2"
}
}
| docs/site/package.json | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017564439622219652,
0.00016992117161862552,
0.0001640419359318912,
0.00016915297601372004,
0.0000038460129871964455
]
|
{
"id": 2,
"code_window": [
" loaders: ['babel'],\n",
" },\n",
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 33
} | // @flow weak
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import Avatar from 'material-ui/Avatar';
import { deepOrange, deepPurple } from 'material-ui/styles/colors';
const styleSheet = createStyleSheet('LetterAvatars', () => ({
avatar: {
margin: 10,
},
orangeAvatar: {
margin: 10,
color: '#fff',
backgroundColor: deepOrange[500],
},
purpleAvatar: {
margin: 10,
color: '#fff',
backgroundColor: deepPurple[500],
},
row: {
display: 'flex',
justifyContent: 'center',
},
}));
export default function LetterAvatars(props, context) {
const classes = context.styleManager.render(styleSheet);
return (
<div className={classes.row}>
<Avatar
icon="H"
className={classes.avatar}
/>
<Avatar
icon="N"
className={classes.orangeAvatar}
/>
<Avatar
icon="O"
className={classes.purpleAvatar}
/>
</div>
);
}
LetterAvatars.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
| docs/site/src/demos/avatars/LetterAvatars.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017602597654331475,
0.00017426739213988185,
0.00016915297601372004,
0.00017550727352499962,
0.000002406335170235252
]
|
{
"id": 2,
"code_window": [
" loaders: ['babel'],\n",
" },\n",
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 33
} | ListSubheader
=============
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:-----|:-----|
| children | node | | The content of the ListSubheader. |
| className | string | | The CSS class name of the root element. |
| inset | bool | false | If true, the ListSubheader will be indented. |
| primary | bool | false | If true, the ListSubheader will have the theme primary color. |
Other properties (no documented) are applied to the root element.
| docs/api/List/ListSubheader.md | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017119811673182994,
0.0001707370684016496,
0.00017027603462338448,
0.0001707370684016496,
4.610410542227328e-7
]
|
{
"id": 2,
"code_window": [
" loaders: ['babel'],\n",
" },\n",
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 33
} | ListItem
========
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:-----|:-----|
| button | bool | false | |
| children | node | | |
| className | string | | The CSS class name of the root element. |
| component | union | 'div' | |
| dense | bool | false | |
| divider | bool | false | |
| gutters | bool | true | |
Other properties (no documented) are applied to the root element.
| docs/api/List/ListItem.md | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001731355587253347,
0.00017137592658400536,
0.00016915297601372004,
0.0001718392304610461,
0.000001658560222494998
]
|
{
"id": 3,
"code_window": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 38
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.(jpg|gif|png)$/,
loader: 'file!img',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| docs/site/webpack.dev.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.9946711659431458,
0.14273475110530853,
0.0001652749051572755,
0.00016938232874963433,
0.34780365228652954
]
|
{
"id": 3,
"code_window": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 38
} | 'use strict';
const path = require('path');
/*
* Return path to write file to inside outputDir.
*
* @param {object} pathObj
* path objects from path.parse
*
* @param {string} innerPath
* Path (relative to options.svgDir) to svg file
* e.g. if svgFile was /home/user/icons/path/to/svg/file.svg
* options.svgDir is /home/user/icons/
* innerPath is path/to/svg
*
* @param {object} options
* @return {string} output file dest relative to outputDir
*/
function defaultDestRewriter(pathObj, innerPath, options) {
let fileName = pathObj.base;
if (options.fileSuffix) {
fileName.replace(options.fileSuffix, '.svg');
} else {
fileName = fileName.replace('.svg', '.js');
}
fileName = fileName.replace(/_/g, '-');
return path.join(innerPath, fileName);
}
module.exports = defaultDestRewriter;
| packages/icon-builder/filters/rename/default.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017191558436024934,
0.000167954305652529,
0.00016455895092803985,
0.00016767135821282864,
0.00000265697849499702
]
|
{
"id": 3,
"code_window": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 38
} | node_modules
npm-debug.log
local.log
dist
build
coverage
selenium-output
test/regressions/screenshots/output
# Exclude compiled files
/lib
icon-builder/js
icon-builder/jsx
# Exclude IDE project folders
.idea
*.sublime-project
*.sublime-workspace
jsconfig.json
# OS files
.DS_STORE
# tmp
tmp*
| .gitignore | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00016678280371706933,
0.00016515592869836837,
0.00016400519234593958,
0.00016467981913592666,
0.0000011828773267552606
]
|
{
"id": 3,
"code_window": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.dev.config.js",
"type": "replace",
"edit_start_line_idx": 38
} | # Menus
Menus display a list of choices on a transient sheet of material.
Menus appear upon interaction with a button, action, or other control. They display a list of choices, with one choice per line.
Menu items may be disabled if not applicable to a certain context. Contextual menus dynamically change their available menu items based on the current state of the app.
Menus should not be used as a primary method for navigation within an app.
## Simple menus
Simple menus open over the anchor element by default (this option can be changed via props). When close to a screen edge, simple menus vertically realign to make all menu items are completely visible.
Choosing an option should immediately ideally commit the option and close the menu.
**Disambiguation**: In contrast to simple menus, simple dialogs can present additional detail related to the options available for a list item or provide navigational or orthogonal actions related to the primary task. Although they can display the same content, simple menus are preferred over simple dialogs because simple menus are less disruptive to the user’s current context.
{{demo='demos/menus/SimpleMenu.js'}}
If used for item selection, when opened, simple menus attempt to vertically align the currently selected menu item with the anchor element. The currently selected menu item is set using the `selected` prop.
{{demo='demos/menus/SimpleListMenu.js'}}
If text in a simple menu wraps to a second line, use a simple dialog instead. Simple dialogs can have rows with varying heights.
## TextField select menus
Coming soon...
| docs/site/src/demos/menus/menus.md | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001674212544457987,
0.0001659182016737759,
0.00016407293151132762,
0.00016626041906420141,
0.0000013882005305276834
]
|
{
"id": 4,
"code_window": [
"const webpack = require('webpack');\n",
"\n",
"module.exports = {\n",
" devtool: 'source-map',\n",
" context: path.resolve(__dirname),\n",
" entry: {\n",
" main: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 6
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.(jpg|gif|png)$/,
loader: 'file!img',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| docs/site/webpack.dev.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.9978585839271545,
0.14319588243961334,
0.00017213162209372967,
0.0002931332273874432,
0.34891629219055176
]
|
{
"id": 4,
"code_window": [
"const webpack = require('webpack');\n",
"\n",
"module.exports = {\n",
" devtool: 'source-map',\n",
" context: path.resolve(__dirname),\n",
" entry: {\n",
" main: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 6
} | // @flow weak
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
export const styleSheet = createStyleSheet('Toolbar', (theme) => {
return {
root: {
position: 'relative',
display: 'flex',
alignItems: 'center',
height: 56,
},
gutters: theme.mixins.gutters({}),
[theme.breakpoints.up('sm')]: {
root: {
height: 64,
},
},
};
});
export default function Toolbar(props, context) {
const {
children,
className: classNameProp,
gutters,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
const className = classNames(classes.root, {
[classes.gutters]: gutters,
}, classNameProp);
return (
<div className={className} {...other} >
{children}
</div>
);
}
Toolbar.propTypes = {
/**
* Can be a `ToolbarGroup` to render a group of related items.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* If set to true, enables gutter padding.
*/
gutters: PropTypes.bool,
};
Toolbar.defaultProps = {
gutters: true,
};
Toolbar.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
| src/Toolbar/Toolbar.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00024206314992625266,
0.00019024642824660987,
0.0001656911481404677,
0.00017470883904024959,
0.000025253413696191274
]
|
{
"id": 4,
"code_window": [
"const webpack = require('webpack');\n",
"\n",
"module.exports = {\n",
" devtool: 'source-map',\n",
" context: path.resolve(__dirname),\n",
" entry: {\n",
" main: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 6
} | <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48">
<path d="M0 0h48v48H0z" fill="none"/>
<path d="M24 14V6H4v36h40V14H24zM12 38H8v-4h4v4zm0-8H8v-4h4v4zm0-8H8v-4h4v4zm0-8H8v-4h4v4zm8 24h-4v-4h4v4zm0-8h-4v-4h4v4zm0-8h-4v-4h4v4zm0-8h-4v-4h4v4zm20 24H24v-4h4v-4h-4v-4h4v-4h-4v-4h16v20zm-4-16h-4v4h4v-4zm0 8h-4v4h4v-4z"/>
</svg>
| packages/icon-builder/test/fixtures/material-design-icons/svg/social/svg/design/ic_domain_48px.svg | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00016832725668791682,
0.00016832725668791682,
0.00016832725668791682,
0.00016832725668791682,
0
]
|
{
"id": 4,
"code_window": [
"const webpack = require('webpack');\n",
"\n",
"module.exports = {\n",
" devtool: 'source-map',\n",
" context: path.resolve(__dirname),\n",
" entry: {\n",
" main: [\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 6
} | ListItemSecondaryAction
=======================
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:-----|:-----|
| children | node | | |
| className | string | | The CSS class name of the root element. |
Other properties (no documented) are applied to the root element.
| docs/api/List/ListItemSecondaryAction.md | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017265418136958033,
0.0001718105049803853,
0.00017096681403927505,
0.0001718105049803853,
8.436836651526392e-7
]
|
{
"id": 5,
"code_window": [
" output: {\n",
" path: path.join(__dirname, 'build'),\n",
" filename: 'bundle.js',\n",
" publicPath: '/build/',\n",
" },\n",
" module: {\n",
" loaders: [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" publicPath: 'build/',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 16
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.(jpg|gif|png)$/,
loader: 'file!img',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| docs/site/webpack.dev.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.04329228028655052,
0.008251259103417397,
0.00017042465333361179,
0.0003097275330219418,
0.01476020086556673
]
|
{
"id": 5,
"code_window": [
" output: {\n",
" path: path.join(__dirname, 'build'),\n",
" filename: 'bundle.js',\n",
" publicPath: '/build/',\n",
" },\n",
" module: {\n",
" loaders: [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" publicPath: 'build/',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 16
} | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import CircularProgress, { styleSheet } from './CircularProgress';
describe('<CircularProgress />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a div with the root class', () => {
const wrapper = shallow(<CircularProgress />);
assert.strictEqual(wrapper.is('div'), true, 'should be a div');
});
it('should render with the user and root classes', () => {
const wrapper = shallow(<CircularProgress className="woof" />);
assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
});
it('should contain an SVG with the svg class, and a circle with the circle class', () => {
const wrapper = shallow(<CircularProgress />);
const svg = wrapper.childAt(0);
assert.strictEqual(svg.is('svg'), true, 'should be a svg');
assert.strictEqual(svg.hasClass(classes.svg), true, 'should have the svg class');
assert.strictEqual(svg.childAt(0).is('circle'), true, 'should be a circle');
assert.strictEqual(svg.childAt(0).hasClass(classes.circle), true, 'should have the circle class');
});
});
| src/Progress/CircularProgress.spec.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017901090905070305,
0.00017508823657408357,
0.00017294927965849638,
0.00017419637879356742,
0.0000024177315935958177
]
|
{
"id": 5,
"code_window": [
" output: {\n",
" path: path.join(__dirname, 'build'),\n",
" filename: 'bundle.js',\n",
" publicPath: '/build/',\n",
" },\n",
" module: {\n",
" loaders: [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" publicPath: 'build/',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 16
} | /* eslint-disable flowtype/require-valid-file-annotation */
export default from './Dialog';
export Dialog from './Dialog';
export DialogActions from './DialogActions';
export DialogTitle from './DialogTitle';
export DialogContent from './DialogContent';
| src/Dialog/index.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017220697191078216,
0.00017220697191078216,
0.00017220697191078216,
0.00017220697191078216,
0
]
|
{
"id": 5,
"code_window": [
" output: {\n",
" path: path.join(__dirname, 'build'),\n",
" filename: 'bundle.js',\n",
" publicPath: '/build/',\n",
" },\n",
" module: {\n",
" loaders: [\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" publicPath: 'build/',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 16
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M255.125 99.406c-65.804 0-124.928 29.754-167.656 69.875-42.73 40.122-69.75 90.556-69.75 135.126 0 44.57 29.306 75.8 72.56 93.78 43.257 17.983 101.178 24.845 164.845 24.845s121.588-6.86 164.844-24.842c43.254-17.982 72.53-49.212 72.53-93.782 0-44.57-26.99-95.004-69.72-135.125-42.727-40.12-101.85-69.874-167.655-69.874zm0 18.688c60.148 0 115.033 27.43 154.844 64.812 39.81 37.382 63.842 84.752 63.842 121.5 0 36.748-21.747 60.17-61.03 76.5-39.285 16.33-95.373 23.438-157.657 23.438-62.284 0-118.404-7.107-157.688-23.438-39.283-16.33-61.03-39.752-61.03-76.5s24.032-84.118 63.843-121.5c39.81-37.38 94.727-64.812 154.875-64.812zm-54.72 38.594c-3.344-.012-7.06.508-11.124 1.656-20.917 5.907-33.254 41.475-55.06 62.28-24.13 23.022-62.7 40.588-67.907 72.657-3.98 18.225 7.183 36.783 25.374 41.658 18.726 5.017 38.233-6.243 43.25-24.97.723-2.695 1.083-5.41 1.157-8.093h.156c-1.697-38.35 7.258-90.663 56.03-93.5 39.072-2.273 40.46-51.575 8.126-51.688zm87.345 5.218c-11.417.332-23.452 6.93-23.188 18 .53 22.14 37.174 29.432 42.657 1.53 2.74-13.95-8.053-19.862-19.47-19.53zm60 19.438c-18.423.31-18.102 16.73-8.47 23.062 49.25 32.365 8.474 45.84-16.686 32.03-23.675-12.998-87.44-19.36-111.47 3.94-19.138 18.553-3.26 53.928 26.407 32.78 49.634-35.375 94.1-15.667 113.5 28.78l.064-.03c9.498 21.795 33.91 34.08 57.53 27.75 26.004-6.967 41.594-33.934 34.626-59.937-1.334-4.978-3.41-9.56-6.063-13.69-11.404-37.086-37.062-62.783-77.218-73.03-4.758-1.214-8.808-1.713-12.22-1.656zm47.78 70.75c13.585-.253 25.967 8.665 29.658 22.437 4.353 16.248-5.16 32.71-21.407 37.064-16.247 4.354-32.677-5.128-37.03-21.375-4.353-16.248 5.127-32.71 21.375-37.064 2.03-.544 4.08-.875 6.094-1 .44-.027.873-.054 1.31-.062zm-295.186 32.094c.48-.012.952 0 1.437.03 1.11.072 2.224.263 3.345.563 8.97 2.405 14.153 11.376 11.75 20.345-2.404 8.97-11.374 14.153-20.344 11.75-8.97-2.403-14.152-11.373-11.75-20.344 1.973-7.358 8.378-12.178 15.564-12.342zm179.53 10.562c-15.81.215-34.724 5.274-47.468 12.97-14.87 5.774-25.5 20.262-25.5 37.092 0 21.845 17.907 39.75 39.75 39.75.43 0 .854-.017 1.28-.03 32.518 2.444 76.975-14.784 76.47-31.813-.573-19.364-36.953-.27-38-21.876-.47-9.746 27.4-11.914 21.03-25.5-3.588-7.66-14.52-10.77-27.56-10.594zm-33.218 28.97c11.743 0 21.094 9.35 21.094 21.092 0 11.745-9.35 21.063-21.094 21.063-11.743 0-21.062-9.318-21.062-21.063 0-11.744 9.32-21.093 21.062-21.093z" /></svg> | packages/icon-builder/test/fixtures/game-icons/svg/icons/lorc/originals/svg/000000/transparent/acid-blob.svg | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0037034349516034126,
0.0037034349516034126,
0.0037034349516034126,
0.0037034349516034126,
0
]
|
{
"id": 6,
"code_window": [
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 28
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'source-map',
context: path.resolve(__dirname),
entry: {
main: [
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
react: path.resolve(__dirname, 'node_modules/react'),
lodash: path.resolve(__dirname, '../../node_modules/lodash'),
},
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
],
};
| docs/site/webpack.prod.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.6514814496040344,
0.09341857582330704,
0.0001675694657023996,
0.0001725422771414742,
0.2278287261724472
]
|
{
"id": 6,
"code_window": [
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 28
} | // @flow weak
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import MuiThemeProvider, { MUI_SHEET_ORDER } from 'material-ui/styles/MuiThemeProvider';
import createPalette from 'material-ui/styles/palette';
import createMuiTheme from 'material-ui/styles/theme';
import { blue, pink } from 'material-ui/styles/colors';
import { lightTheme, darkTheme, setPrismTheme } from 'docs/site/src/utils/prism';
import AppRouter from './AppRouter';
function App(props) {
const { dark, ...other } = props;
const palette = createPalette({
primary: blue,
accent: pink,
type: dark ? 'dark' : 'light',
});
const { styleManager, theme } = MuiThemeProvider.createDefaultContext({
theme: createMuiTheme({ palette }),
});
styleManager.setSheetOrder(MUI_SHEET_ORDER.concat([
'AppContent',
'AppDrawer',
'AppDrawerNavItem',
'AppFrame',
'MarkdownDocs',
'MarkdownElement',
'Demo',
]));
if (dark) {
setPrismTheme(darkTheme);
} else {
setPrismTheme(lightTheme);
}
return (
<MuiThemeProvider theme={theme} styleManager={styleManager} {...other}>
<AppRouter />
</MuiThemeProvider>
);
}
App.propTypes = {
dark: PropTypes.bool.isRequired,
};
export default connect((state) => ({ dark: state.dark }))(App);
| docs/site/src/components/App.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001752327079884708,
0.0001728416682453826,
0.00016860917094163597,
0.00017316995945293456,
0.000002159430550818797
]
|
{
"id": 6,
"code_window": [
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 28
} | <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M6 8c1.11 0 2-.9 2-2s-.89-2-2-2c-1.1 0-2 .9-2 2s.9 2 2 2zm6 0c1.11 0 2-.9 2-2s-.89-2-2-2c-1.11 0-2 .9-2 2s.9 2 2 2zM6 9.2c-1.67 0-5 .83-5 2.5V13h10v-1.3c0-1.67-3.33-2.5-5-2.5zm6 0c-.25 0-.54.02-.84.06.79.6 1.34 1.4 1.34 2.44V13H17v-1.3c0-1.67-3.33-2.5-5-2.5z"/></svg> | packages/icon-builder/test/fixtures/material-design-icons/svg/social/svg/production/ic_group_18px.svg | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00016880060138646513,
0.00016880060138646513,
0.00016880060138646513,
0.00016880060138646513,
0
]
|
{
"id": 6,
"code_window": [
" {\n",
" test: /\\.svg$/,\n",
" loader: 'file',\n",
" include: /assets\\/images/,\n",
" },\n",
" {\n",
" test: /\\.md$/,\n",
" loader: 'raw',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" },\n",
" {\n",
" test: /\\.(jpg|gif|png)$/,\n",
" loader: 'file!img',\n"
],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 28
} | MuiThemeProvider
================
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:-----|:-----|
| <span style="color: #31a148">children *</span> | node | | |
| styleManager | object | | |
| theme | object | | |
Other properties (no documented) are applied to the root element.
| docs/api/styles/MuiThemeProvider.md | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.0001730269577819854,
0.00017070744070224464,
0.0001683879381744191,
0.00017070744070224464,
0.0000023195098037831485
]
|
{
"id": 7,
"code_window": [
" resolve: {\n",
" alias: {\n",
" docs: path.resolve(__dirname, '../../docs'),\n",
" 'material-ui': path.resolve(__dirname, '../../src'),\n",
" react: path.resolve(__dirname, 'node_modules/react'),\n",
" lodash: path.resolve(__dirname, '../../node_modules/lodash'),\n",
" },\n",
" },\n",
" plugins: [\n",
" new webpack.optimize.OccurenceOrderPlugin(),\n",
" new webpack.optimize.DedupePlugin(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | // @flow weak
const path = require('path');
const webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'inline-source-map',
context: path.resolve(__dirname),
entry: {
main: [
'eventsource-polyfill', // hot reloading in IE
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./src/index',
],
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build/',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel'],
},
{
test: /\.svg$/,
loader: 'file',
include: /assets\/images/,
},
{
test: /\.(jpg|gif|png)$/,
loader: 'file!img',
include: /assets\/images/,
},
{
test: /\.md$/,
loader: 'raw',
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
resolve: {
alias: {
docs: path.resolve(__dirname, '../../docs'),
'material-ui': path.resolve(__dirname, '../../src'),
},
},
progress: true,
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
| docs/site/webpack.dev.config.js | 1 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.9938446283340454,
0.14260831475257874,
0.00016545118705835193,
0.00017186379409395158,
0.34751763939857483
]
|
{
"id": 7,
"code_window": [
" resolve: {\n",
" alias: {\n",
" docs: path.resolve(__dirname, '../../docs'),\n",
" 'material-ui': path.resolve(__dirname, '../../src'),\n",
" react: path.resolve(__dirname, 'node_modules/react'),\n",
" lodash: path.resolve(__dirname, '../../node_modules/lodash'),\n",
" },\n",
" },\n",
" plugins: [\n",
" new webpack.optimize.OccurenceOrderPlugin(),\n",
" new webpack.optimize.DedupePlugin(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | // @flow weak
const path = require('path');
const glob = require('glob');
function runTest(testFn) {
function tests(testPath) {
return function regressions(browser) {
browser
.url(`${browser.launch_url}/#/${testPath}`)
.waitForElementVisible('[data-reactroot]', 6000)
.perform((client, done) => testFn(client, testPath, done));
};
}
function reduceTests(res, n) {
const testPath = n.replace(/^.*?tests\/(.*).js$/i, '$1');
res[testPath] = tests(testPath);
return res;
}
return glob
.sync(path.resolve(__dirname, 'site/src/tests/**/*.js'))
.reduce(reduceTests, {
beforeEach(browser) {
browser
.setWindowPosition(0, 0)
.resizeWindow(1200, 1000);
},
after(browser) {
browser.end();
},
});
}
module.exports = runTest;
| test/regressions/runTest.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.000818270375020802,
0.0003361155104357749,
0.00016782690363470465,
0.00017918240337166935,
0.0002785046526696533
]
|
{
"id": 7,
"code_window": [
" resolve: {\n",
" alias: {\n",
" docs: path.resolve(__dirname, '../../docs'),\n",
" 'material-ui': path.resolve(__dirname, '../../src'),\n",
" react: path.resolve(__dirname, 'node_modules/react'),\n",
" lodash: path.resolve(__dirname, '../../node_modules/lodash'),\n",
" },\n",
" },\n",
" plugins: [\n",
" new webpack.optimize.OccurenceOrderPlugin(),\n",
" new webpack.optimize.DedupePlugin(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | // @flow weak
import React, { Component, PropTypes, cloneElement, isValidElement } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import ButtonBase from '../internal/ButtonBase';
export const styleSheet = createStyleSheet('BottomNavigationButton', (theme) => {
return {
root: {
transition: `${
theme.transitions.create('color', '250ms')}, ${
theme.transitions.create('padding-top', '250ms')}`,
paddingTop: 8,
paddingBottom: 10,
paddingLeft: 12,
paddingRight: 12,
minWidth: 80,
maxWidth: 168,
background: 'none',
color: theme.palette.text.secondary,
flex: '1',
},
selected: {
paddingTop: 6,
color: theme.palette.primary[500],
},
selectedIconOnly: {
paddingTop: 16,
},
label: {
fontSize: theme.typography.fontSize - 2,
opacity: 1,
transition: 'font-size 0.2s, opacity 0.2s',
transitionDelay: '0.1s',
},
selectedLabel: {
fontSize: theme.typography.fontSize,
},
hiddenLabel: {
opacity: 0,
transitionDelay: '0s',
},
icon: {
display: 'block',
},
};
});
export default class BottomNavigationButton extends Component {
handleChangeIndex = (event) => {
const { onChangeIndex, index, onClick } = this.props;
onChangeIndex(index);
if (onClick) {
onClick(event);
}
};
render() {
const {
label,
icon: iconProp,
selected,
className: classNameProp,
showLabel: showLabelProp,
onChangeIndex, // eslint-disable-line no-unused-vars
index, // eslint-disable-line no-unused-vars
...other
} = this.props;
const classes = this.context.styleManager.render(styleSheet);
const className = classNames(classes.root, {
[classes.selected]: selected,
[classes.selectedIconOnly]: !showLabelProp && !selected,
}, classNameProp);
const classNameIcon = classNames(classes.icon,
isValidElement(iconProp) ? iconProp.props.className : null);
const classNameLabel = classNames(classes.label, {
[classes.selectedLabel]: selected,
[classes.hiddenLabel]: !showLabelProp && !selected,
});
const icon = isValidElement(iconProp) ?
cloneElement(iconProp, { className: classNameIcon }) :
<span className="material-icons">{iconProp}</span>;
return (
<ButtonBase
className={className}
focusRipple
{...other}
onClick={this.handleChangeIndex}
>
{icon}
<div className={classNameLabel}>
{label}
</div>
</ButtonBase>
);
}
}
BottomNavigationButton.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The icon element. If a string is passed, it will be used as a material icon font ligature.
*/
icon: PropTypes.node,
/**
* @ignore
*/
index: PropTypes.number,
/**
* The label element.
*/
label: PropTypes.node,
/**
* @ignore
*/
onChangeIndex: PropTypes.func,
/**
* @ignore
*/
onClick: PropTypes.func,
/**
* @ignore
*/
selected: PropTypes.bool,
/**
* If true, the BottomNavigationButton will show his label.
*/
showLabel: PropTypes.bool,
};
BottomNavigationButton.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
| src/BottomNavigation/BottomNavigationButton.js | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017549055337440223,
0.00017127240425907075,
0.00016400347521994263,
0.0001714622922008857,
0.0000028627011943171965
]
|
{
"id": 7,
"code_window": [
" resolve: {\n",
" alias: {\n",
" docs: path.resolve(__dirname, '../../docs'),\n",
" 'material-ui': path.resolve(__dirname, '../../src'),\n",
" react: path.resolve(__dirname, 'node_modules/react'),\n",
" lodash: path.resolve(__dirname, '../../node_modules/lodash'),\n",
" },\n",
" },\n",
" plugins: [\n",
" new webpack.optimize.OccurenceOrderPlugin(),\n",
" new webpack.optimize.DedupePlugin(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/site/webpack.prod.config.js",
"type": "replace",
"edit_start_line_idx": 44
} | CardMedia
=========
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:-----|:-----|
| className | string | | The CSS class name of the root element. |
Other properties (no documented) are applied to the root element.
| docs/api/Card/CardMedia.md | 0 | https://github.com/mui/material-ui/commit/420a835aae583c65864e0f6a10e0f83124bc1ff8 | [
0.00017168479098472744,
0.0001696418330539018,
0.00016759887512307614,
0.0001696418330539018,
0.0000020429579308256507
]
|
{
"id": 0,
"code_window": [
"\n",
".main-color {\n",
" overflow: hidden;\n",
"}\n",
"\n",
".main-color {\n",
" &-item {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" display: flex;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 6
} | .color-palette {
margin: 45px 0;
}
.main-color {
overflow: hidden;
}
.main-color {
&-item {
width: 80px;
height: 60px;
border-radius: 4px;
float: left;
margin: 0 5px 5px 0;
transition: all .2s;
position: relative;
text-align: center;
padding-top: 20px;
font-family: Consolas;
font-size: 12px;
}
&-item &-value {
font-size: 12px;
position: absolute;
bottom: -4px;
transform: scale(0.85);
left: 0;
width: 100%;
text-align: center;
opacity: 0;
transition: all .2s ease .1s;
}
}
.color-title {
margin: 0 0 16px 0;
font-weight: 500;
color: #5C6B77;
font-size: 22px;
text-transform: capitalize;
}
.color-description {
font-size: 16px;
margin-left: 12px;
font-weight: normal;
color: #888;
}
.main-color:hover {
.main-color-item {
padding-top: 4px;
}
.main-color-value {
opacity: 0.7;
bottom: 3px;
}
}
.color-block {
position: relative;
width: 60px;
border-radius: @border-radius-base;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
cursor: pointer;
}
.color-block:after {
position: absolute;
top: 10px;
left: 0;
height: 100%;
width: 100%;
content: "Copied!";
font-size: 12px;
line-height: 28px;
text-align: center;
color: #444;
transition: all 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
opacity: 0;
}
.color-block.copied:after {
opacity: 1;
top: 0;
}
.color-block.dark:after {
color: #fff;
}
.make-palatte(@color, @index: 1) when (@index <= 10) {
.palatte-@{color}-@{index} {
@background: "@{color}-@{index}";
background: @@background;
}
.make-palatte(@color, (@index + 1)); // next iteration
}
.main-color {
.make-palatte(blue);
.make-palatte(purple);
.make-palatte(cyan);
.make-palatte(green);
.make-palatte(pink);
.make-palatte(red);
.make-palatte(orange);
.make-palatte(yellow);
}
| site/theme/static/colors.less | 1 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.9809941053390503,
0.08246028423309326,
0.00016687490278854966,
0.00017307839880231768,
0.27092134952545166
]
|
{
"id": 0,
"code_window": [
"\n",
".main-color {\n",
" overflow: hidden;\n",
"}\n",
"\n",
".main-color {\n",
" &-item {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" display: flex;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 6
} | import React from 'react';
import Tooltip from '../tooltip';
import { AbstractTooltipProps } from '../tooltip';
import Icon from '../icon';
import Button from '../button';
export interface PopconfirmProps extends AbstractTooltipProps {
title: React.ReactNode;
onConfirm?: () => void;
onCancel?: () => void;
okText?: React.ReactNode;
cancelText?: React.ReactNode;
}
export interface PopconfirmContext {
antLocale?: {
Popconfirm?: any,
};
}
export default class Popconfirm extends React.Component<PopconfirmProps, any> {
static defaultProps = {
prefixCls: 'ant-popover',
transitionName: 'zoom-big',
placement: 'top',
trigger: 'click',
};
static contextTypes = {
antLocale: React.PropTypes.object,
};
context: PopconfirmContext;
constructor(props: PopconfirmProps) {
super(props);
this.state = {
visible: props.visible,
};
}
componentWillReceiveProps(nextProps: PopconfirmProps) {
if ('visible' in nextProps) {
this.setState({ visible: nextProps.visible });
}
}
confirm = () => {
this.setVisible(false);
const onConfirm = this.props.onConfirm;
if (onConfirm) {
onConfirm.call(this);
}
}
cancel = () => {
this.setVisible(false);
const onCancel = this.props.onCancel;
if (onCancel) {
onCancel.call(this);
}
}
onVisibleChange = (visible) => {
this.setVisible(visible);
}
setVisible(visible) {
const props = this.props;
if (!('visible' in props)) {
this.setState({ visible });
}
const onVisibleChange = props.onVisibleChange;
if (onVisibleChange) {
onVisibleChange(visible);
}
}
render() {
const { props, context } = this;
const { prefixCls, title, placement, ...restProps } = props;
let { okText, cancelText } = props;
const popconfirmLocale = context.antLocale && context.antLocale.Popconfirm;
if (popconfirmLocale) {
okText = okText || popconfirmLocale.okText;
cancelText = cancelText || popconfirmLocale.cancelText;
}
const overlay = (
<div>
<div className={`${prefixCls}-inner-content`}>
<div className={`${prefixCls}-message`}>
<Icon type="exclamation-circle" />
<div className={`${prefixCls}-message-title`}>{title}</div>
</div>
<div className={`${prefixCls}-buttons`}>
<Button onClick={this.cancel} type="ghost" size="small">{cancelText || '取消'}</Button>
<Button onClick={this.confirm} type="primary" size="small">{okText || '确定'}</Button>
</div>
</div>
</div>
);
return (
<Tooltip
{...restProps}
prefixCls={prefixCls}
placement={placement}
onVisibleChange={this.onVisibleChange}
visible={this.state.visible}
overlay={overlay}
/>
);
}
}
| components/popconfirm/index.tsx | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.004508769605308771,
0.0006884757895022631,
0.00016686633171048015,
0.00017390343418810517,
0.001268959604203701
]
|
{
"id": 0,
"code_window": [
"\n",
".main-color {\n",
" overflow: hidden;\n",
"}\n",
"\n",
".main-color {\n",
" &-item {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" display: flex;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 6
} | import demoTest from '../../../tests/shared/demoTest';
demoTest('grid');
| components/grid/__tests__/demo.test.js | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017845071852207184,
0.00017845071852207184,
0.00017845071852207184,
0.00017845071852207184,
0
]
|
{
"id": 0,
"code_window": [
"\n",
".main-color {\n",
" overflow: hidden;\n",
"}\n",
"\n",
".main-color {\n",
" &-item {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" display: flex;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 6
} | ---
order: 2
title:
zh-CN: 不可用
en-US: Disabled
---
## zh-CN
点击按钮切换可用状态。
## en-US
Click the button to toggle between available and disabled states.
````__react
import { InputNumber, Button } from 'antd';
const Test = React.createClass({
getInitialState() {
return {
disabled: true,
};
},
toggle() {
this.setState({
disabled: !this.state.disabled,
});
},
render() {
return (
<div>
<InputNumber min={1} max={10} disabled={this.state.disabled} defaultValue={3} />
<div style={{ marginTop: 20 }}>
<Button onClick={this.toggle} type="primary">Toggle disabled</Button>
</div>
</div>
);
},
});
ReactDOM.render(<Test />, mountNode);
````
| components/input-number/demo/disabled.md | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017683245823718607,
0.00017216245760209858,
0.00016796299314592034,
0.00017180417489726096,
0.0000029073291898384923
]
|
{
"id": 1,
"code_window": [
" &-item {\n",
" width: 80px;\n",
" height: 60px;\n",
" border-radius: 4px;\n",
" float: left;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" flex: 1;\n",
" height: 80px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 10
} | .color-palette {
margin: 45px 0;
}
.main-color {
overflow: hidden;
}
.main-color {
&-item {
width: 80px;
height: 60px;
border-radius: 4px;
float: left;
margin: 0 5px 5px 0;
transition: all .2s;
position: relative;
text-align: center;
padding-top: 20px;
font-family: Consolas;
font-size: 12px;
}
&-item &-value {
font-size: 12px;
position: absolute;
bottom: -4px;
transform: scale(0.85);
left: 0;
width: 100%;
text-align: center;
opacity: 0;
transition: all .2s ease .1s;
}
}
.color-title {
margin: 0 0 16px 0;
font-weight: 500;
color: #5C6B77;
font-size: 22px;
text-transform: capitalize;
}
.color-description {
font-size: 16px;
margin-left: 12px;
font-weight: normal;
color: #888;
}
.main-color:hover {
.main-color-item {
padding-top: 4px;
}
.main-color-value {
opacity: 0.7;
bottom: 3px;
}
}
.color-block {
position: relative;
width: 60px;
border-radius: @border-radius-base;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
cursor: pointer;
}
.color-block:after {
position: absolute;
top: 10px;
left: 0;
height: 100%;
width: 100%;
content: "Copied!";
font-size: 12px;
line-height: 28px;
text-align: center;
color: #444;
transition: all 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
opacity: 0;
}
.color-block.copied:after {
opacity: 1;
top: 0;
}
.color-block.dark:after {
color: #fff;
}
.make-palatte(@color, @index: 1) when (@index <= 10) {
.palatte-@{color}-@{index} {
@background: "@{color}-@{index}";
background: @@background;
}
.make-palatte(@color, (@index + 1)); // next iteration
}
.main-color {
.make-palatte(blue);
.make-palatte(purple);
.make-palatte(cyan);
.make-palatte(green);
.make-palatte(pink);
.make-palatte(red);
.make-palatte(orange);
.make-palatte(yellow);
}
| site/theme/static/colors.less | 1 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.9933621883392334,
0.08310694247484207,
0.0001671960053499788,
0.00017735932487994432,
0.27445247769355774
]
|
{
"id": 1,
"code_window": [
" &-item {\n",
" width: 80px;\n",
" height: 60px;\n",
" border-radius: 4px;\n",
" float: left;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" flex: 1;\n",
" height: 80px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 10
} | import React from 'react';
import classNames from 'classnames';
import Radio from './radio';
import RadioButton from './radioButton';
import PureRenderMixin from 'rc-util/lib/PureRenderMixin';
import assign from 'object-assign';
function getCheckedValue(children) {
let value = null;
let matched = false;
React.Children.forEach(children, (radio: any) => {
if (radio && radio.props && radio.props.checked) {
value = radio.props.value;
matched = true;
}
});
return matched ? { value } : undefined;
}
export interface RadioGroupProps {
prefixCls?: string;
className?: string;
/** 选项变化时的回调函数*/
onChange?: React.FormEventHandler<any>;
/** 用于设置当前选中的值*/
value?: string | number;
/** 默认选中的值*/
defaultValue?: string | number;
/** 大小,只对按钮样式生效*/
size?: 'large' | 'default' | 'small';
style?: React.CSSProperties;
disabled?: boolean;
onMouseEnter?: React.FormEventHandler<any>;
onMouseLeave?: React.FormEventHandler<any>;
}
export default class RadioGroup extends React.Component<RadioGroupProps, any> {
static defaultProps = {
disabled: false,
};
constructor(props) {
super(props);
let value;
if ('value' in props) {
value = props.value;
} else if ('defaultValue' in props) {
value = props.defaultValue;
} else {
const checkedValue = getCheckedValue(props.children);
value = checkedValue && checkedValue.value;
}
this.state = {
value,
};
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
this.setState({
value: nextProps.value,
});
} else {
const checkedValue = getCheckedValue(nextProps.children);
if (checkedValue) {
this.setState({
value: checkedValue.value,
});
}
}
}
shouldComponentUpdate(...args) {
return PureRenderMixin.shouldComponentUpdate.apply(this, args);
}
onRadioChange = (ev) => {
const lastValue = this.state.value;
const { value } = ev.target;
if (!('value' in this.props)) {
this.setState({
value,
});
}
const onChange = this.props.onChange;
if (onChange && value !== lastValue) {
onChange(ev);
}
}
render() {
const props = this.props;
const children = !props.children ? [] : React.Children.map(props.children, (radio: any) => {
if (radio && (radio.type === Radio || radio.type === RadioButton) && radio.props) {
return React.cloneElement(radio, assign({}, radio.props, {
onChange: this.onRadioChange,
checked: this.state.value === radio.props.value,
disabled: radio.props.disabled || this.props.disabled,
}));
}
return radio;
});
const { prefixCls = 'ant-radio-group', className = '' } = props;
const classString = classNames(prefixCls, {
[`${prefixCls}-${props.size}`]: props.size,
}, className);
return (
<div
className={classString}
style={props.style}
onMouseEnter={props.onMouseEnter}
onMouseLeave={props.onMouseLeave}
>
{children}
</div>
);
}
}
| components/radio/group.tsx | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017712033877614886,
0.00016890613187570125,
0.00016615168715361506,
0.0001679013657849282,
0.000002970208242913941
]
|
{
"id": 1,
"code_window": [
" &-item {\n",
" width: 80px;\n",
" height: 60px;\n",
" border-radius: 4px;\n",
" float: left;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" flex: 1;\n",
" height: 80px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 10
} | ---
order: 0
title: Cases
---
Ant Design is a design language for enterprise-like complex UIs.
Starting in April 2015, more and more products of Ant Financial follow Ant Design specification, covering multiple business lines and more than 40 systems.
Designed for enterprise-like complex UIs, used by both professional and non-professional designers,
Ant Design has a low learning curve that helps you getting started fast and achieve rapid results.
With a strong focus on proof-based design and user experience,
Ant Design provides a complete front-end development solution that can greatly enhance the design and development efficiency.
Currently, there are many products and sites using Ant Design.
References to some of these implementations can be found [here](https://github.com/ant-design/ant-design/issues/477).
If your solutions are using Ant Design, please leave us a message.
## Best Practices
---
### Financial Cloud
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/kBgLUfEwxlBdwUr.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/SeXqPPyixccDJBY.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/IRjHVNFWRlCMdnb.png">
Cloud-oriented financial services, used by financial institutions that benefit from customized business cloud computing services.
It assists financial institutions to upgrade to a new financial restructuring, promotion of capacity platforms, data and technology.
<p><a class="outside-link" href="https://www.cloud.alipay.com/" target="_blank">Website</a></p>
---
### OceanBase Cloud Platform
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/JUAXPZYtVyUQfGu.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/lpzTKvgLpJgKGpq.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/GVJGaWbqfBFedWN.png">
OceanBase Cloud is a distributed relational database in a real sense, but OceanBase Cloud Platform is the OceanBase cloud-based database service that can help users quickly create and use OceanBase service.
<p><a class="outside-link internal" href="http://oceanbase.alipay.com/" target="_blank">Website</a></p>
---
### Service Experience Platform
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/PiSveQClPzmxPTy.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/vsoYArBwcPRZnVE.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/TMyfsUGQSjOdGIm.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/sBlmIcJXZdJTJbC.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/fRDuTjVbVApxyzU.png">
Experience Platform is used for collecting all the points of contact and information of the user (including microblogging and other channels).
Through data mining, it exposes the users's experience and it helps the company's internal business team / product managers, facilitating the experience problem solving, in order to achieve healthy functioning streams.
<p><a class="outside-link internal" href="http://tiyan.alipay.com/" target="_blank">Website</a></p>
---
### AntV
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/yWNVSFBhKsoShvi.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/nvJftlNzfzhVDVW.png">
<img class="preview-img" width="420" align="right" src="https://os.alipayobjects.com/rmsportal/LugOCvzybKsmQCj.png">
AntV is a graphical library that is based on the work of a data group team
whose results of exploring data visualization were summarized
and shared them together with the required data visualization theory.
<p><a class="outside-link internal" href="https://antv.alipay.com/" target="_blank">Website</a></p>
<style>
.preview-image-boxes {
margin-top: -36px;
}
.preview-image-wrapper {
padding: 0;
background: #fff;
}
.toc {
display: none;
}
</style>
| docs/practice/cases.en-US.md | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00016949379642028362,
0.00016674393555149436,
0.00016446749214082956,
0.00016644710558466613,
0.0000016929722050917917
]
|
{
"id": 1,
"code_window": [
" &-item {\n",
" width: 80px;\n",
" height: 60px;\n",
" border-radius: 4px;\n",
" float: left;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" flex: 1;\n",
" height: 80px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 10
} | .move-motion(@className, @keyframeName) {
.make-motion(@className, @keyframeName);
.@{className}-enter,
.@{className}-appear {
opacity: 0;
animation-timing-function: @ease-out-circ;
}
.@{className}-leave {
animation-timing-function: @ease-in-circ;
}
}
.move-motion(move-up, antMoveUp);
.move-motion(move-down, antMoveDown);
.move-motion(move-left, antMoveLeft);
.move-motion(move-right, antMoveRight);
@keyframes antMoveDownIn {
0% {
transform-origin: 0 0;
transform: translateY(100%);
opacity: 0;
}
100% {
transform-origin: 0 0;
transform: translateY(0%);
opacity: 1;
}
}
@keyframes antMoveDownOut {
0% {
transform-origin: 0 0;
transform: translateY(0%);
opacity: 1;
}
100% {
transform-origin: 0 0;
transform: translateY(100%);
opacity: 0;
}
}
@keyframes antMoveLeftIn {
0% {
transform-origin: 0 0;
transform: translateX(-100%);
opacity: 0;
}
100% {
transform-origin: 0 0;
transform: translateX(0%);
opacity: 1;
}
}
@keyframes antMoveLeftOut {
0% {
transform-origin: 0 0;
transform: translateX(0%);
opacity: 1;
}
100% {
transform-origin: 0 0;
transform: translateX(-100%);
opacity: 0;
}
}
@keyframes antMoveRightIn {
0% {
opacity: 0;
transform-origin: 0 0;
transform: translateX(100%);
}
100% {
opacity: 1;
transform-origin: 0 0;
transform: translateX(0%);
}
}
@keyframes antMoveRightOut {
0% {
transform-origin: 0 0;
transform: translateX(0%);
opacity: 1;
}
100% {
transform-origin: 0 0;
transform: translateX(100%);
opacity: 0;
}
}
@keyframes antMoveUpIn {
0% {
transform-origin: 0 0;
transform: translateY(-100%);
opacity: 0;
}
100% {
transform-origin: 0 0;
transform: translateY(0%);
opacity: 1;
}
}
@keyframes antMoveUpOut {
0% {
transform-origin: 0 0;
transform: translateY(0%);
opacity: 1;
}
100% {
transform-origin: 0 0;
transform: translateY(-100%);
opacity: 0;
}
}
| components/style/core/motion/move.less | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017514584760647267,
0.0001705926115391776,
0.00016798557771835476,
0.00017077065422199667,
0.000002046859435722581
]
|
{
"id": 2,
"code_window": [
" border-radius: 4px;\n",
" float: left;\n",
" margin: 0 5px 5px 0;\n",
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-right: 4px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 14
} | .color-palette {
margin: 45px 0;
}
.main-color {
overflow: hidden;
}
.main-color {
&-item {
width: 80px;
height: 60px;
border-radius: 4px;
float: left;
margin: 0 5px 5px 0;
transition: all .2s;
position: relative;
text-align: center;
padding-top: 20px;
font-family: Consolas;
font-size: 12px;
}
&-item &-value {
font-size: 12px;
position: absolute;
bottom: -4px;
transform: scale(0.85);
left: 0;
width: 100%;
text-align: center;
opacity: 0;
transition: all .2s ease .1s;
}
}
.color-title {
margin: 0 0 16px 0;
font-weight: 500;
color: #5C6B77;
font-size: 22px;
text-transform: capitalize;
}
.color-description {
font-size: 16px;
margin-left: 12px;
font-weight: normal;
color: #888;
}
.main-color:hover {
.main-color-item {
padding-top: 4px;
}
.main-color-value {
opacity: 0.7;
bottom: 3px;
}
}
.color-block {
position: relative;
width: 60px;
border-radius: @border-radius-base;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
cursor: pointer;
}
.color-block:after {
position: absolute;
top: 10px;
left: 0;
height: 100%;
width: 100%;
content: "Copied!";
font-size: 12px;
line-height: 28px;
text-align: center;
color: #444;
transition: all 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
opacity: 0;
}
.color-block.copied:after {
opacity: 1;
top: 0;
}
.color-block.dark:after {
color: #fff;
}
.make-palatte(@color, @index: 1) when (@index <= 10) {
.palatte-@{color}-@{index} {
@background: "@{color}-@{index}";
background: @@background;
}
.make-palatte(@color, (@index + 1)); // next iteration
}
.main-color {
.make-palatte(blue);
.make-palatte(purple);
.make-palatte(cyan);
.make-palatte(green);
.make-palatte(pink);
.make-palatte(red);
.make-palatte(orange);
.make-palatte(yellow);
}
| site/theme/static/colors.less | 1 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.9977951049804688,
0.08542299270629883,
0.00016372145910281688,
0.0001830548862926662,
0.27513715624809265
]
|
{
"id": 2,
"code_window": [
" border-radius: 4px;\n",
" float: left;\n",
" margin: 0 5px 5px 0;\n",
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-right: 4px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 14
} | import demoTest from '../../../tests/shared/demoTest';
demoTest('steps');
| components/steps/__tests__/demo.test.js | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.000174552493263036,
0.000174552493263036,
0.000174552493263036,
0.000174552493263036,
0
]
|
{
"id": 2,
"code_window": [
" border-radius: 4px;\n",
" float: left;\n",
" margin: 0 5px 5px 0;\n",
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-right: 4px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 14
} | import '../../style/index.less';
import './index.less';
| components/grid/style/index.tsx | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017627589113544673,
0.00017627589113544673,
0.00017627589113544673,
0.00017627589113544673,
0
]
|
{
"id": 2,
"code_window": [
" border-radius: 4px;\n",
" float: left;\n",
" margin: 0 5px 5px 0;\n",
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-right: 4px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 14
} | ---
category: Components
type: Layout
cols: 1
title: Grid
---
24 Grids System。
## Design concept
<div class="grid-demo">
<div class="ant-row demo-row">
<div class="ant-col-24 demo-col demo-col-1">
100%
</div>
</div>
<div class="ant-row demo-row">
<div class="ant-col-6 demo-col demo-col-2">
25%
</div>
<div class="ant-col-6 demo-col demo-col-3">
25%
</div>
<div class="ant-col-6 demo-col demo-col-2">
25%
</div>
<div class="ant-col-6 demo-col demo-col-3">
25%
</div>
</div>
<div class="ant-row demo-row">
<div class="ant-col-8 demo-col demo-col-4">
33.33%
</div>
<div class="ant-col-8 demo-col demo-col-5">
33.33%
</div>
<div class="ant-col-8 demo-col demo-col-4">
33.33%
</div>
</div>
<div class="ant-row demo-row">
<div class="ant-col-12 demo-col demo-col-1">
50%
</div>
<div class="ant-col-12 demo-col demo-col-3">
50%
</div>
</div>
<div class="ant-row demo-row">
<div class="ant-col-16 demo-col demo-col-4">
66.66%
</div>
<div class="ant-col-8 demo-col demo-col-5">
33.33%
</div>
</div>
</div>
In most business situations,Ant Design need solve a lot of information storage problems within the design area,so based on 12 Grids System,we divided the design area into 24 aliquots.
We name the divided area as 'box'.We suggest that four boxes horizontal arrangement at most, one at least.Box on the proportion of the entire screen as above picture.To ensure that the level of visual comfort,we custom typography inside of the box based on the box unit.
## Outline
In the grid system, we define the frame outside the information area based on row and column, to ensure that every area can steady arrangement.
Following is a brief look at how it works:
* To establish a set of `column` in the horizontal direction by` row` (abbreviated col)
* Direct your content elements should be placed in the `col`, and only` col` as the `row`
* The column grid system is a value of 1-24 to represent its range spans.For example, three columns of equal width can be created by `.col-8`.
* If a `row` sum of` col` more than 24, then the extra `col` as a whole will start a new line arrangement.
## Flex layout
Our grid systems support Flex layout to allow the child elements within the parent horizontal alignment - Left, center, right of abode, and other wide arrangement, decentralized arrangement. Between sub-elements and sub-elements, support the top of the aligned vertically centered, bottom-aligned manner. At the same time, you can define the order of elements by using 'order'.
Flex layout is based on a grid 24 to define each "box" in width, but not rigidly adhere to the grid layout.
## API
Ant Design layout component if it can not meet your needs, you can use the excellent layout of the components of the community:
- [react-flexbox-grid](http://roylee0704.github.io/react-flexbox-grid/)
- [react-blocks](http://whoisandie.github.io/react-blocks/)
### Row
| Member | Explanation | Type | Default |
|------------|-----------------|--------------------|-------------|
| gutter | grid spacing | number | 0 |
| type | layout mode, the optional `flex`, effective modern browser | string | |
| align | the vertical alignment of the layout of flex: `top` ` middle` `bottom` | string | `top` |
| justify | horizontal arrangement of the layout of flex: `start` ` end` `center` ` space-around` `space-between` | string | `start` |
### Col
| Member | Explanation | Type | Default |
|------------|-----------------|--------------------|-------------|
| span | raster occupying the number of cells,0 corresponds to `display: none` | number | none |
| order | raster order, under `flex` effective layout mode | number | 0 |
| offset | the number of cells to the left of the grid spacing, no cell in grid spacing | number | 0 |
| push | the number of cells that raster move to the right | number | 0 |
| pull | the number of cells that raster move to the left | number | 0 |
| components/grid/index.en-US.md | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00020351854618638754,
0.0001717673585517332,
0.0001639958209125325,
0.00016808972577564418,
0.000010267696779919788
]
|
{
"id": 3,
"code_window": [
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n",
" padding-top: 20px;\n",
" font-family: Consolas;\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" padding-top: 28px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 18
} | .color-palette {
margin: 45px 0;
}
.main-color {
overflow: hidden;
}
.main-color {
&-item {
width: 80px;
height: 60px;
border-radius: 4px;
float: left;
margin: 0 5px 5px 0;
transition: all .2s;
position: relative;
text-align: center;
padding-top: 20px;
font-family: Consolas;
font-size: 12px;
}
&-item &-value {
font-size: 12px;
position: absolute;
bottom: -4px;
transform: scale(0.85);
left: 0;
width: 100%;
text-align: center;
opacity: 0;
transition: all .2s ease .1s;
}
}
.color-title {
margin: 0 0 16px 0;
font-weight: 500;
color: #5C6B77;
font-size: 22px;
text-transform: capitalize;
}
.color-description {
font-size: 16px;
margin-left: 12px;
font-weight: normal;
color: #888;
}
.main-color:hover {
.main-color-item {
padding-top: 4px;
}
.main-color-value {
opacity: 0.7;
bottom: 3px;
}
}
.color-block {
position: relative;
width: 60px;
border-radius: @border-radius-base;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
cursor: pointer;
}
.color-block:after {
position: absolute;
top: 10px;
left: 0;
height: 100%;
width: 100%;
content: "Copied!";
font-size: 12px;
line-height: 28px;
text-align: center;
color: #444;
transition: all 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
opacity: 0;
}
.color-block.copied:after {
opacity: 1;
top: 0;
}
.color-block.dark:after {
color: #fff;
}
.make-palatte(@color, @index: 1) when (@index <= 10) {
.palatte-@{color}-@{index} {
@background: "@{color}-@{index}";
background: @@background;
}
.make-palatte(@color, (@index + 1)); // next iteration
}
.main-color {
.make-palatte(blue);
.make-palatte(purple);
.make-palatte(cyan);
.make-palatte(green);
.make-palatte(pink);
.make-palatte(red);
.make-palatte(orange);
.make-palatte(yellow);
}
| site/theme/static/colors.less | 1 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.9979398846626282,
0.0838845744729042,
0.000167479069205001,
0.000199544447241351,
0.2755998969078064
]
|
{
"id": 3,
"code_window": [
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n",
" padding-top: 20px;\n",
" font-family: Consolas;\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" padding-top: 28px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 18
} | ---
order: 6
title: i18n 方案
link: //github.com/ant-design/intl-example
---
| docs/react/i18n-solution.zh-CN.md | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017527064483147115,
0.00017527064483147115,
0.00017527064483147115,
0.00017527064483147115,
0
]
|
{
"id": 3,
"code_window": [
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n",
" padding-top: 20px;\n",
" font-family: Consolas;\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" padding-top: 28px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 18
} | import demoTest from '../../../tests/shared/demoTest';
demoTest('pagination');
| components/pagination/__tests__/demo.test.js | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017485517309978604,
0.00017485517309978604,
0.00017485517309978604,
0.00017485517309978604,
0
]
|
{
"id": 3,
"code_window": [
" transition: all .2s;\n",
" position: relative;\n",
" text-align: center;\n",
" padding-top: 20px;\n",
" font-family: Consolas;\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" padding-top: 28px;\n"
],
"file_path": "site/theme/static/colors.less",
"type": "replace",
"edit_start_line_idx": 18
} | ---
category: Principles
order: 8
title: Provide an Invitation
---
A common problem with many of these rich interactions (e.g. Drag and Drop, Inline Editing, and Contextual Tools) is their lack of discoverability. Providing an invitation to the user is one of the keys to successful interactive interfaces.
Invitations are the prompts and cues that lead users through an interaction. They often include just-in-time tips or visual affordances that hint at what will happen next in the interface.
> ** Signifiers ** are signals, communication devices. These signs tell you about the possible actions; what to do, and where to do it. Signifiers are often visible, audible or tangible, from the Design of Everyday Things.
> ** Affordances ** are the relationships (read: possible actions) between an object and an entity (most often a person). The presence of an affordance is determined by the properties of the object and of the abilities of the entity who's interacting with the object, from the Design of Everyday Things.
---
## Static Invitations
By providing cues for interaction directly on the page we can statically indicate to the user the expected interface behavior. Static Invitations provide cues directly on the page.
<br>
<img class="preview-img" align="right" alt="example of Text Invitation" src="https://os.alipayobjects.com/rmsportal/pWnlJpbkCPIaKdP.png">
<img class="preview-img" align="right" alt="example of Blank Slate Invitation" src="https://os.alipayobjects.com/rmsportal/DkOYgfJHDuzhyBg.png">
<img class="preview-img" align="right" alt="example of Unfinished Invitation" src="https://os.alipayobjects.com/rmsportal/cojQlWfINmsVDGd.png">
Call to Action Invitations are generally provided as static instructions on the page. But visually they can be provided in many different ways such as Text Invitation, Blank Slate Invitation and Unfinished Invitation.
<br>
<img class="preview-img" align="right" alt="example 1 of Tour Invitation" description="A few of tour points are provided when the user first logs in. Clicking the “Got It” button leads the user to the next tour step." src="https://os.alipayobjects.com/rmsportal/TGnzYViseCoFBYL.png">
<img class="preview-img" align="right" alt="example 2 of Tour Invitation" src="https://os.alipayobjects.com/rmsportal/KQabdaTbolVuMld.png">
Tour invitation can be a nice way to explain design changes to a web application, especially for a well-designed interface. But providing tours will not solve the real problems an interface may have during interaction.
>Note that make Tour Invitations short and simple, easy to exit, and clear to restart.
<br>
---
## Dynamic Invitations
Dynamic Invitations engage users at the point of the interaction and guide them through the next step of interaction.
<br>
<img class="preview-img" align="right" alt="example 1 of Hover Invitation" description="During mouse hover on the whole card, the clickable parts turn to blue hypertext." src="https://os.alipayobjects.com/rmsportal/gzfDJLcETyTOfFg.png">
<img class="preview-img" align="right" alt="example 2 of Hover Invitation" description="During mouse hover, the button of "Select this Template" appears." src="https://os.alipayobjects.com/rmsportal/tdJWZFIDWYuMVIe.png">
Hover Invitation: Provide an invitation during mouse hover.
<br>
<img class="preview-img" align="right" alt="example of Inference Invitation" description="The system predicts that the user's interest in an article extends to a type of articles, and it provides an invitation after the user click "like"." src="https://os.alipayobjects.com/rmsportal/SyurwytfcvpbNLG.png">
Inference Invitation: Use visual inferences during interaction to cue users as to what the system has inferred about their intent.
<br>
<img class="preview-img" align="right" alt="example of More Content Invitation" description="Use the left or right arrows to switch more content around Modal." src="https://os.alipayobjects.com/rmsportal/sOqYOydwQjLHqph.png">
More Content Invitation: Indicate that there is more content on the page.
<br>
<br>
<p><span class="waiting">Affordance Invitation (coming soon)</span></p>
<br>
<p><span class="waiting">Drag and Drop Invitation (coming soon)</span></p>
| docs/spec/invitation.en-US.md | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017448226572014391,
0.00017089192988350987,
0.0001667231845203787,
0.00017050431051757187,
0.0000022306974187813466
]
|
{
"id": 4,
"code_window": [
" font-family: Consolas;\n",
" font-size: 12px;\n",
" }\n",
" &-item &-value {\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" &:last-child {\n",
" margin-right: 0;\n",
" }\n"
],
"file_path": "site/theme/static/colors.less",
"type": "add",
"edit_start_line_idx": 21
} | .color-palette {
margin: 45px 0;
}
.main-color {
overflow: hidden;
}
.main-color {
&-item {
width: 80px;
height: 60px;
border-radius: 4px;
float: left;
margin: 0 5px 5px 0;
transition: all .2s;
position: relative;
text-align: center;
padding-top: 20px;
font-family: Consolas;
font-size: 12px;
}
&-item &-value {
font-size: 12px;
position: absolute;
bottom: -4px;
transform: scale(0.85);
left: 0;
width: 100%;
text-align: center;
opacity: 0;
transition: all .2s ease .1s;
}
}
.color-title {
margin: 0 0 16px 0;
font-weight: 500;
color: #5C6B77;
font-size: 22px;
text-transform: capitalize;
}
.color-description {
font-size: 16px;
margin-left: 12px;
font-weight: normal;
color: #888;
}
.main-color:hover {
.main-color-item {
padding-top: 4px;
}
.main-color-value {
opacity: 0.7;
bottom: 3px;
}
}
.color-block {
position: relative;
width: 60px;
border-radius: @border-radius-base;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
cursor: pointer;
}
.color-block:after {
position: absolute;
top: 10px;
left: 0;
height: 100%;
width: 100%;
content: "Copied!";
font-size: 12px;
line-height: 28px;
text-align: center;
color: #444;
transition: all 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
opacity: 0;
}
.color-block.copied:after {
opacity: 1;
top: 0;
}
.color-block.dark:after {
color: #fff;
}
.make-palatte(@color, @index: 1) when (@index <= 10) {
.palatte-@{color}-@{index} {
@background: "@{color}-@{index}";
background: @@background;
}
.make-palatte(@color, (@index + 1)); // next iteration
}
.main-color {
.make-palatte(blue);
.make-palatte(purple);
.make-palatte(cyan);
.make-palatte(green);
.make-palatte(pink);
.make-palatte(red);
.make-palatte(orange);
.make-palatte(yellow);
}
| site/theme/static/colors.less | 1 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.008045248687267303,
0.0013038419419899583,
0.00016785220941528678,
0.00017689750529825687,
0.0025613366160541773
]
|
{
"id": 4,
"code_window": [
" font-family: Consolas;\n",
" font-size: 12px;\n",
" }\n",
" &-item &-value {\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" &:last-child {\n",
" margin-right: 0;\n",
" }\n"
],
"file_path": "site/theme/static/colors.less",
"type": "add",
"edit_start_line_idx": 21
} | html {
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html,
body {
height: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", SimSun, sans-serif;
line-height: 1.5;
color: @text-color;
font-size: 14px;
background: #FFF;
transition: background 1s cubic-bezier(0.075, 0.82, 0.165, 1);
overflow-x: hidden;
}
a {
transition: color .3s ease;
}
.main-wrapper {
background: #fff;
margin: 0 48px;
border-radius: @border-radius-base;
padding: 24px 0 0;
margin-bottom: 24px;
position: relative;
}
div.main-container {
padding: 0 130px 120px 40px;
margin-left: -1px;
background: #fff;
min-height: 500px;
overflow: hidden;
border-left: 1px solid #e9e9e9;
position: relative;
}
.aside-container {
padding-bottom: 50px;
font-family: Lato, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", SimSun, sans-serif;
&.ant-menu-inline .ant-menu-submenu-title h4,
&.ant-menu-inline > .ant-menu-item,
&.ant-menu-inline .ant-menu-item a {
font-size: 14px;
text-overflow: ellipsis;
overflow: hidden;
}
a[disabled] {
color: #ccc;
}
}
.aside-container .chinese {
font-size: 12px;
margin-left: 6px;
font-weight: normal;
opacity: .67;
}
.outside-link {
display: inline-block;
}
.outside-link:after {
content: '\e691';
font-family: 'anticon';
margin-left: 5px;
font-size: 12px;
color: #aaa;
}
.outside-link.internal {
display: none;
}
.page-wrapper {
background: #ECECEC;
}
| site/theme/static/common.less | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.0001782464823918417,
0.00017144763842225075,
0.00016652220801915973,
0.00017120905977208167,
0.0000036394785638549365
]
|
{
"id": 4,
"code_window": [
" font-family: Consolas;\n",
" font-size: 12px;\n",
" }\n",
" &-item &-value {\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" &:last-child {\n",
" margin-right: 0;\n",
" }\n"
],
"file_path": "site/theme/static/colors.less",
"type": "add",
"edit_start_line_idx": 21
} | ---
order: 3
title:
zh-CN: 更灵活的内容展示
en-US: Customized content
---
## zh-CN
可以调整默认边距,设定宽度。
## en-US
Customizing default width and margin.
````__react
import { Card } from 'antd';
ReactDOM.render(
<Card style={{ width: 240 }} bodyStyle={{ padding: 0 }}>
<div className="custom-image">
<img alt="example" width="100%" src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png" />
</div>
<div className="custom-card">
<h3>Europe Street beat</h3>
<p>www.instagram.com</p>
</div>
</Card>
, mountNode);
````
````css
.custom-image img {
display: block;
}
.custom-card {
padding: 10px 16px;
}
.custom-card p {
color: #999;
}
````
| components/card/demo/no-padding.md | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017518708773422986,
0.00017123061115853488,
0.00016659875109326094,
0.00017165153985843062,
0.0000031408183076564455
]
|
{
"id": 4,
"code_window": [
" font-family: Consolas;\n",
" font-size: 12px;\n",
" }\n",
" &-item &-value {\n",
" font-size: 12px;\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" &:last-child {\n",
" margin-right: 0;\n",
" }\n"
],
"file_path": "site/theme/static/colors.less",
"type": "add",
"edit_start_line_idx": 21
} | import React from 'react';
import classNames from 'classnames';
import omit from 'omit.js';
import Icon from '../icon';
export interface SiderProps {
style?: React.CSSProperties;
prefixCls?: string;
className?: string;
collapsible?: boolean;
collapsed?: boolean;
defaultCollapsed?: boolean;
onCollapse?: (collapsed: boolean) => void;
trigger?: React.ReactNode;
width?: number | string;
collapsedWidth?: number;
}
export default class Sider extends React.Component<SiderProps, any> {
static defaultProps = {
prefixCls: 'ant-layout-sider',
collapsible: false,
defaultCollapsed: false,
width: 200,
collapsedWidth: 64,
style: {},
name: 'Sider',
};
constructor(props) {
super(props);
let collapsed;
if ('collapsed' in props) {
collapsed = props.collapsed;
} else {
collapsed = props.defaultCollapsed;
}
this.state = {
collapsed,
};
}
componentWillReceiveProps(nextProps) {
if ('collapsed' in nextProps) {
this.setState({
collapsed: nextProps.collapsed,
});
}
}
setCollapsed = (collapsed) => {
if (!('collapsed' in this.props)) {
this.setState({
collapsed,
});
}
const { onCollapse } = this.props;
if (onCollapse) {
onCollapse(collapsed);
}
}
toggle = () => {
const collapsed = !this.state.collapsed;
this.setCollapsed(collapsed);
}
render() {
const {
prefixCls, className, collapsible, trigger, style, width, collapsedWidth,
...others,
} = this.props;
const divProps = omit(others, ['collapsed', 'defaultCollapsed', 'onCollapse', 'name']);
const siderCls = classNames(className, prefixCls, {
[`${prefixCls}-collapsed`]: !!this.state.collapsed,
[`${prefixCls}-has-trigger`]: !!trigger,
});
const divStyle = {
...style,
flex: `0 0 ${this.state.collapsed ? collapsedWidth : width}px`,
};
const iconObj = {
'expanded': <Icon type="left" />,
'collapsed': <Icon type="right" />,
};
const status = this.state.collapsed ? 'collapsed' : 'expanded';
const defaultTrigger = iconObj[status];
const triggerDom = (
trigger !== null ?
(<div className={`${prefixCls}-trigger`} onClick={this.toggle}>
{trigger || defaultTrigger}
</div>)
: null
);
return (
<div className={siderCls} {...divProps} style={divStyle}>
{this.props.children}
{collapsible && triggerDom}
</div>
);
}
}
| components/layout/Sider.tsx | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017701988690532744,
0.00017158650734927505,
0.00016744570166338235,
0.00017159608250949532,
0.000002575434564278112
]
|
{
"id": 5,
"code_window": [
" list-style: none;\n",
"}\n",
"\n",
".toc > ul {\n",
" padding: 8px 0;\n",
" list-style: none;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markdown .toc {\n",
" background: #fbfbfb;\n",
" border-left: 2px solid #eee;\n",
"}\n",
"\n"
],
"file_path": "site/theme/static/toc.less",
"type": "add",
"edit_start_line_idx": 7
} | .color-palette {
margin: 45px 0;
}
.main-color {
overflow: hidden;
}
.main-color {
&-item {
width: 80px;
height: 60px;
border-radius: 4px;
float: left;
margin: 0 5px 5px 0;
transition: all .2s;
position: relative;
text-align: center;
padding-top: 20px;
font-family: Consolas;
font-size: 12px;
}
&-item &-value {
font-size: 12px;
position: absolute;
bottom: -4px;
transform: scale(0.85);
left: 0;
width: 100%;
text-align: center;
opacity: 0;
transition: all .2s ease .1s;
}
}
.color-title {
margin: 0 0 16px 0;
font-weight: 500;
color: #5C6B77;
font-size: 22px;
text-transform: capitalize;
}
.color-description {
font-size: 16px;
margin-left: 12px;
font-weight: normal;
color: #888;
}
.main-color:hover {
.main-color-item {
padding-top: 4px;
}
.main-color-value {
opacity: 0.7;
bottom: 3px;
}
}
.color-block {
position: relative;
width: 60px;
border-radius: @border-radius-base;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
cursor: pointer;
}
.color-block:after {
position: absolute;
top: 10px;
left: 0;
height: 100%;
width: 100%;
content: "Copied!";
font-size: 12px;
line-height: 28px;
text-align: center;
color: #444;
transition: all 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
opacity: 0;
}
.color-block.copied:after {
opacity: 1;
top: 0;
}
.color-block.dark:after {
color: #fff;
}
.make-palatte(@color, @index: 1) when (@index <= 10) {
.palatte-@{color}-@{index} {
@background: "@{color}-@{index}";
background: @@background;
}
.make-palatte(@color, (@index + 1)); // next iteration
}
.main-color {
.make-palatte(blue);
.make-palatte(purple);
.make-palatte(cyan);
.make-palatte(green);
.make-palatte(pink);
.make-palatte(red);
.make-palatte(orange);
.make-palatte(yellow);
}
| site/theme/static/colors.less | 1 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00018178604659624398,
0.00017142615979537368,
0.00016703124856576324,
0.00016991914890240878,
0.000004062883817823604
]
|
{
"id": 5,
"code_window": [
" list-style: none;\n",
"}\n",
"\n",
".toc > ul {\n",
" padding: 8px 0;\n",
" list-style: none;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markdown .toc {\n",
" background: #fbfbfb;\n",
" border-left: 2px solid #eee;\n",
"}\n",
"\n"
],
"file_path": "site/theme/static/toc.less",
"type": "add",
"edit_start_line_idx": 7
} | @import "../../style/themes/default";
@import "../../style/mixins/index";
@layout-prefix-cls: ~"@{ant-prefix}-layout";
.@{layout-prefix-cls} {
display: flex;
flex-direction: column;
flex: auto;
overflow: auto;
background: @layout-body-background;
&&-has-sider {
flex-direction: row;
}
&-header,
&-footer {
flex: 0 0 auto;
}
&-header {
background: @layout-header-background;
padding: @layout-header-padding;
height: @layout-header-height;
line-height: @layout-header-height;
}
&-footer {
padding: @layout-footer-padding;
color: @text-color;
font-size: @font-size-base;
}
&-content {
flex: auto;
}
&-sider {
flex: 0 0 200px;
transition: all .3s ease;
position: relative;
background: @layout-sider-background;
&-has-trigger {
padding-bottom: @layout-trigger-height;
}
&-right {
order: 1;
}
&-collapsed {
flex: 0 0 64px;
}
&-trigger {
position: absolute;
text-align: center;
width: 100%;
bottom: 0;
cursor: pointer;
height: @layout-trigger-height;
line-height: @layout-trigger-height;
background: tint(@heading-color, 20%);
color: #fff;
}
}
}
| components/layout/style/index.less | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017184742318931967,
0.00016981185763143003,
0.0001674966188147664,
0.00016962781955953687,
0.0000013956804423287394
]
|
{
"id": 5,
"code_window": [
" list-style: none;\n",
"}\n",
"\n",
".toc > ul {\n",
" padding: 8px 0;\n",
" list-style: none;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markdown .toc {\n",
" background: #fbfbfb;\n",
" border-left: 2px solid #eee;\n",
"}\n",
"\n"
],
"file_path": "site/theme/static/toc.less",
"type": "add",
"edit_start_line_idx": 7
} | import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { Select, Modal } from 'antd';
import { version as antdVersion } from 'antd/package.json';
import * as utils from '../utils';
const Option = Select.Option;
function isLocalStorageNameSupported() {
const testKey = 'test';
const storage = window.localStorage;
try {
storage.setItem(testKey, '1');
storage.removeItem(testKey);
return true;
} catch (error) {
return false;
}
}
class Footer extends React.Component {
componentDidMount() {
// for some iOS
// http://stackoverflow.com/a/14555361
if (!isLocalStorageNameSupported()) {
return;
}
// 大版本发布后全局弹窗提示
// 1. 点击『知道了』之后不再提示
// 2. 超过截止日期后不再提示
if (
localStorage.getItem('[email protected]') !== 'true' &&
Date.now() < new Date('2016/10/14').getTime()
) {
this.infoNewVersion();
}
}
infoNewVersion() {
const messages = this.props.intl.messages;
Modal.info({
title: messages['app.publish.title'],
content: (
<div>
<img src="https://os.alipayobjects.com/rmsportal/nyqBompsynAQCpJ.svg" alt="Ant Design" />
<p>
{messages['app.publish.greeting']}
<a target="_blank" rel="noopener noreferrer" href="/changelog">[email protected]</a>
{messages['app.publish.intro']}
{messages['app.publish.old-version-guide']}
<a target="_blank" rel="noopener noreferrer" href="http://1x.ant.design">1x.ant.design</a>
{messages['app.publish.old-version-tips']}
</p>
</div>
),
okText: 'OK',
onOk: () => localStorage.setItem('[email protected]', 'true'),
className: 'new-version-info-modal',
width: 470,
});
}
handleVersionChange = (url) => {
const currentUrl = window.location.href;
const currentPathname = window.location.pathname;
window.location.href = currentUrl.replace(window.location.origin, url)
.replace(currentPathname, utils.getLocalizedPathname(currentPathname));
}
render() {
const { themeConfig } = this.props;
const docVersions = { ...themeConfig.docVersions, [antdVersion]: antdVersion };
const options = Object.keys(docVersions)
.map(version => <Option value={docVersions[version]} key={version}>{version}</Option>);
return (
<footer id="footer">
<ul>
<li>
<h2>GitHub</h2>
<div>
<a target="_blank " href="https://github.com/ant-design/ant-design">
<FormattedMessage id="app.footer.repo" />
</a>
</div>
<div>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/dvajs/dva">dva</a> - <FormattedMessage id="app.footer.dva" />
</div>
<div>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/dvajs/dva-cli">dva-cli</a> -
<FormattedMessage id="app.footer.scaffold" />
</div>
<div>
<a target="_blank" rel="noopener noreferrer" href="http://ant-tool.github.io">ant-tool</a> - <FormattedMessage id="app.footer.dev-tools" />
</div>
</li>
<li>
<h2><FormattedMessage id="app.footer.links" /></h2>
<div>
<a href="http://mobile.ant.design">Ant Design Mobile</a>
<span> - </span>
<FormattedMessage id="app.footer.mobile" />
</div>
<div>
<a href="https://g2.alipay.com/">G2</a>
<span> - </span>
<FormattedMessage id="app.footer.data-vis" />
</div>
<div>
<a href="https://antv.alipay.com/">AntV</a>
<span> - </span>
<FormattedMessage id="app.footer.data-vis-spec" />
</div>
<div>
<a href="http://motion.ant.design">Ant Motion</a>
<span> - </span>
<FormattedMessage id="app.footer.motion" />
</div>
<div>
<a href="http://library.ant.design/">AntD Library</a>
<span> - </span>
<FormattedMessage id="app.footer.antd-library" />
</div>
<div>
<a href="http://ux.ant.design">Ant UX</a>
<span> - </span>
<FormattedMessage id="app.footer.material" />
</div>
</li>
<li>
<h2><FormattedMessage id="app.footer.community" /></h2>
<div>
<a rel="noopener noreferrer" href="/changelog">
<FormattedMessage id="app.footer.change-log" />
</a>
</div>
<div>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/ant-design/ant-design/issues">
<FormattedMessage id="app.footer.feedback" />
</a>
</div>
<div>
<a target="_blank" rel="noopener noreferrer" href="https://gitter.im/ant-design/ant-design">
<FormattedMessage id="app.footer.discuss" />
</a>
</div>
<div>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/ant-design/ant-design/issues/new">
<FormattedMessage id="app.footer.bug-report" />
</a>
</div>
</li>
<li>
<div>©2016 <FormattedMessage id="app.footer.author" /></div>
<div>Powered by <a href="https://github.com/benjycui/bisheng">BiSheng</a></div>
<div style={{ marginTop: 10 }}>
<FormattedMessage id="app.footer.version" />
<Select
size="small"
dropdownMatchSelectWidth={false}
defaultValue={antdVersion}
onChange={this.handleVersionChange}
>
{options}
</Select>
</div>
</li>
</ul>
</footer>
);
}
}
export default injectIntl(Footer);
| site/theme/template/Layout/Footer.jsx | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00018090885714627802,
0.000169798600836657,
0.00016687238530721515,
0.00016909166879486293,
0.0000031067229429027066
]
|
{
"id": 5,
"code_window": [
" list-style: none;\n",
"}\n",
"\n",
".toc > ul {\n",
" padding: 8px 0;\n",
" list-style: none;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".markdown .toc {\n",
" background: #fbfbfb;\n",
" border-left: 2px solid #eee;\n",
"}\n",
"\n"
],
"file_path": "site/theme/static/toc.less",
"type": "add",
"edit_start_line_idx": 7
} | import { PropTypes } from 'react';
import React from 'react';
import Icon from '../icon';
import { Circle } from 'rc-progress';
import classNames from 'classnames';
const statusColorMap = {
normal: '#108ee9',
exception: '#ff5500',
success: '#87d068',
};
export interface ProgressProps {
prefixCls?: string;
className?: string;
type?: 'line' | 'circle';
percent?: number;
format?: (percent: number) => string;
status?: 'success' | 'active' | 'exception';
showInfo?: boolean;
strokeWidth?: number;
trailColor?: string;
width?: number;
style?: React.CSSProperties;
}
export default class Progress extends React.Component<ProgressProps, any> {
static Line: any;
static Circle: any;
static defaultProps = {
type: 'line',
percent: 0,
showInfo: true,
trailColor: '#f3f3f3',
prefixCls: 'ant-progress',
};
static propTypes = {
status: PropTypes.oneOf(['normal', 'exception', 'active', 'success']),
type: PropTypes.oneOf(['line', 'circle']),
showInfo: PropTypes.bool,
percent: PropTypes.number,
width: PropTypes.number,
strokeWidth: PropTypes.number,
trailColor: PropTypes.string,
format: PropTypes.func,
};
render() {
const props = this.props;
const {
prefixCls, className, percent = 0, status, format, trailColor,
type, strokeWidth, width, showInfo, ...restProps,
} = props;
const progressStatus = parseInt(percent.toString(), 10) >= 100 && !('status' in props) ?
'success' : (status || 'normal');
let progressInfo;
let progress;
const textFormatter = format || (percentNumber => `${percentNumber}%`);
if (showInfo) {
let text;
const iconType = type === 'circle' ? '' : '-circle';
if (progressStatus === 'exception') {
text = format ? textFormatter(percent) : <Icon type={`cross${iconType}`} />;
} else if (progressStatus === 'success') {
text = format ? textFormatter(percent) : <Icon type={`check${iconType}`} />;
} else {
text = textFormatter(percent);
}
progressInfo = <span className={`${prefixCls}-text`}>{text}</span>;
}
if (type === 'line') {
const percentStyle = {
width: `${percent}%`,
height: strokeWidth || 10,
};
progress = (
<div>
<div className={`${prefixCls}-outer`}>
<div className={`${prefixCls}-inner`}>
<div className={`${prefixCls}-bg`} style={percentStyle} />
</div>
</div>
{progressInfo}
</div>
);
} else if (type === 'circle') {
const circleSize = width || 132;
const circleStyle = {
width: circleSize,
height: circleSize,
fontSize: circleSize * 0.16 + 6,
};
const circleWidth = strokeWidth || 6;
progress = (
<div className={`${prefixCls}-inner`} style={circleStyle}>
<Circle
percent={percent}
strokeWidth={circleWidth}
trailWidth={circleWidth}
strokeColor={statusColorMap[progressStatus]}
trailColor={trailColor}
/>
{progressInfo}
</div>
);
}
const classString = classNames(prefixCls, {
[`${prefixCls}-${type}`]: true,
[`${prefixCls}-status-${progressStatus}`]: true,
[`${prefixCls}-show-info`]: showInfo,
}, className);
return (
<div {...restProps} className={classString}>
{progress}
</div>
);
}
}
| components/progress/progress.tsx | 0 | https://github.com/ant-design/ant-design/commit/6c98d94b0de2fdead95ce98e2435701eb4c1a14d | [
0.00017931617912836373,
0.00017096204101108015,
0.00016708220937289298,
0.0001706565381027758,
0.0000031827214570512297
]
|
{
"id": 0,
"code_window": [
"export class SystemJsNgModuleLoader implements NgModuleFactoryLoader {\n",
" private _config: SystemJsNgModuleLoaderConfig;\n",
"\n",
" /**\n",
" * @internal\n",
" */\n",
" _system: any;\n",
"\n",
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /**
* @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 {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
function mockSystem(module: string, contents: any) {
return {
'import': (target: string) => {
expect(target).toBe(module);
return Promise.resolve(contents);
}
};
}
export function main() {
describe('SystemJsNgModuleLoader', () => {
it('loads a default factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});
loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
}));
it('loads a named factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () =>
mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
it('loads a named factory with a configured prefix and suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler(), {
factoryPathPrefix: 'prefixed/',
factoryPathSuffix: '/suffixed',
});
loader._system = () =>
mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
});
};
| modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.9984641075134277,
0.3987739682197571,
0.00019951500871684402,
0.005058778915554285,
0.486177921295166
]
|
{
"id": 0,
"code_window": [
"export class SystemJsNgModuleLoader implements NgModuleFactoryLoader {\n",
" private _config: SystemJsNgModuleLoaderConfig;\n",
"\n",
" /**\n",
" * @internal\n",
" */\n",
" _system: any;\n",
"\n",
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /**
* @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 {ListWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {ParseError, ParseSourceSpan} from '../parse_util';
import * as html from './ast';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from './interpolation_config';
import * as lex from './lexer';
import {TagDefinition, getNsPrefix, mergeNsAndName} from './tags';
export class TreeError extends ParseError {
static create(elementName: string, span: ParseSourceSpan, msg: string): TreeError {
return new TreeError(elementName, span, msg);
}
constructor(public elementName: string, span: ParseSourceSpan, msg: string) { super(span, msg); }
}
export class ParseTreeResult {
constructor(public rootNodes: html.Node[], public errors: ParseError[]) {}
}
export class Parser {
constructor(public getTagDefinition: (tagName: string) => TagDefinition) {}
parse(
source: string, url: string, parseExpansionForms: boolean = false,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ParseTreeResult {
const tokensAndErrors =
lex.tokenize(source, url, this.getTagDefinition, parseExpansionForms, interpolationConfig);
const treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
return new ParseTreeResult(
treeAndErrors.rootNodes,
(<ParseError[]>tokensAndErrors.errors).concat(treeAndErrors.errors));
}
}
class _TreeBuilder {
private _index: number = -1;
private _peek: lex.Token;
private _rootNodes: html.Node[] = [];
private _errors: TreeError[] = [];
private _elementStack: html.Element[] = [];
constructor(
private tokens: lex.Token[], private getTagDefinition: (tagName: string) => TagDefinition) {
this._advance();
}
build(): ParseTreeResult {
while (this._peek.type !== lex.TokenType.EOF) {
if (this._peek.type === lex.TokenType.TAG_OPEN_START) {
this._consumeStartTag(this._advance());
} else if (this._peek.type === lex.TokenType.TAG_CLOSE) {
this._consumeEndTag(this._advance());
} else if (this._peek.type === lex.TokenType.CDATA_START) {
this._closeVoidElement();
this._consumeCdata(this._advance());
} else if (this._peek.type === lex.TokenType.COMMENT_START) {
this._closeVoidElement();
this._consumeComment(this._advance());
} else if (
this._peek.type === lex.TokenType.TEXT || this._peek.type === lex.TokenType.RAW_TEXT ||
this._peek.type === lex.TokenType.ESCAPABLE_RAW_TEXT) {
this._closeVoidElement();
this._consumeText(this._advance());
} else if (this._peek.type === lex.TokenType.EXPANSION_FORM_START) {
this._consumeExpansion(this._advance());
} else {
// Skip all other tokens...
this._advance();
}
}
return new ParseTreeResult(this._rootNodes, this._errors);
}
private _advance(): lex.Token {
const prev = this._peek;
if (this._index < this.tokens.length - 1) {
// Note: there is always an EOF token at the end
this._index++;
}
this._peek = this.tokens[this._index];
return prev;
}
private _advanceIf(type: lex.TokenType): lex.Token {
if (this._peek.type === type) {
return this._advance();
}
return null;
}
private _consumeCdata(startToken: lex.Token) {
this._consumeText(this._advance());
this._advanceIf(lex.TokenType.CDATA_END);
}
private _consumeComment(token: lex.Token) {
const text = this._advanceIf(lex.TokenType.RAW_TEXT);
this._advanceIf(lex.TokenType.COMMENT_END);
const value = isPresent(text) ? text.parts[0].trim() : null;
this._addToParent(new html.Comment(value, token.sourceSpan));
}
private _consumeExpansion(token: lex.Token) {
const switchValue = this._advance();
const type = this._advance();
const cases: html.ExpansionCase[] = [];
// read =
while (this._peek.type === lex.TokenType.EXPANSION_CASE_VALUE) {
let expCase = this._parseExpansionCase();
if (isBlank(expCase)) return; // error
cases.push(expCase);
}
// read the final }
if (this._peek.type !== lex.TokenType.EXPANSION_FORM_END) {
this._errors.push(
TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '}'.`));
return;
}
const sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
this._addToParent(new html.Expansion(
switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
this._advance();
}
private _parseExpansionCase(): html.ExpansionCase {
const value = this._advance();
// read {
if (this._peek.type !== lex.TokenType.EXPANSION_CASE_EXP_START) {
this._errors.push(
TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '{'.`));
return null;
}
// read until }
const start = this._advance();
const exp = this._collectExpansionExpTokens(start);
if (isBlank(exp)) return null;
const end = this._advance();
exp.push(new lex.Token(lex.TokenType.EOF, [], end.sourceSpan));
// parse everything in between { and }
const parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
if (parsedExp.errors.length > 0) {
this._errors = this._errors.concat(<TreeError[]>parsedExp.errors);
return null;
}
const sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
const expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
return new html.ExpansionCase(
value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
}
private _collectExpansionExpTokens(start: lex.Token): lex.Token[] {
const exp: lex.Token[] = [];
const expansionFormStack = [lex.TokenType.EXPANSION_CASE_EXP_START];
while (true) {
if (this._peek.type === lex.TokenType.EXPANSION_FORM_START ||
this._peek.type === lex.TokenType.EXPANSION_CASE_EXP_START) {
expansionFormStack.push(this._peek.type);
}
if (this._peek.type === lex.TokenType.EXPANSION_CASE_EXP_END) {
if (lastOnStack(expansionFormStack, lex.TokenType.EXPANSION_CASE_EXP_START)) {
expansionFormStack.pop();
if (expansionFormStack.length == 0) return exp;
} else {
this._errors.push(
TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
}
if (this._peek.type === lex.TokenType.EXPANSION_FORM_END) {
if (lastOnStack(expansionFormStack, lex.TokenType.EXPANSION_FORM_START)) {
expansionFormStack.pop();
} else {
this._errors.push(
TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
}
if (this._peek.type === lex.TokenType.EOF) {
this._errors.push(
TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
exp.push(this._advance());
}
}
private _consumeText(token: lex.Token) {
let text = token.parts[0];
if (text.length > 0 && text[0] == '\n') {
const parent = this._getParentElement();
if (isPresent(parent) && parent.children.length == 0 &&
this.getTagDefinition(parent.name).ignoreFirstLf) {
text = text.substring(1);
}
}
if (text.length > 0) {
this._addToParent(new html.Text(text, token.sourceSpan));
}
}
private _closeVoidElement(): void {
if (this._elementStack.length > 0) {
const el = ListWrapper.last(this._elementStack);
if (this.getTagDefinition(el.name).isVoid) {
this._elementStack.pop();
}
}
}
private _consumeStartTag(startTagToken: lex.Token) {
const prefix = startTagToken.parts[0];
const name = startTagToken.parts[1];
const attrs: html.Attribute[] = [];
while (this._peek.type === lex.TokenType.ATTR_NAME) {
attrs.push(this._consumeAttr(this._advance()));
}
const fullName = this._getElementFullName(prefix, name, this._getParentElement());
let selfClosing = false;
// Note: There could have been a tokenizer error
// so that we don't get a token for the end tag...
if (this._peek.type === lex.TokenType.TAG_OPEN_END_VOID) {
this._advance();
selfClosing = true;
const tagDef = this.getTagDefinition(fullName);
if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
this._errors.push(TreeError.create(
fullName, startTagToken.sourceSpan,
`Only void and foreign elements can be self closed "${startTagToken.parts[1]}"`));
}
} else if (this._peek.type === lex.TokenType.TAG_OPEN_END) {
this._advance();
selfClosing = false;
}
const end = this._peek.sourceSpan.start;
const span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
const el = new html.Element(fullName, attrs, [], span, span, null);
this._pushElement(el);
if (selfClosing) {
this._popElement(fullName);
el.endSourceSpan = span;
}
}
private _pushElement(el: html.Element) {
if (this._elementStack.length > 0) {
const parentEl = ListWrapper.last(this._elementStack);
if (this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
this._elementStack.pop();
}
}
const tagDef = this.getTagDefinition(el.name);
const {parent, container} = this._getParentElementSkippingContainers();
if (isPresent(parent) && tagDef.requireExtraParent(parent.name)) {
const newParent = new html.Element(
tagDef.parentToAdd, [], [], el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
this._insertBeforeContainer(parent, container, newParent);
}
this._addToParent(el);
this._elementStack.push(el);
}
private _consumeEndTag(endTagToken: lex.Token) {
const fullName = this._getElementFullName(
endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
if (this._getParentElement()) {
this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
}
if (this.getTagDefinition(fullName).isVoid) {
this._errors.push(TreeError.create(
fullName, endTagToken.sourceSpan,
`Void elements do not have end tags "${endTagToken.parts[1]}"`));
} else if (!this._popElement(fullName)) {
this._errors.push(TreeError.create(
fullName, endTagToken.sourceSpan, `Unexpected closing tag "${endTagToken.parts[1]}"`));
}
}
private _popElement(fullName: string): boolean {
for (let stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
const el = this._elementStack[stackIndex];
if (el.name == fullName) {
ListWrapper.splice(this._elementStack, stackIndex, this._elementStack.length - stackIndex);
return true;
}
if (!this.getTagDefinition(el.name).closedByParent) {
return false;
}
}
return false;
}
private _consumeAttr(attrName: lex.Token): html.Attribute {
const fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
let end = attrName.sourceSpan.end;
let value = '';
if (this._peek.type === lex.TokenType.ATTR_VALUE) {
const valueToken = this._advance();
value = valueToken.parts[0];
end = valueToken.sourceSpan.end;
}
return new html.Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end));
}
private _getParentElement(): html.Element {
return this._elementStack.length > 0 ? ListWrapper.last(this._elementStack) : null;
}
/**
* Returns the parent in the DOM and the container.
*
* `<ng-container>` elements are skipped as they are not rendered as DOM element.
*/
private _getParentElementSkippingContainers(): {parent: html.Element, container: html.Element} {
let container: html.Element = null;
for (let i = this._elementStack.length - 1; i >= 0; i--) {
if (this._elementStack[i].name !== 'ng-container') {
return {parent: this._elementStack[i], container};
}
container = this._elementStack[i];
}
return {parent: ListWrapper.last(this._elementStack), container};
}
private _addToParent(node: html.Node) {
const parent = this._getParentElement();
if (isPresent(parent)) {
parent.children.push(node);
} else {
this._rootNodes.push(node);
}
}
/**
* Insert a node between the parent and the container.
* When no container is given, the node is appended as a child of the parent.
* Also updates the element stack accordingly.
*
* @internal
*/
private _insertBeforeContainer(
parent: html.Element, container: html.Element, node: html.Element) {
if (!container) {
this._addToParent(node);
this._elementStack.push(node);
} else {
if (parent) {
// replace the container with the new node in the children
const index = parent.children.indexOf(container);
parent.children[index] = node;
} else {
this._rootNodes.push(node);
}
node.children.push(container);
this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
}
}
private _getElementFullName(prefix: string, localName: string, parentElement: html.Element):
string {
if (isBlank(prefix)) {
prefix = this.getTagDefinition(localName).implicitNamespacePrefix;
if (isBlank(prefix) && isPresent(parentElement)) {
prefix = getNsPrefix(parentElement.name);
}
}
return mergeNsAndName(prefix, localName);
}
}
function lastOnStack(stack: any[], element: any): boolean {
return stack.length > 0 && stack[stack.length - 1] === element;
}
| modules/@angular/compiler/src/ml_parser/parser.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.9769790768623352,
0.042495615780353546,
0.00016765961481723934,
0.0001728237548377365,
0.18742811679840088
]
|
{
"id": 0,
"code_window": [
"export class SystemJsNgModuleLoader implements NgModuleFactoryLoader {\n",
" private _config: SystemJsNgModuleLoaderConfig;\n",
"\n",
" /**\n",
" * @internal\n",
" */\n",
" _system: any;\n",
"\n",
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /**
* @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, Injectable, OpaqueToken} from '@angular/core';
import {Options} from '../common_options';
import {DateWrapper, Json, isBlank, isPresent} from '../facade/lang';
import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter';
import {SampleDescription} from '../sample_description';
import {formatStats, sortedProps} from './util';
/**
* A reporter that writes results into a json file.
*/
@Injectable()
export class JsonFileReporter extends Reporter {
static PATH = new OpaqueToken('JsonFileReporter.path');
static PROVIDERS = [JsonFileReporter, {provide: JsonFileReporter.PATH, useValue: '.'}];
constructor(
private _description: SampleDescription, @Inject(JsonFileReporter.PATH) private _path: string,
@Inject(Options.WRITE_FILE) private _writeFile: Function,
@Inject(Options.NOW) private _now: Function) {
super();
}
reportMeasureValues(measureValues: MeasureValues): Promise<any> { return Promise.resolve(null); }
reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise<any> {
const stats: {[key: string]: string} = {};
sortedProps(this._description.metrics).forEach((metricName) => {
stats[metricName] = formatStats(validSample, metricName);
});
var content = Json.stringify({
'description': this._description,
'stats': stats,
'completeSample': completeSample,
'validSample': validSample,
});
var filePath =
`${this._path}/${this._description.id}_${DateWrapper.toMillis(this._now())}.json`;
return this._writeFile(filePath, content);
}
}
| modules/@angular/benchpress/src/reporter/json_file_reporter.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.6428553462028503,
0.10728859156370163,
0.00017361249774694443,
0.00017480403766967356,
0.23951271176338196
]
|
{
"id": 0,
"code_window": [
"export class SystemJsNgModuleLoader implements NgModuleFactoryLoader {\n",
" private _config: SystemJsNgModuleLoaderConfig;\n",
"\n",
" /**\n",
" * @internal\n",
" */\n",
" _system: any;\n",
"\n",
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /**
* @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 {verifyNoBrowserErrors} from 'e2e_util/e2e_util';
var URL = 'all/playground/src/web_workers/message_broker/index.html';
describe('MessageBroker', function() {
afterEach(() => {
verifyNoBrowserErrors();
browser.ignoreSynchronization = false;
});
it('should bootstrap', () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
waitForBootstrap();
expect(element(by.css('app h1')).getText()).toEqual('WebWorker MessageBroker Test');
});
it('should echo messages', () => {
const VALUE = 'Hi There';
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
waitForBootstrap();
var input = element.all(by.css('#echo_input')).first();
input.sendKeys(VALUE);
element(by.css('#send_echo')).click();
var area = element(by.css('#echo_result'));
browser.wait(protractor.until.elementTextIs(area, VALUE), 5000);
expect(area.getText()).toEqual(VALUE);
});
});
function waitForBootstrap(): void {
browser.wait(protractor.until.elementLocated(by.css('app h1')), 15000);
}
| modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017579081759322435,
0.00017335431766696274,
0.00016907864483073354,
0.0001743465691106394,
0.000002380136720603332
]
|
{
"id": 1,
"code_window": [
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n",
" this._system = () => System;\n",
" this._config = config || DEFAULT_CONFIG;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /**
* @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 {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
function mockSystem(module: string, contents: any) {
return {
'import': (target: string) => {
expect(target).toBe(module);
return Promise.resolve(contents);
}
};
}
export function main() {
describe('SystemJsNgModuleLoader', () => {
it('loads a default factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});
loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
}));
it('loads a named factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () =>
mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
it('loads a named factory with a configured prefix and suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler(), {
factoryPathPrefix: 'prefixed/',
factoryPathSuffix: '/suffixed',
});
loader._system = () =>
mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
});
};
| modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.43612685799598694,
0.11977998912334442,
0.0001738931459840387,
0.0003362910356372595,
0.17013752460479736
]
|
{
"id": 1,
"code_window": [
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n",
" this._system = () => System;\n",
" this._config = config || DEFAULT_CONFIG;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 56
} | <!doctype html>
<html>
<body>
<h2>Params</h2>
<form>
Depth:
<input type="number" name="depth" placeholder="depth" value="9">
<br>
<button>Apply</button>
</form>
<h2>Baseline tree benchmark</h2>
<p>
<button id="destroyDom">destroyDom</button>
<button id="createDom">createDom</button>
<button id="updateDomProfile">profile updateDom</button>
<button id="createDomProfile">profile createDom</button>
</p>
<div>
<tree id="root"></tree>
</div>
<script src="../../bootstrap_plain.js"></script>
</body>
</html> | modules/benchmarks/src/tree/incremental_dom/index.html | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017507623124402016,
0.00017419979849364609,
0.0001730954390950501,
0.00017442771058995277,
8.245580715993128e-7
]
|
{
"id": 1,
"code_window": [
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n",
" this._system = () => System;\n",
" this._config = config || DEFAULT_CONFIG;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /**
* @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 {CommonModule} from '@angular/common';
import {AnimationDriver} from '@angular/platform-browser/src/dom/animation_driver';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {MockAnimationDriver} from '@angular/platform-browser/testing/mock_animation_driver';
import {Component} from '../../index';
import {DEFAULT_STATE} from '../../src/animation/animation_constants';
import {AnimationKeyframe} from '../../src/animation/animation_keyframe';
import {AnimationPlayer} from '../../src/animation/animation_player';
import {AnimationStyles} from '../../src/animation/animation_styles';
import {AnimationTransitionEvent} from '../../src/animation/animation_transition_event';
import {AUTO_STYLE, animate, group, keyframes, sequence, state, style, transition, trigger} from '../../src/animation/metadata';
import {isPresent} from '../../src/facade/lang';
import {TestBed, fakeAsync, flushMicrotasks} from '../../testing';
import {MockAnimationPlayer} from '../../testing/mock_animation_player';
export function main() {
describe('jit', () => { declareTests({useJit: true}); });
describe('no jit', () => { declareTests({useJit: false}); });
}
function declareTests({useJit}: {useJit: boolean}) {
describe('animation tests', function() {
beforeEach(() => {
InnerContentTrackingAnimationPlayer.initLog = [];
TestBed.configureCompiler({useJit: useJit});
TestBed.configureTestingModule({
declarations: [DummyLoadingCmp, DummyIfCmp],
providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}],
imports: [CommonModule]
});
});
describe('animation triggers', () => {
it('should trigger a state change animation from void => state', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [trigger(
'myAnimation',
[transition(
'void => *',
[style({'opacity': 0}), animate(500, style({'opacity': 1}))])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(1);
var keyframes2 = driver.log[0]['keyframeLookup'];
expect(keyframes2.length).toEqual(2);
expect(keyframes2[0]).toEqual([0, {'opacity': 0}]);
expect(keyframes2[1]).toEqual([1, {'opacity': 1}]);
}));
it('should trigger a state change animation from state => void', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [trigger(
'myAnimation',
[transition(
'* => void',
[style({'opacity': 1}), animate(500, style({'opacity': 0}))])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(1);
var keyframes2 = driver.log[0]['keyframeLookup'];
expect(keyframes2.length).toEqual(2);
expect(keyframes2[0]).toEqual([0, {'opacity': 1}]);
expect(keyframes2[1]).toEqual([1, {'opacity': 0}]);
}));
it('should animate the element when the expression changes between states', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => state1', [
style({'background': 'red'}),
animate('0.5s 1s ease-out', style({'background': 'blue'}))
])
])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = 'state1';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(1);
var animation1 = driver.log[0];
expect(animation1['duration']).toEqual(500);
expect(animation1['delay']).toEqual(1000);
expect(animation1['easing']).toEqual('ease-out');
var startingStyles = animation1['startingStyles'];
expect(startingStyles).toEqual({'background': 'red'});
var kf = animation1['keyframeLookup'];
expect(kf[0]).toEqual([0, {'background': 'red'}]);
expect(kf[1]).toEqual([1, {'background': 'blue'}]);
}));
it('should animate between * and void and back even when no expression is assigned',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@myAnimation] *ngIf="exp"></div>
`,
animations: [trigger(
'myAnimation',
[
state('*', style({'opacity': '1'})), state('void', style({'opacity': '0'})),
transition('* => *', [animate('500ms')])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
var result = driver.log.pop();
expect(result['duration']).toEqual(500);
expect(result['startingStyles']).toEqual({'opacity': '0'});
expect(result['keyframeLookup']).toEqual([[0, {'opacity': '0'}], [1, {'opacity': '1'}]]);
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
result = driver.log.pop();
expect(result['duration']).toEqual(500);
expect(result['startingStyles']).toEqual({'opacity': '1'});
expect(result['keyframeLookup']).toEqual([[0, {'opacity': '1'}], [1, {'opacity': '0'}]]);
}));
it('should combine repeated style steps into a single step', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [
style({'background': 'red'}),
style({'width': '100px'}),
style({'background': 'gold'}),
style({'height': 111}),
animate('999ms', style({'width': '200px', 'background': 'blue'})),
style({'opacity': '1'}),
style({'border-width': '100px'}),
animate('999ms', style({'opacity': '0', 'height': '200px', 'border-width': '10px'}))
])
])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(2);
var animation1 = driver.log[0];
expect(animation1['duration']).toEqual(999);
expect(animation1['delay']).toEqual(0);
expect(animation1['easing']).toEqual(null);
expect(animation1['startingStyles'])
.toEqual({'background': 'gold', 'width': '100px', 'height': 111});
var keyframes1 = animation1['keyframeLookup'];
expect(keyframes1[0]).toEqual([0, {'background': 'gold', 'width': '100px'}]);
expect(keyframes1[1]).toEqual([1, {'background': 'blue', 'width': '200px'}]);
var animation2 = driver.log[1];
expect(animation2['duration']).toEqual(999);
expect(animation2['delay']).toEqual(0);
expect(animation2['easing']).toEqual(null);
expect(animation2['startingStyles']).toEqual({'opacity': '1', 'border-width': '100px'});
var keyframes2 = animation2['keyframeLookup'];
expect(keyframes2[0]).toEqual([
0, {'opacity': '1', 'height': 111, 'border-width': '100px'}
]);
expect(keyframes2[1]).toEqual([
1, {'opacity': '0', 'height': '200px', 'border-width': '10px'}
]);
}));
describe('groups/sequences', () => {
var assertPlaying = (player: MockAnimationDriver, isPlaying: any /** TODO #9100 */) => {
var method = 'play';
var lastEntry = player.log.length > 0 ? player.log[player.log.length - 1] : null;
if (isPresent(lastEntry)) {
if (isPlaying) {
expect(lastEntry).toEqual(method);
} else {
expect(lastEntry).not.toEqual(method);
}
}
};
it('should run animations in sequence one by one if a top-level array is used',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [transition(
'void => *',
[
style({'opacity': '0'}),
animate(1000, style({'opacity': '0.5'})),
animate('1000ms', style({'opacity': '0.8'})),
animate('1s', style({'opacity': '1'})),
])])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(3);
var player1 = driver.log[0]['player'];
var player2 = driver.log[1]['player'];
var player3 = driver.log[2]['player'];
assertPlaying(player1, true);
assertPlaying(player2, false);
assertPlaying(player3, false);
player1.finish();
assertPlaying(player1, false);
assertPlaying(player2, true);
assertPlaying(player3, false);
player2.finish();
assertPlaying(player1, false);
assertPlaying(player2, false);
assertPlaying(player3, true);
player3.finish();
assertPlaying(player1, false);
assertPlaying(player2, false);
assertPlaying(player3, false);
}));
it('should run animations in parallel if a group is used', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [
style({'width': 0, 'height': 0}),
group([animate(1000, style({'width': 100})), animate(5000, style({'height': 500}))]),
group([animate(1000, style({'width': 0})), animate(5000, style({'height': 0}))])
])
])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(5);
var player1 = driver.log[0]['player'];
var player2 = driver.log[1]['player'];
var player3 = driver.log[2]['player'];
var player4 = driver.log[3]['player'];
var player5 = driver.log[4]['player'];
assertPlaying(player1, true);
assertPlaying(player2, false);
assertPlaying(player3, false);
assertPlaying(player4, false);
assertPlaying(player5, false);
player1.finish();
assertPlaying(player1, false);
assertPlaying(player2, true);
assertPlaying(player3, true);
assertPlaying(player4, false);
assertPlaying(player5, false);
player2.finish();
assertPlaying(player1, false);
assertPlaying(player2, false);
assertPlaying(player3, true);
assertPlaying(player4, false);
assertPlaying(player5, false);
player3.finish();
assertPlaying(player1, false);
assertPlaying(player2, false);
assertPlaying(player3, false);
assertPlaying(player4, true);
assertPlaying(player5, true);
}));
});
describe('keyframes', () => {
it('should create an animation step with multiple keyframes', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [trigger(
'myAnimation',
[transition('void => *', [animate(
1000, keyframes([
style([{'width': 0, offset: 0}]),
style([{'width': 100, offset: 0.25}]),
style([{'width': 200, offset: 0.75}]),
style([{'width': 300, offset: 1}])
]))])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
var kf = driver.log[0]['keyframeLookup'];
expect(kf.length).toEqual(4);
expect(kf[0]).toEqual([0, {'width': 0}]);
expect(kf[1]).toEqual([0.25, {'width': 100}]);
expect(kf[2]).toEqual([0.75, {'width': 200}]);
expect(kf[3]).toEqual([1, {'width': 300}]);
}));
it('should fetch any keyframe styles that are not defined in the first keyframe from the previous entries or getCompuedStyle',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [
style({'color': 'white'}),
animate(1000, style({'color': 'silver'})),
animate(1000, keyframes([
style([{'color': 'gold', offset: 0.25}]),
style([{'color': 'bronze', 'background-color': 'teal', offset: 0.50}]),
style([{'color': 'platinum', offset: 0.75}]),
style([{'color': 'diamond', offset: 1}])
]))
])
])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
var kf = driver.log[1]['keyframeLookup'];
expect(kf.length).toEqual(5);
expect(kf[0]).toEqual([0, {'color': 'silver', 'background-color': AUTO_STYLE}]);
expect(kf[1]).toEqual([0.25, {'color': 'gold'}]);
expect(kf[2]).toEqual([0.50, {'color': 'bronze', 'background-color': 'teal'}]);
expect(kf[3]).toEqual([0.75, {'color': 'platinum'}]);
expect(kf[4]).toEqual([1, {'color': 'diamond', 'background-color': 'teal'}]);
}));
});
it('should cancel the previously running animation active with the same element/animationName pair',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [trigger(
'myAnimation',
[transition(
'* => *',
[style({'opacity': 0}), animate(500, style({'opacity': 1}))])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = 'state1';
fixture.detectChanges();
flushMicrotasks();
var enterCompleted = false;
var enterPlayer = driver.log[0]['player'];
enterPlayer.onDone(() => enterCompleted = true);
expect(enterCompleted).toEqual(false);
cmp.exp = 'state2';
fixture.detectChanges();
flushMicrotasks();
expect(enterCompleted).toEqual(true);
}));
it('should destroy all animation players once the animation is complete', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [
style({'background': 'red', 'opacity': 0.5}),
animate(500, style({'background': 'black'})),
group([
animate(500, style({'background': 'black'})),
animate(1000, style({'opacity': '0.2'})),
]),
sequence([
animate(500, style({'opacity': '1'})),
animate(1000, style({'background': 'white'}))
])
])
])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(5);
driver.log.forEach(entry => entry['player'].finish());
driver.log.forEach(entry => {
var player = <MockAnimationDriver>entry['player'];
expect(player.log[player.log.length - 2]).toEqual('finish');
expect(player.log[player.log.length - 1]).toEqual('destroy');
});
}));
it('should use first matched animation when multiple animations are registered',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@rotate]="exp"></div>
<div [@rotate]="exp2"></div>
`,
animations: [
trigger(
'rotate',
[
transition(
'start => *',
[
style({'color': 'white'}),
animate(500, style({'color': 'red'}))
]),
transition(
'start => end',
[
style({'color': 'white'}),
animate(500, style({'color': 'pink'}))
])
])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = 'start';
cmp.exp2 = 'start';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(0);
cmp.exp = 'something';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(1);
var animation1 = driver.log[0];
var keyframes1 = animation1['keyframeLookup'];
var toStyles1 = keyframes1[1][1];
expect(toStyles1['color']).toEqual('red');
cmp.exp2 = 'end';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(2);
var animation2 = driver.log[1];
var keyframes2 = animation2['keyframeLookup'];
var toStyles2 = keyframes2[1][1];
expect(toStyles2['color']).toEqual('red');
}));
it('should not remove the element until the void transition animation is complete',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="my-if" *ngIf="exp" [@myAnimation]></div>
`,
animations: [trigger(
'myAnimation',
[transition('* => void', [animate(1000, style({'opacity': 0}))])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
var player = driver.log[0]['player'];
var container = fixture.debugElement.nativeElement;
var ifElm = getDOM().querySelector(container, '.my-if');
expect(ifElm).toBeTruthy();
player.finish();
ifElm = getDOM().querySelector(container, '.my-if');
expect(ifElm).toBeFalsy();
}));
it('should fill an animation with the missing style values if not defined within an earlier style step',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@myAnimation]="exp"></div>
`,
animations:
[trigger('myAnimation', [transition(
'* => *',
[
animate(1000, style({'opacity': 0})),
animate(1000, style({'opacity': 1}))
])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = 'state1';
fixture.detectChanges();
flushMicrotasks();
var animation1 = driver.log[0];
var keyframes1 = animation1['keyframeLookup'];
expect(keyframes1[0]).toEqual([0, {'opacity': AUTO_STYLE}]);
expect(keyframes1[1]).toEqual([1, {'opacity': 0}]);
var animation2 = driver.log[1];
var keyframes2 = animation2['keyframeLookup'];
expect(keyframes2[0]).toEqual([0, {'opacity': 0}]);
expect(keyframes2[1]).toEqual([1, {'opacity': 1}]);
}));
it('should perform two transitions in parallel if defined in different state triggers',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@one]="exp" [@two]="exp2"></div>
`,
animations: [
trigger(
'one', [transition(
'state1 => state2',
[style({'opacity': 0}), animate(1000, style({'opacity': 1}))])]),
trigger(
'two',
[transition(
'state1 => state2',
[style({'width': 100}), animate(1000, style({'width': 1000}))])])
]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = 'state1';
cmp.exp2 = 'state1';
fixture.detectChanges();
flushMicrotasks();
cmp.exp = 'state2';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(1);
var count = 0;
var animation1 = driver.log[0];
var player1 = animation1['player'];
player1.onDone(() => count++);
expect(count).toEqual(0);
cmp.exp2 = 'state2';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(2);
expect(count).toEqual(0);
var animation2 = driver.log[1];
var player2 = animation2['player'];
player2.onDone(() => count++);
expect(count).toEqual(0);
player1.finish();
expect(count).toEqual(1);
player2.finish();
expect(count).toEqual(2);
}));
});
describe('ng directives', () => {
describe('*ngFor', () => {
let tpl = '<div *ngFor="let item of items" @trigger>{{ item }}</div>';
let getText =
(node: any) => { return node.innerHTML ? node.innerHTML : node.children[0].data; };
let assertParentChildContents = (parent: any, content: string) => {
var values: string[] = [];
for (var i = 0; i < parent.childNodes.length; i++) {
let child = parent.childNodes[i];
if (child['nodeType'] == 1) {
values.push(getText(child).trim());
}
}
var value = values.join(' -> ');
expect(value).toEqual(content);
};
it('should animate when items are inserted into the list at different points',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: tpl,
animations: [trigger('trigger', [transition('void => *', [animate(1000)])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var parent = fixture.debugElement.nativeElement;
cmp.items = [0, 2, 4, 6, 8];
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(5);
assertParentChildContents(parent, '0 -> 2 -> 4 -> 6 -> 8');
driver.log = [];
cmp.items = [0, 1, 2, 3, 4, 5, 6, 7, 8];
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(4);
assertParentChildContents(parent, '0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8');
}));
it('should animate when items are removed + moved into the list at different points and retain DOM ordering during the animation',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: tpl,
animations: [trigger('trigger', [transition('* => *', [animate(1000)])])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var parent = fixture.debugElement.nativeElement;
cmp.items = [0, 1, 2, 3, 4];
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(5);
driver.log = [];
cmp.items = [3, 4, 0, 9];
fixture.detectChanges();
flushMicrotasks();
// TODO (matsko): update comment below once move animations are a thing
// there are only three animations since we do
// not yet support move-based animations
expect(driver.log.length).toEqual(3);
// move(~), add(+), remove(-)
// -1, -2, ~3, ~4, ~0, +9
var rm0 = driver.log.shift();
var rm1 = driver.log.shift();
var in0 = driver.log.shift();
// we want to assert that the DOM chain is still preserved
// until the animations are closed
assertParentChildContents(parent, '3 -> 4 -> 0 -> 9 -> 1 -> 2');
rm0['player'].finish();
assertParentChildContents(parent, '3 -> 4 -> 0 -> 9 -> 2');
rm1['player'].finish();
assertParentChildContents(parent, '3 -> 4 -> 0 -> 9');
}));
});
});
describe('DOM order tracking', () => {
if (!getDOM().supportsDOMEvents()) return;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: AnimationDriver, useClass: InnerContentTrackingAnimationDriver}]
});
});
it('should evaluate all inner children and their bindings before running the animation on a parent',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp">
<div *ngIf="exp2" class="inner">inner child guy</div>
</div>
`,
animations: [trigger(
'status',
[
state('final', style({'height': '*'})), transition('* => *', [animate(1000)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = true;
cmp.exp2 = true;
fixture.detectChanges();
flushMicrotasks();
var animation = driver.log.pop();
var player = <InnerContentTrackingAnimationPlayer>animation['player'];
expect(player.capturedInnerText).toEqual('inner child guy');
}));
it('should run the initialization stage after all children have been evaluated',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp">
<div style="height:20px"></div>
<div *ngIf="exp2" style="height:40px;" class="inner">inner child guy</div>
</div>
`,
animations:
[trigger('status', [transition('* => *', sequence([
animate(1000, style({height: 0})),
animate(1000, style({height: '*'}))
]))])]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
cmp.exp2 = true;
fixture.detectChanges();
flushMicrotasks();
fixture.detectChanges();
var animation = driver.log.pop();
var player = <InnerContentTrackingAnimationPlayer>animation['player'];
// this is just to confirm that the player is using the parent element
expect(player.element.className).toEqual('target');
expect(player.computedHeight).toEqual('60px');
}));
it('should not trigger animations more than once within a view that contains multiple animation triggers',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" @one><div class="inner"></div></div>
<div *ngIf="exp2" @two><div class="inner"></div></div>
`,
animations: [
trigger('one', [transition('* => *', [animate(1000)])]),
trigger('two', [transition('* => *', [animate(2000)])])
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
cmp.exp2 = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(2);
var animation1 = driver.log.pop();
var animation2 = driver.log.pop();
var player1 = <InnerContentTrackingAnimationPlayer>animation1['player'];
var player2 = <InnerContentTrackingAnimationPlayer>animation2['player'];
expect(player1.playAttempts).toEqual(1);
expect(player2.playAttempts).toEqual(1);
}));
it('should trigger animations when animations are detached from the page', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" @trigger><div class="inner"></div></div>
`,
animations: [
trigger('trigger', [transition('* => void', [animate(1000)])]),
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(1);
var animation = driver.log.pop();
var player = <InnerContentTrackingAnimationPlayer>animation['player'];
expect(player.playAttempts).toEqual(1);
}));
it('should always trigger animations on the parent first before starting the child',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@outer]="exp">
outer
<div *ngIf="exp2" [@inner]="exp">
inner
< </div>
< </div>
`,
animations: [
trigger('outer', [transition('* => *', [animate(1000)])]),
trigger('inner', [transition('* => *', [animate(1000)])]),
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
cmp.exp2 = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(2);
var inner: any = driver.log.pop();
var innerPlayer: any = <InnerContentTrackingAnimationPlayer>inner['player'];
var outer: any = driver.log.pop();
var outerPlayer: any = <InnerContentTrackingAnimationPlayer>outer['player'];
expect(InnerContentTrackingAnimationPlayer.initLog).toEqual([
outerPlayer.element, innerPlayer.element
]);
}));
it('should trigger animations that exist in nested views even if a parent embedded view does not contain an animation',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngIf="exp" [@outer]="exp">
outer
<div *ngIf="exp">
middle
<div *ngIf="exp2" [@inner]="exp">
inner
</div>
< </div>
< </div>
`,
animations: [
trigger('outer', [transition('* => *', [animate(1000)])]),
trigger('inner', [transition('* => *', [animate(1000)])]),
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
cmp.exp2 = true;
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(2);
var inner: any = driver.log.pop();
var innerPlayer: any = <InnerContentTrackingAnimationPlayer>inner['player'];
var outer: any = driver.log.pop();
var outerPlayer: any = <InnerContentTrackingAnimationPlayer>outer['player'];
expect(InnerContentTrackingAnimationPlayer.initLog).toEqual([
outerPlayer.element, innerPlayer.element
]);
}));
});
describe('animation output events', () => {
it('should fire the associated animation output expression when the animation starts even if no animation is fired',
() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@trigger]="exp" (@trigger.start)="callback($event)"></div>
`,
animations: [
trigger('trigger', [transition('one => two', [animate(1000)])]),
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var isAnimationRunning = false;
var calls = 0;
var cmp = fixture.debugElement.componentInstance;
cmp.callback = (e: AnimationTransitionEvent) => {
isAnimationRunning = e.totalTime > 0;
calls++;
};
cmp.exp = 'one';
fixture.detectChanges();
expect(calls).toEqual(1);
expect(isAnimationRunning).toEqual(false);
cmp.exp = 'two';
fixture.detectChanges();
expect(calls).toEqual(2);
expect(isAnimationRunning).toEqual(true);
});
it('should fire the associated animation output expression when the animation ends even if no animation is fired',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@trigger]="exp" (@trigger.done)="callback($event)"></div>
`,
animations: [
trigger('trigger', [transition('one => two', [animate(1000)])]),
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var isAnimationRunning = false;
var calls = 0;
var cmp = fixture.debugElement.componentInstance;
cmp.callback = (e: AnimationTransitionEvent) => {
isAnimationRunning = e.totalTime > 0;
calls++;
};
cmp.exp = 'one';
fixture.detectChanges();
expect(calls).toEqual(0);
flushMicrotasks();
expect(calls).toEqual(1);
expect(isAnimationRunning).toEqual(false);
cmp.exp = 'two';
fixture.detectChanges();
expect(calls).toEqual(1);
var player = driver.log.shift()['player'];
player.finish();
expect(calls).toEqual(2);
expect(isAnimationRunning).toEqual(true);
}));
it('should emit the `fromState` and `toState` within the event data when a callback is fired',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@trigger]="exp" (@trigger.start)="callback($event)"></div>
`,
animations: [
trigger('trigger', [transition('one => two', [animate(1000)])]),
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var eventData: AnimationTransitionEvent = null;
var cmp = fixture.debugElement.componentInstance;
cmp.callback = (e: AnimationTransitionEvent) => { eventData = e; };
cmp.exp = 'one';
fixture.detectChanges();
flushMicrotasks();
expect(eventData.fromState).toEqual('void');
expect(eventData.toState).toEqual('one');
cmp.exp = 'two';
fixture.detectChanges();
flushMicrotasks();
expect(eventData.fromState).toEqual('one');
expect(eventData.toState).toEqual('two');
}));
it('should emit the `totalTime` values for an animation callback', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@trigger]="exp" (@trigger.start)="callback1($event)"></div>
<div [@noTrigger]="exp2" (@noTrigger.start)="callback2($event)"></div>
`,
animations: [
trigger(
'trigger',
[transition(
'* => *',
[animate('1s 750ms', style({})), animate('2000ms 0ms', style({}))])]),
trigger('noTrigger', [])
]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var eventData1: AnimationTransitionEvent = null;
var eventData2: AnimationTransitionEvent = null;
var cmp = fixture.debugElement.componentInstance;
cmp.callback1 = (e: AnimationTransitionEvent) => { eventData1 = e; };
cmp.callback2 = (e: AnimationTransitionEvent) => { eventData2 = e; };
cmp.exp = 'one';
fixture.detectChanges();
flushMicrotasks();
expect(eventData1.totalTime).toEqual(3750);
cmp.exp2 = 'two';
fixture.detectChanges();
flushMicrotasks();
expect(eventData2.totalTime).toEqual(0);
}));
it('should throw an error if an animation output is referenced is not defined within the component',
() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [@something]="exp" (@something.done)="callback($event)"></div>
`
}
});
var message = '';
try {
let fixture = TestBed.createComponent(DummyIfCmp);
fixture.detectChanges();
} catch (e) {
message = e.message;
}
expect(message).toMatch(
/- Couldn't find the corresponding animation trigger definition for \(@something\)/);
});
it('should throw an error if an animation output is referenced that is not bound to as a property on the same element',
() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div (@trigger.done)="callback($event)"></div>
`,
animations: [trigger('trigger', [transition('one => two', [animate(1000)])])]
}
});
var message = '';
try {
let fixture = TestBed.createComponent(DummyIfCmp);
fixture.detectChanges();
} catch (e) {
message = e.message;
}
expect(message).toMatch(
/- Unable to listen on \(@trigger.done\) because the animation trigger \[@trigger\] isn't being used on the same element/);
});
it('should throw an error if an unsupported animation output phase name is used', () => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div (@trigger.jump)="callback($event)"></div>
`,
animations: [trigger('trigger', [transition('one => two', [animate(1000)])])]
}
});
var message = '';
try {
let fixture = TestBed.createComponent(DummyIfCmp);
fixture.detectChanges();
} catch (e) {
message = e.message;
}
expect(message).toMatch(
/The provided animation output phase value "jump" for "@trigger" is not supported \(use start or done\)/);
});
it('should throw an error if the animation output event phase value is missing', () => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div (@trigger)="callback($event)"></div>
`,
animations: [trigger('trigger', [transition('one => two', [animate(1000)])])]
}
});
var message = '';
try {
let fixture = TestBed.createComponent(DummyIfCmp);
fixture.detectChanges();
} catch (e) {
message = e.message;
}
expect(message).toMatch(
/The animation trigger output event \(@trigger\) is missing its phase value name \(start or done are currently supported\)/);
});
it('should throw an error when an animation output is referenced but the host-level animation binding is missing',
() => {
TestBed.overrideComponent(
DummyLoadingCmp, {set: {host: {'(@trigger.done)': 'callback($event)'}}});
var message = '';
try {
let fixture = TestBed.createComponent(DummyLoadingCmp);
fixture.detectChanges();
} catch (e) {
message = e.message;
}
expect(message).toMatch(
/Couldn't find the corresponding host-level animation trigger definition for \(@trigger\)/);
});
it('should allow host and element-level animation bindings to be defined on the same tag/component',
fakeAsync(() => {
TestBed.overrideComponent(DummyLoadingCmp, {
set: {
host: {
'[attr.title]': 'exp',
'[@loading]': 'exp',
'(@loading.start)': 'callback($event)'
},
animations: [trigger('loading', [transition('* => *', [animate(1000)])])]
}
});
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<dummy-loading-cmp [@trigger]="exp" (@trigger.start)="callback($event)"></dummy-loading-cmp>
`,
animations: [trigger('trigger', [transition('* => *', [animate(1000)])])]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
var ifCalls = 0;
var loadingCalls = 0;
let fixture = TestBed.createComponent(DummyIfCmp);
var ifCmp = fixture.debugElement.componentInstance;
var loadingCmp = fixture.debugElement.childNodes[1].componentInstance;
ifCmp.callback = (e: any) => ifCalls++;
loadingCmp.callback = (e: any) => loadingCalls++;
expect(ifCalls).toEqual(0);
expect(loadingCalls).toEqual(0);
ifCmp.exp = 'one';
loadingCmp.exp = 'one';
fixture.detectChanges();
flushMicrotasks();
expect(ifCalls).toEqual(1);
expect(loadingCalls).toEqual(1);
ifCmp.exp = 'two';
loadingCmp.exp = 'two';
fixture.detectChanges();
flushMicrotasks();
expect(ifCalls).toEqual(2);
expect(loadingCalls).toEqual(2);
}));
it('should allow animation triggers to trigger on the component when bound to embedded views via ngFor',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div *ngFor="let item of items"
(@trigger.start)="callback($event, item, 'start')"
(@trigger.done)="callback($event, item, 'done')"
@trigger>{{ item }}</div>
`,
animations: [trigger('trigger', [transition('* => *', [animate(1000)])])]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var startCalls = [0, 0, 0, 0, 0];
var doneCalls = [0, 0, 0, 0, 0];
cmp.callback = (e: any, index: number, phase: string) => {
(phase == 'start' ? startCalls : doneCalls)[index] = 1;
};
cmp.items = [0, 1, 2, 3, 4];
fixture.detectChanges();
flushMicrotasks();
for (var i = 0; i < cmp.items.length; i++) {
expect(startCalls[i]).toEqual(1);
}
driver.log[0]['player'].finish();
driver.log[2]['player'].finish();
driver.log[4]['player'].finish();
expect(doneCalls[0]).toEqual(1);
expect(doneCalls[1]).toEqual(0);
expect(doneCalls[2]).toEqual(1);
expect(doneCalls[3]).toEqual(0);
expect(doneCalls[4]).toEqual(1);
driver.log[1]['player'].finish();
driver.log[3]['player'].finish();
expect(doneCalls[0]).toEqual(1);
expect(doneCalls[1]).toEqual(1);
expect(doneCalls[2]).toEqual(1);
expect(doneCalls[3]).toEqual(1);
expect(doneCalls[4]).toEqual(1);
}));
});
describe('ng directives', () => {
describe('[ngClass]', () => {
it('should persist ngClass class values when a remove element animation is active',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div [ngClass]="exp2" *ngIf="exp" @trigger></div>
`,
animations: [trigger('trigger', [transition('* => void', [animate(1000)])])]
}
});
const driver = TestBed.get(AnimationDriver) as InnerContentTrackingAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = true;
cmp.exp2 = 'blue';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
var animation = driver.log.pop();
var element = animation['element'];
(<any>expect(element)).toHaveCssClass('blue');
}));
});
});
describe('animation states', () => {
it('should throw an error when an animation is referenced that isn\'t defined within the component annotation',
() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: []
}
});
var failureMessage = '';
try {
let fixture = TestBed.createComponent(DummyLoadingCmp);
} catch (e) {
failureMessage = e.message;
}
expect(failureMessage)
.toMatch(/Animation parsing for DummyIfCmp has failed due to the following errors:/);
expect(failureMessage).toMatch(/- Couldn't find an animation entry for status/);
});
it('should be permitted to be registered on the host element', fakeAsync(() => {
TestBed.overrideComponent(DummyLoadingCmp, {
set: {
host: {'[@loading]': 'exp'},
animations: [trigger(
'loading',
[
state('final', style({'background': 'grey'})),
transition('* => final', [animate(1000)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyLoadingCmp);
var cmp = fixture.debugElement.componentInstance;
cmp.exp = 'final';
fixture.detectChanges();
flushMicrotasks();
var animation = driver.log.pop();
var kf = animation['keyframeLookup'];
expect(kf[1]).toEqual([1, {'background': 'grey'}]);
}));
it('should throw an error if a host-level referenced animation is not defined within the component',
() => {
TestBed.overrideComponent(DummyLoadingCmp, {set: {animations: []}});
var failureMessage = '';
try {
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
} catch (e) {
failureMessage = e.message;
}
expect(failureMessage).toMatch(/- Couldn't find an animation entry for loading/);
});
it('should retain the destination animation state styles once the animation is complete',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
state('final', style({'top': '100px'})),
transition('* => final', [animate(1000)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'final';
fixture.detectChanges();
flushMicrotasks();
var animation = driver.log[0];
var player = animation['player'];
player.finish();
expect(getDOM().getStyle(node, 'top')).toEqual('100px');
}));
it('should animate to and retain the default animation state styles once the animation is complete if defined',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
state(DEFAULT_STATE, style({'background': 'grey'})),
state('green', style({'background': 'green'})),
state('red', style({'background': 'red'})),
transition('* => *', [animate(1000)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'green';
fixture.detectChanges();
flushMicrotasks();
var animation = driver.log.pop();
var kf = animation['keyframeLookup'];
expect(kf[1]).toEqual([1, {'background': 'green'}]);
cmp.exp = 'blue';
fixture.detectChanges();
flushMicrotasks();
animation = driver.log.pop();
kf = animation['keyframeLookup'];
expect(kf[0]).toEqual([0, {'background': 'green'}]);
expect(kf[1]).toEqual([1, {'background': 'grey'}]);
cmp.exp = 'red';
fixture.detectChanges();
flushMicrotasks();
animation = driver.log.pop();
kf = animation['keyframeLookup'];
expect(kf[0]).toEqual([0, {'background': 'grey'}]);
expect(kf[1]).toEqual([1, {'background': 'red'}]);
cmp.exp = 'orange';
fixture.detectChanges();
flushMicrotasks();
animation = driver.log.pop();
kf = animation['keyframeLookup'];
expect(kf[0]).toEqual([0, {'background': 'red'}]);
expect(kf[1]).toEqual([1, {'background': 'grey'}]);
}));
it('should seed in the origin animation state styles into the first animation step',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
state('void', style({'height': '100px'})),
transition('* => *', [animate(1000)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'final';
fixture.detectChanges();
flushMicrotasks();
var animation = driver.log[0];
expect(animation['startingStyles']).toEqual({'height': '100px'});
}));
it('should perform a state change even if there is no transition that is found',
fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
state('void', style({'width': '0px'})),
state('final', style({'width': '100px'})),
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'final';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.length).toEqual(0);
flushMicrotasks();
expect(getDOM().getStyle(node, 'width')).toEqual('100px');
}));
it('should allow multiple states to be defined with the same styles', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
state('a, c', style({'height': '100px'})),
state('b, d', style({'width': '100px'}))
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'a';
fixture.detectChanges();
flushMicrotasks();
expect(getDOM().getStyle(node, 'height')).toEqual('100px');
expect(getDOM().getStyle(node, 'width')).not.toEqual('100px');
cmp.exp = 'b';
fixture.detectChanges();
flushMicrotasks();
expect(getDOM().getStyle(node, 'height')).not.toEqual('100px');
expect(getDOM().getStyle(node, 'width')).toEqual('100px');
cmp.exp = 'c';
fixture.detectChanges();
flushMicrotasks();
expect(getDOM().getStyle(node, 'height')).toEqual('100px');
expect(getDOM().getStyle(node, 'width')).not.toEqual('100px');
cmp.exp = 'd';
fixture.detectChanges();
flushMicrotasks();
expect(getDOM().getStyle(node, 'height')).not.toEqual('100px');
expect(getDOM().getStyle(node, 'width')).toEqual('100px');
cmp.exp = 'e';
fixture.detectChanges();
flushMicrotasks();
expect(getDOM().getStyle(node, 'height')).not.toEqual('100px');
expect(getDOM().getStyle(node, 'width')).not.toEqual('100px');
}));
it('should allow multiple transitions to be defined with the same sequence', fakeAsync(() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
transition('a => b, b => c', [animate(1000)]),
transition('* => *', [animate(300)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'a';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.pop()['duration']).toEqual(300);
cmp.exp = 'b';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.pop()['duration']).toEqual(1000);
cmp.exp = 'c';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.pop()['duration']).toEqual(1000);
cmp.exp = 'd';
fixture.detectChanges();
flushMicrotasks();
expect(driver.log.pop()['duration']).toEqual(300);
}));
it('should balance the animation with the origin/destination styles as keyframe animation properties',
() => {
TestBed.overrideComponent(DummyIfCmp, {
set: {
template: `
<div class="target" [@status]="exp"></div>
`,
animations: [trigger(
'status',
[
state('void', style({'height': '100px', 'opacity': 0})),
state('final', style({'height': '333px', 'width': '200px'})),
transition('void => final', [animate(1000)])
])]
}
});
const driver = TestBed.get(AnimationDriver) as MockAnimationDriver;
let fixture = TestBed.createComponent(DummyIfCmp);
var cmp = fixture.debugElement.componentInstance;
var node = getDOM().querySelector(fixture.debugElement.nativeElement, '.target');
cmp.exp = 'final';
fixture.detectChanges();
var animation = driver.log.pop();
var kf = animation['keyframeLookup'];
expect(kf[0]).toEqual([0, {'height': '100px', 'opacity': 0, 'width': AUTO_STYLE}]);
expect(kf[1]).toEqual([1, {'height': '333px', 'opacity': AUTO_STYLE, 'width': '200px'}]);
});
});
});
}
class InnerContentTrackingAnimationDriver extends MockAnimationDriver {
animate(
element: any, startingStyles: AnimationStyles, keyframes: AnimationKeyframe[],
duration: number, delay: number, easing: string): AnimationPlayer {
super.animate(element, startingStyles, keyframes, duration, delay, easing);
var player = new InnerContentTrackingAnimationPlayer(element);
this.log[this.log.length - 1]['player'] = player;
return player;
}
}
class InnerContentTrackingAnimationPlayer extends MockAnimationPlayer {
static initLog: any[] = [];
constructor(public element: any) { super(); }
public computedHeight: number;
public capturedInnerText: string;
public playAttempts = 0;
init() {
InnerContentTrackingAnimationPlayer.initLog.push(this.element);
this.computedHeight = getDOM().getComputedStyle(this.element)['height'];
}
play() {
this.playAttempts++;
var innerElm = this.element.querySelector('.inner');
this.capturedInnerText = innerElm ? innerElm.innerText : '';
}
}
@Component({
selector: 'if-cmp',
animations: [trigger('myAnimation', [])],
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`
})
class DummyIfCmp {
exp = false;
exp2 = false;
items = [0, 1, 2, 3, 4];
callback: Function = () => {};
}
@Component({
selector: 'dummy-loading-cmp',
host: {'[@loading]': 'exp'},
animations: [trigger('loading', [])],
template: `
<div>loading...</div>
`
})
class DummyLoadingCmp {
exp = false;
callback = () => {};
}
@Component({
selector: 'if-cmp',
host: {
'(@loading.start)': 'callback($event,"start")',
'(@loading.done)': 'callback($event,"done")'
},
template: `
<div>loading...</div>
`
})
class BrokenDummyLoadingCmp {
exp = false;
callback = () => {};
}
| modules/@angular/core/test/animation/animation_integration_spec.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.7697800397872925,
0.004312278237193823,
0.00016558596689719707,
0.000172893880517222,
0.05627831071615219
]
|
{
"id": 1,
"code_window": [
" constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {\n",
" this._system = () => System;\n",
" this._config = config || DEFAULT_CONFIG;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 56
} | #!/usr/bin/env bash
set -ex -o pipefail
# These ones can be `npm link`ed for fast development
LINKABLE_PKGS=(
$(pwd)/dist/packages-dist/{common,forms,core,compiler,compiler-cli,platform-{browser,server},platform-browser-dynamic}
$(pwd)/dist/tools/@angular/tsc-wrapped
)
PKGS=(
[email protected]
[email protected]
[email protected]
[email protected]
@types/{[email protected],[email protected]}
[email protected]
[email protected]
@angular2-material/{core,button}@2.0.0-alpha.8-1
)
TMPDIR=${TMPDIR:-.}
readonly TMP=$TMPDIR/e2e_test.$(date +%s)
mkdir -p $TMP
cp -R -v modules/@angular/compiler-cli/integrationtest/* $TMP
# Try to use the same versions as angular, in particular, this will
# cause us to install the same rxjs version.
cp -v package.json $TMP
# run in subshell to avoid polluting cwd
(
cd $TMP
set -ex -o pipefail
npm install ${PKGS[*]}
# TODO(alexeagle): allow this to be npm link instead
npm install ${LINKABLE_PKGS[*]}
./node_modules/.bin/tsc --version
# Compile the compiler-cli integration tests
# TODO(vicb): restore the test for .xtb
#./node_modules/.bin/ngc --i18nFile=src/messages.fi.xtb --locale=fi --i18nFormat=xtb
./node_modules/.bin/ngc --i18nFile=src/messages.fi.xlf --locale=fi --i18nFormat=xlf
./node_modules/.bin/ng-xi18n --i18nFormat=xlf
./node_modules/.bin/ng-xi18n --i18nFormat=xmb
./node_modules/.bin/jasmine init
# Run compiler-cli integration tests in node
./node_modules/.bin/webpack ./webpack.config.js
./node_modules/.bin/jasmine ./all_spec.js
# Compile again with a differently named tsconfig file
mv tsconfig.json othername.json
./node_modules/.bin/ngc -p othername.json
)
| scripts/ci-lite/offline_compiler_test.sh | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017474833293817937,
0.00017122119606938213,
0.00016875311848707497,
0.00017057833611033857,
0.00000247697539634828
]
|
{
"id": 2,
"code_window": [
"\n",
" private loadAndCompile(path: string): Promise<NgModuleFactory<any>> {\n",
" let [module, exportName] = path.split(_SEPARATOR);\n",
" if (exportName === undefined) exportName = 'default';\n",
"\n",
" return this._system()\n",
" .import(module)\n",
" .then((module: any) => module[exportName])\n",
" .then((type: any) => checkNotEmpty(type, module, exportName))\n",
" .then((type: any) => this._compiler.compileModuleAsync(type));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(module)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 69
} | /**
* @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 {Injectable, Optional} from '../di';
import {Compiler} from './compiler';
import {NgModuleFactory} from './ng_module_factory';
import {NgModuleFactoryLoader} from './ng_module_factory_loader';
const _SEPARATOR = '#';
const FACTORY_CLASS_SUFFIX = 'NgFactory';
/**
* Configuration for SystemJsNgModuleLoader.
* token.
*
* @experimental
*/
export abstract class SystemJsNgModuleLoaderConfig {
/**
* Prefix to add when computing the name of the factory module for a given module name.
*/
factoryPathPrefix: string;
/**
* Suffix to add when computing the name of the factory module for a given module name.
*/
factoryPathSuffix: string;
}
const DEFAULT_CONFIG: SystemJsNgModuleLoaderConfig = {
factoryPathPrefix: '',
factoryPathSuffix: '.ngfactory',
};
/**
* NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory
* @experimental
*/
@Injectable()
export class SystemJsNgModuleLoader implements NgModuleFactoryLoader {
private _config: SystemJsNgModuleLoaderConfig;
/**
* @internal
*/
_system: any;
constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {
this._system = () => System;
this._config = config || DEFAULT_CONFIG;
}
load(path: string): Promise<NgModuleFactory<any>> {
const offlineMode = this._compiler instanceof Compiler;
return offlineMode ? this.loadFactory(path) : this.loadAndCompile(path);
}
private loadAndCompile(path: string): Promise<NgModuleFactory<any>> {
let [module, exportName] = path.split(_SEPARATOR);
if (exportName === undefined) exportName = 'default';
return this._system()
.import(module)
.then((module: any) => module[exportName])
.then((type: any) => checkNotEmpty(type, module, exportName))
.then((type: any) => this._compiler.compileModuleAsync(type));
}
private loadFactory(path: string): Promise<NgModuleFactory<any>> {
let [module, exportName] = path.split(_SEPARATOR);
let factoryClassSuffix = FACTORY_CLASS_SUFFIX;
if (exportName === undefined) {
exportName = 'default';
factoryClassSuffix = '';
}
return this._system()
.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)
.then((module: any) => module[exportName + factoryClassSuffix])
.then((factory: any) => checkNotEmpty(factory, module, exportName));
}
}
function checkNotEmpty(value: any, modulePath: string, exportName: string): any {
if (!value) {
throw new Error(`Cannot find '${exportName}' in '${modulePath}'`);
}
return value;
}
| modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.998267650604248,
0.2981909215450287,
0.00017317272431682795,
0.001831438159570098,
0.4537709653377533
]
|
{
"id": 2,
"code_window": [
"\n",
" private loadAndCompile(path: string): Promise<NgModuleFactory<any>> {\n",
" let [module, exportName] = path.split(_SEPARATOR);\n",
" if (exportName === undefined) exportName = 'default';\n",
"\n",
" return this._system()\n",
" .import(module)\n",
" .then((module: any) => module[exportName])\n",
" .then((type: any) => checkNotEmpty(type, module, exportName))\n",
" .then((type: any) => this._compiler.compileModuleAsync(type));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(module)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 69
} | /**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the platform-browser/testing package.
*/
export * from './browser';
| modules/@angular/platform-browser/testing/index.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017375225434079766,
0.00016926605894695967,
0.00016477986355312169,
0.00016926605894695967,
0.000004486195393837988
]
|
{
"id": 2,
"code_window": [
"\n",
" private loadAndCompile(path: string): Promise<NgModuleFactory<any>> {\n",
" let [module, exportName] = path.split(_SEPARATOR);\n",
" if (exportName === undefined) exportName = 'default';\n",
"\n",
" return this._system()\n",
" .import(module)\n",
" .then((module: any) => module[exportName])\n",
" .then((type: any) => checkNotEmpty(type, module, exportName))\n",
" .then((type: any) => this._compiler.compileModuleAsync(type));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(module)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 69
} | import {SelectorMatcher} from '@angular/compiler/src/selector';
import {CssSelector} from '@angular/compiler/src/selector';
import {Math, StringWrapper} from '@angular/facade/lang';
import {BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter';
import {bindAction, getIntParameter} from '@angular/testing/src/benchmark_util';
export function main() {
BrowserDomAdapter.makeCurrent();
var count = getIntParameter('selectors');
var fixedMatcher;
var fixedSelectorStrings = [];
var fixedSelectors = [];
for (var i = 0; i < count; i++) {
fixedSelectorStrings.push(randomSelector());
}
for (var i = 0; i < count; i++) {
fixedSelectors.push(CssSelector.parse(fixedSelectorStrings[i]));
}
fixedMatcher = new SelectorMatcher();
for (var i = 0; i < count; i++) {
fixedMatcher.addSelectables(fixedSelectors[i], i);
}
function parse() {
var result = [];
for (var i = 0; i < count; i++) {
result.push(CssSelector.parse(fixedSelectorStrings[i]));
}
return result;
}
function addSelectable() {
var matcher = new SelectorMatcher();
for (var i = 0; i < count; i++) {
matcher.addSelectables(fixedSelectors[i], i);
}
return matcher;
}
function match() {
var matchCount = 0;
for (var i = 0; i < count; i++) {
fixedMatcher.match(fixedSelectors[i][0], (selector, selected) => { matchCount += selected; });
}
return matchCount;
}
bindAction('#parse', parse);
bindAction('#addSelectable', addSelectable);
bindAction('#match', match);
}
function randomSelector() {
var res = randomStr(5);
for (var i = 0; i < 3; i++) {
res += '.' + randomStr(5);
}
for (var i = 0; i < 3; i++) {
res += '[' + randomStr(3) + '=' + randomStr(6) + ']';
}
return res;
}
function randomStr(len) {
var s = '';
while (s.length < len) {
s += randomChar();
}
return s;
}
function randomChar() {
var n = randomNum(62);
if (n < 10) return n.toString(); // 1-10
if (n < 36) return StringWrapper.fromCharCode(n + 55); // A-Z
return StringWrapper.fromCharCode(n + 61); // a-z
}
function randomNum(max) {
return Math.floor(Math.random() * max);
}
| modules/benchmarks/src/old/compiler/selector_benchmark.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.0001751139498082921,
0.00017318024765700102,
0.00016996425983961672,
0.00017350277630612254,
0.000001487976874159358
]
|
{
"id": 2,
"code_window": [
"\n",
" private loadAndCompile(path: string): Promise<NgModuleFactory<any>> {\n",
" let [module, exportName] = path.split(_SEPARATOR);\n",
" if (exportName === undefined) exportName = 'default';\n",
"\n",
" return this._system()\n",
" .import(module)\n",
" .then((module: any) => module[exportName])\n",
" .then((type: any) => checkNotEmpty(type, module, exportName))\n",
" .then((type: any) => this._compiler.compileModuleAsync(type));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(module)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 69
} | /**
* @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 {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA} from '@angular/core';
import {Component} from '@angular/core/src/metadata';
import {TestBed, getTestBed} from '@angular/core/testing';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it} from '@angular/core/testing/testing_internal';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DomSanitizer} from '@angular/platform-browser/src/security/dom_sanitization_service';
export function main() {
describe('jit', () => { declareTests({useJit: true}); });
describe('no jit', () => { declareTests({useJit: false}); });
}
@Component({selector: 'my-comp', template: ''})
class SecuredComponent {
ctxProp: string;
constructor() { this.ctxProp = 'some value'; }
}
function declareTests({useJit}: {useJit: boolean}) {
describe('security integration tests', function() {
beforeEach(() => {
TestBed.configureCompiler({useJit: useJit});
TestBed.configureTestingModule({declarations: [SecuredComponent]});
});
let originalLog: (msg: any) => any;
beforeEach(() => {
originalLog = getDOM().log;
getDOM().log = (msg) => { /* disable logging */ };
});
afterEach(() => { getDOM().log = originalLog; });
describe('events', () => {
it('should disallow binding to attr.on*', () => {
const template = `<div [attr.onclick]="ctxProp"></div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
try {
TestBed.createComponent(SecuredComponent);
throw 'Should throw';
} catch (e) {
expect(e.message).toContain(
`Template parse errors:\n` +
`Binding to event attribute 'onclick' is disallowed ` +
`for security reasons, please use (click)=... `);
}
});
it('should disallow binding to on* with NO_ERRORS_SCHEMA', () => {
const template = `<div [onclick]="ctxProp"></div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}}).configureTestingModule({
schemas: [NO_ERRORS_SCHEMA]
});
;
try {
TestBed.createComponent(SecuredComponent);
throw 'Should throw';
} catch (e) {
expect(e.message).toContain(
`Template parse errors:\n` +
`Binding to event attribute 'onclick' is disallowed ` +
`for security reasons, please use (click)=... `);
}
});
});
describe('safe HTML values', function() {
it('should not escape values marked as trusted', () => {
const template = `<a [href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const sanitizer: DomSanitizer = getTestBed().get(DomSanitizer);
let e = fixture.debugElement.children[0].nativeElement;
let ci = fixture.debugElement.componentInstance;
let trusted = sanitizer.bypassSecurityTrustUrl('javascript:alert(1)');
ci.ctxProp = trusted;
fixture.detectChanges();
expect(getDOM().getProperty(e, 'href')).toEqual('javascript:alert(1)');
});
it('should error when using the wrong trusted value', () => {
const template = `<a [href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const sanitizer: DomSanitizer = getTestBed().get(DomSanitizer);
let trusted = sanitizer.bypassSecurityTrustScript('javascript:alert(1)');
let ci = fixture.debugElement.componentInstance;
ci.ctxProp = trusted;
expect(() => fixture.detectChanges()).toThrowError(/Required a safe URL, got a Script/);
});
it('should warn when using in string interpolation', () => {
const template = `<a href="/foo/{{ctxProp}}">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const sanitizer: DomSanitizer = getTestBed().get(DomSanitizer);
let e = fixture.debugElement.children[0].nativeElement;
let trusted = sanitizer.bypassSecurityTrustUrl('bar/baz');
let ci = fixture.debugElement.componentInstance;
ci.ctxProp = trusted;
fixture.detectChanges();
expect(getDOM().getProperty(e, 'href')).toMatch(/SafeValue(%20| )must(%20| )use/);
});
});
describe('sanitizing', () => {
it('should escape unsafe attributes', () => {
const template = `<a [href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
let e = fixture.debugElement.children[0].nativeElement;
let ci = fixture.debugElement.componentInstance;
ci.ctxProp = 'hello';
fixture.detectChanges();
// In the browser, reading href returns an absolute URL. On the server side,
// it just echoes back the property.
expect(getDOM().getProperty(e, 'href')).toMatch(/.*\/?hello$/);
ci.ctxProp = 'javascript:alert(1)';
fixture.detectChanges();
expect(getDOM().getProperty(e, 'href')).toEqual('unsafe:javascript:alert(1)');
});
it('should escape unsafe style values', () => {
const template = `<div [style.background]="ctxProp">Text</div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
let e = fixture.debugElement.children[0].nativeElement;
let ci = fixture.debugElement.componentInstance;
// Make sure binding harmless values works.
ci.ctxProp = 'red';
fixture.detectChanges();
// In some browsers, this will contain the full background specification, not just
// the color.
expect(getDOM().getStyle(e, 'background')).toMatch(/red.*/);
ci.ctxProp = 'url(javascript:evil())';
fixture.detectChanges();
// Updated value gets rejected, no value change.
expect(getDOM().getStyle(e, 'background')).not.toContain('javascript');
});
it('should escape unsafe SVG attributes', () => {
const template = `<svg:circle [xlink:href]="ctxProp">Text</svg:circle>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
try {
TestBed.createComponent(SecuredComponent);
throw 'Should throw';
} catch (e) {
expect(e.message).toContain(`Can't bind to 'xlink:href'`);
}
});
it('should escape unsafe HTML values', () => {
const template = `<div [innerHTML]="ctxProp">Text</div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
let e = fixture.debugElement.children[0].nativeElement;
let ci = fixture.debugElement.componentInstance;
// Make sure binding harmless values works.
ci.ctxProp = 'some <p>text</p>';
fixture.detectChanges();
expect(getDOM().getInnerHTML(e)).toEqual('some <p>text</p>');
ci.ctxProp = 'ha <script>evil()</script>';
fixture.detectChanges();
expect(getDOM().getInnerHTML(e)).toEqual('ha evil()');
ci.ctxProp = 'also <img src="x" onerror="evil()"> evil';
fixture.detectChanges();
expect(getDOM().getInnerHTML(e)).toEqual('also <img src="x"> evil');
ci.ctxProp = 'also <iframe srcdoc="evil"></iframe> evil';
fixture.detectChanges();
expect(getDOM().getInnerHTML(e)).toEqual('also evil');
});
});
});
}
| modules/@angular/core/test/linker/security_integration_spec.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017796338943298906,
0.00017405238759238273,
0.0001694441889412701,
0.0001741870364639908,
0.000002487265419404139
]
|
{
"id": 3,
"code_window": [
" if (exportName === undefined) {\n",
" exportName = 'default';\n",
" factoryClassSuffix = '';\n",
" }\n",
"\n",
" return this._system()\n",
" .import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n",
" .then((module: any) => module[exportName + factoryClassSuffix])\n",
" .then((factory: any) => checkNotEmpty(factory, module, exportName));\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 84
} | /**
* @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 {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
function mockSystem(module: string, contents: any) {
return {
'import': (target: string) => {
expect(target).toBe(module);
return Promise.resolve(contents);
}
};
}
export function main() {
describe('SystemJsNgModuleLoader', () => {
it('loads a default factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});
loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
}));
it('loads a named factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () =>
mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
it('loads a named factory with a configured prefix and suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler(), {
factoryPathPrefix: 'prefixed/',
factoryPathSuffix: '/suffixed',
});
loader._system = () =>
mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
});
};
| modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00250231078825891,
0.0007263399893417954,
0.00016932756989262998,
0.00018797711527440697,
0.0009028467466123402
]
|
{
"id": 3,
"code_window": [
" if (exportName === undefined) {\n",
" exportName = 'default';\n",
" factoryClassSuffix = '';\n",
" }\n",
"\n",
" return this._system()\n",
" .import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n",
" .then((module: any) => module[exportName + factoryClassSuffix])\n",
" .then((factory: any) => checkNotEmpty(factory, module, exportName));\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 84
} | /**
* @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 {Injectable} from '@angular/core/src/di';
import {Testability} from '@angular/core/src/testability/testability';
import {NgZone} from '@angular/core/src/zone/ng_zone';
import {AsyncTestCompleter, SpyObject, beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {EventEmitter} from '../../src/facade/async';
import {normalizeBlank, scheduleMicroTask} from '../../src/facade/lang';
// Schedules a microtasks (using a resolved promise .then())
function microTask(fn: Function): void {
scheduleMicroTask(() => {
// We do double dispatch so that we can wait for scheduleMicrotask in the Testability when
// NgZone becomes stable.
scheduleMicroTask(fn);
});
}
@Injectable()
class MockNgZone extends NgZone {
/** @internal */
_onUnstableStream: EventEmitter<any>;
get onUnstable() { return this._onUnstableStream; }
/** @internal */
_onStableStream: EventEmitter<any>;
get onStable() { return this._onStableStream; }
constructor() {
super({enableLongStackTrace: false});
this._onUnstableStream = new EventEmitter(false);
this._onStableStream = new EventEmitter(false);
}
unstable(): void { this._onUnstableStream.emit(null); }
stable(): void { this._onStableStream.emit(null); }
}
export function main() {
describe('Testability', () => {
var testability: Testability;
var execute: any;
var execute2: any;
var ngZone: MockNgZone;
beforeEach(() => {
ngZone = new MockNgZone();
testability = new Testability(ngZone);
execute = new SpyObject().spy('execute');
execute2 = new SpyObject().spy('execute');
});
describe('Pending count logic', () => {
it('should start with a pending count of 0',
() => { expect(testability.getPendingRequestCount()).toEqual(0); });
it('should fire whenstable callbacks if pending count is 0',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
testability.whenStable(execute);
microTask(() => {
expect(execute).toHaveBeenCalled();
async.done();
});
}));
it('should not fire whenstable callbacks synchronously if pending count is 0', () => {
testability.whenStable(execute);
expect(execute).not.toHaveBeenCalled();
});
it('should not call whenstable callbacks when there are pending counts',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
testability.increasePendingRequestCount();
testability.increasePendingRequestCount();
testability.whenStable(execute);
microTask(() => {
expect(execute).not.toHaveBeenCalled();
testability.decreasePendingRequestCount();
microTask(() => {
expect(execute).not.toHaveBeenCalled();
async.done();
});
});
}));
it('should fire whenstable callbacks when pending drops to 0',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
testability.increasePendingRequestCount();
testability.whenStable(execute);
microTask(() => {
expect(execute).not.toHaveBeenCalled();
testability.decreasePendingRequestCount();
microTask(() => {
expect(execute).toHaveBeenCalled();
async.done();
});
});
}));
it('should not fire whenstable callbacks synchronously when pending drops to 0', () => {
testability.increasePendingRequestCount();
testability.whenStable(execute);
testability.decreasePendingRequestCount();
expect(execute).not.toHaveBeenCalled();
});
it('should fire whenstable callbacks with didWork if pending count is 0',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
testability.whenStable(execute);
microTask(() => {
expect(execute).toHaveBeenCalledWith(false);
async.done();
});
}));
it('should fire whenstable callbacks with didWork when pending drops to 0',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
testability.increasePendingRequestCount();
testability.whenStable(execute);
microTask(() => {
testability.decreasePendingRequestCount();
microTask(() => {
expect(execute).toHaveBeenCalledWith(true);
testability.whenStable(execute2);
microTask(() => {
expect(execute2).toHaveBeenCalledWith(false);
async.done();
});
});
});
}));
});
describe('NgZone callback logic', () => {
it('should fire whenstable callback if event is already finished',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ngZone.unstable();
ngZone.stable();
testability.whenStable(execute);
microTask(() => {
expect(execute).toHaveBeenCalled();
async.done();
});
}));
it('should not fire whenstable callbacks synchronously if event is already finished', () => {
ngZone.unstable();
ngZone.stable();
testability.whenStable(execute);
expect(execute).not.toHaveBeenCalled();
});
it('should fire whenstable callback when event finishes',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ngZone.unstable();
testability.whenStable(execute);
microTask(() => {
expect(execute).not.toHaveBeenCalled();
ngZone.stable();
microTask(() => {
expect(execute).toHaveBeenCalled();
async.done();
});
});
}));
it('should not fire whenstable callbacks synchronously when event finishes', () => {
ngZone.unstable();
testability.whenStable(execute);
ngZone.stable();
expect(execute).not.toHaveBeenCalled();
});
it('should not fire whenstable callback when event did not finish',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ngZone.unstable();
testability.increasePendingRequestCount();
testability.whenStable(execute);
microTask(() => {
expect(execute).not.toHaveBeenCalled();
testability.decreasePendingRequestCount();
microTask(() => {
expect(execute).not.toHaveBeenCalled();
ngZone.stable();
microTask(() => {
expect(execute).toHaveBeenCalled();
async.done();
});
});
});
}));
it('should not fire whenstable callback when there are pending counts',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ngZone.unstable();
testability.increasePendingRequestCount();
testability.increasePendingRequestCount();
testability.whenStable(execute);
microTask(() => {
expect(execute).not.toHaveBeenCalled();
ngZone.stable();
microTask(() => {
expect(execute).not.toHaveBeenCalled();
testability.decreasePendingRequestCount();
microTask(() => {
expect(execute).not.toHaveBeenCalled();
testability.decreasePendingRequestCount();
microTask(() => {
expect(execute).toHaveBeenCalled();
async.done();
});
});
});
});
}));
it('should fire whenstable callback with didWork if event is already finished',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ngZone.unstable();
ngZone.stable();
testability.whenStable(execute);
microTask(() => {
expect(execute).toHaveBeenCalledWith(true);
testability.whenStable(execute2);
microTask(() => {
expect(execute2).toHaveBeenCalledWith(false);
async.done();
});
});
}));
it('should fire whenstable callback with didwork when event finishes',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
ngZone.unstable();
testability.whenStable(execute);
microTask(() => {
ngZone.stable();
microTask(() => {
expect(execute).toHaveBeenCalledWith(true);
testability.whenStable(execute2);
microTask(() => {
expect(execute2).toHaveBeenCalledWith(false);
async.done();
});
});
});
}));
});
});
}
| modules/@angular/core/test/testability/testability_spec.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.0001786862121662125,
0.00017604885215405375,
0.00017201004084199667,
0.00017611194925848395,
0.0000016077532336566946
]
|
{
"id": 3,
"code_window": [
" if (exportName === undefined) {\n",
" exportName = 'default';\n",
" factoryClassSuffix = '';\n",
" }\n",
"\n",
" return this._system()\n",
" .import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n",
" .then((module: any) => module[exportName + factoryClassSuffix])\n",
" .then((factory: any) => checkNotEmpty(factory, module, exportName));\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 84
} | /**
* @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 {platformBrowser} from '@angular/platform-browser';
import {BasicComp} from './basic';
import {MainModuleNgFactory} from './module.ngfactory';
MainModuleNgFactory.create(null).instance.appRef.bootstrap(BasicComp);
| modules/@angular/compiler-cli/integrationtest/src/bootstrap.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017444916011299938,
0.00017185762408189476,
0.0001692660734988749,
0.00017185762408189476,
0.0000025915433070622385
]
|
{
"id": 3,
"code_window": [
" if (exportName === undefined) {\n",
" exportName = 'default';\n",
" factoryClassSuffix = '';\n",
" }\n",
"\n",
" return this._system()\n",
" .import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n",
" .then((module: any) => module[exportName + factoryClassSuffix])\n",
" .then((factory: any) => checkNotEmpty(factory, module, exportName));\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return System.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)\n"
],
"file_path": "modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts",
"type": "replace",
"edit_start_line_idx": 84
} | /**
* @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 {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {isPresent, isString} from '../src/facade/lang';
import {BaseRequestOptions, RequestOptions} from './base_request_options';
import {RequestMethod} from './enums';
import {ConnectionBackend, RequestOptionsArgs} from './interfaces';
import {Request} from './static_request';
import {Response} from './static_response';
import {URLSearchParams} from './url_search_params';
function httpRequest(backend: ConnectionBackend, request: Request): Observable<Response> {
return backend.createConnection(request).response;
}
function mergeOptions(
defaultOpts: BaseRequestOptions, providedOpts: RequestOptionsArgs, method: RequestMethod,
url: string): RequestOptions {
var newOptions = defaultOpts;
if (isPresent(providedOpts)) {
// Hack so Dart can used named parameters
return newOptions.merge(new RequestOptions({
method: providedOpts.method || method,
url: providedOpts.url || url,
search: providedOpts.search,
headers: providedOpts.headers,
body: providedOpts.body,
withCredentials: providedOpts.withCredentials,
responseType: providedOpts.responseType
}));
}
if (isPresent(method)) {
return newOptions.merge(new RequestOptions({method: method, url: url}));
} else {
return newOptions.merge(new RequestOptions({url: url}));
}
}
/**
* Performs http requests using `XMLHttpRequest` as the default backend.
*
* `Http` is available as an injectable class, with methods to perform http requests. Calling
* `request` returns an `Observable` which will emit a single {@link Response} when a
* response is received.
*
* ### Example
*
* ```typescript
* import {Http, HTTP_PROVIDERS} from '@angular/http';
* import 'rxjs/add/operator/map'
* @Component({
* selector: 'http-app',
* viewProviders: [HTTP_PROVIDERS],
* templateUrl: 'people.html'
* })
* class PeopleComponent {
* constructor(http: Http) {
* http.get('people.json')
* // Call map on the response observable to get the parsed people object
* .map(res => res.json())
* // Subscribe to the observable to get the parsed people object and attach it to the
* // component
* .subscribe(people => this.people = people);
* }
* }
* ```
*
*
* ### Example
*
* ```
* http.get('people.json').subscribe((res:Response) => this.people = res.json());
* ```
*
* The default construct used to perform requests, `XMLHttpRequest`, is abstracted as a "Backend" (
* {@link XHRBackend} in this case), which could be mocked with dependency injection by replacing
* the {@link XHRBackend} provider, as in the following example:
*
* ### Example
*
* ```typescript
* import {BaseRequestOptions, Http} from '@angular/http';
* import {MockBackend} from '@angular/http/testing';
* var injector = Injector.resolveAndCreate([
* BaseRequestOptions,
* MockBackend,
* {provide: Http, useFactory:
* function(backend, defaultOptions) {
* return new Http(backend, defaultOptions);
* },
* deps: [MockBackend, BaseRequestOptions]}
* ]);
* var http = injector.get(Http);
* http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));
* ```
*
* @experimental
*/
@Injectable()
export class Http {
constructor(protected _backend: ConnectionBackend, protected _defaultOptions: RequestOptions) {}
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
var responseObservable: any;
if (isString(url)) {
responseObservable = httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url)));
} else if (url instanceof Request) {
responseObservable = httpRequest(this._backend, url);
} else {
throw new Error('First argument must be a url string or Request instance.');
}
return responseObservable;
}
/**
* Performs a request with `get` http method.
*/
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, url)));
}
/**
* Performs a request with `post` http method.
*/
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend, new Request(mergeOptions(
this._defaultOptions.merge(new RequestOptions({body: body})), options,
RequestMethod.Post, url)));
}
/**
* Performs a request with `put` http method.
*/
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend, new Request(mergeOptions(
this._defaultOptions.merge(new RequestOptions({body: body})), options,
RequestMethod.Put, url)));
}
/**
* Performs a request with `delete` http method.
*/
delete (url: string, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Delete, url)));
}
/**
* Performs a request with `patch` http method.
*/
patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend, new Request(mergeOptions(
this._defaultOptions.merge(new RequestOptions({body: body})), options,
RequestMethod.Patch, url)));
}
/**
* Performs a request with `head` http method.
*/
head(url: string, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Head, url)));
}
/**
* Performs a request with `options` http method.
*/
options(url: string, options?: RequestOptionsArgs): Observable<Response> {
return httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Options, url)));
}
}
/**
* @experimental
*/
@Injectable()
export class Jsonp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*
* @security Regular XHR is the safest alternative to JSONP for most applications, and is
* supported by all current browsers. Because JSONP creates a `<script>` element with
* contents retrieved from a remote source, attacker-controlled data introduced by an untrusted
* source could expose your application to XSS risks. Data exposed by JSONP may also be
* readable by malicious third-party websites. In addition, JSONP introduces potential risk for
* future security issues (e.g. content sniffing). For more detail, see the
* [Security Guide](http://g.co/ng/security).
*/
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
var responseObservable: any;
if (isString(url)) {
url =
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url));
}
if (url instanceof Request) {
if (url.method !== RequestMethod.Get) {
throw new Error('JSONP requests must use GET request method.');
}
responseObservable = httpRequest(this._backend, url);
} else {
throw new Error('First argument must be a url string or Request instance.');
}
return responseObservable;
}
}
| modules/@angular/http/src/http.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00018988916417583823,
0.00016974832396954298,
0.00016007806698326021,
0.0001706178009044379,
0.0000063682582549517974
]
|
{
"id": 4,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"import {global} from '@angular/common/src/facade/lang';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | /**
* @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 {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
function mockSystem(module: string, contents: any) {
return {
'import': (target: string) => {
expect(target).toBe(module);
return Promise.resolve(contents);
}
};
}
export function main() {
describe('SystemJsNgModuleLoader', () => {
it('loads a default factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});
loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
}));
it('loads a named factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () =>
mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
it('loads a named factory with a configured prefix and suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler(), {
factoryPathPrefix: 'prefixed/',
factoryPathSuffix: '/suffixed',
});
loader._system = () =>
mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
});
};
| modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.002091646660119295,
0.0006149954861029983,
0.00016592371684964746,
0.0002539301640354097,
0.0007427081000059843
]
|
{
"id": 4,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"import {global} from '@angular/common/src/facade/lang';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | 'use strict';
describe('router', function () {
var elt, testMod;
beforeEach(function () {
testMod = angular.module('testMod', ['ngComponentRouter'])
.value('$routerRootComponent', 'app');
});
it('should work with a provided root component', function() {
registerComponent('homeCmp', {
template: 'Home'
});
registerComponent('app', {
template: '<div ng-outlet></div>',
$routeConfig: [
{ path: '/', component: 'homeCmp' }
]
});
module('testMod');
compileApp();
inject(function($location, $rootScope) {
$location.path('/');
$rootScope.$digest();
expect(elt.text()).toBe('Home');
});
});
it('should bind the component to the current router', function() {
var router;
registerComponent('homeCmp', {
providers: { $router: '=' },
controller: function($scope, $element) {
this.$routerOnActivate = function() {
router = this.$router;
};
},
template: 'Home'
});
registerComponent('app', {
template: '<div ng-outlet></div>',
$routeConfig: [
{ path: '/', component: 'homeCmp' }
]
});
module('testMod');
compileApp();
inject(function($location, $rootScope) {
$location.path('/');
$rootScope.$digest();
var homeElement = elt.find('home-cmp');
expect(homeElement.text()).toBe('Home');
expect(homeElement.isolateScope().$ctrl.$router).toBeDefined();
expect(router).toBeDefined();
})
});
it('should work when an async route is provided route data', function() {
registerComponent('homeCmp', {
template: 'Home ({{$ctrl.isAdmin}})',
$routerOnActivate: function(next, prev) {
this.isAdmin = next.routeData.data.isAdmin;
}
});
registerComponent('app', {
template: '<div ng-outlet></div>',
$routeConfig: [
{ path: '/', loader: function($q) { return $q.when('homeCmp'); }, data: { isAdmin: true } }
]
});
module('testMod');
compileApp();
inject(function($location, $rootScope) {
$location.path('/');
$rootScope.$digest();
expect(elt.text()).toBe('Home (true)');
});
});
it('should work with a templateUrl component', function() {
var $routerOnActivate = jasmine.createSpy('$routerOnActivate');
registerComponent('homeCmp', {
templateUrl: 'homeCmp.html',
$routerOnActivate: $routerOnActivate
});
registerComponent('app', {
template: '<div ng-outlet></div>',
$routeConfig: [
{ path: '/', component: 'homeCmp' }
]
});
module('testMod');
inject(function($location, $rootScope, $httpBackend) {
$httpBackend.expectGET('homeCmp.html').respond('Home');
compileApp();
$location.path('/');
$rootScope.$digest();
$httpBackend.flush();
var homeElement = elt.find('home-cmp');
expect(homeElement.text()).toBe('Home');
expect($routerOnActivate).toHaveBeenCalled();
})
});
it('should provide the current instruction', function() {
registerComponent('homeCmp', {
template: 'Home ({{homeCmp.isAdmin}})'
});
registerComponent('app', {
template: '<div ng-outlet></div>',
$routeConfig: [
{ path: '/', component: 'homeCmp', name: 'Home' }
]
});
module('testMod');
inject(function($rootScope, $rootRouter, $location) {
compileApp();
$location.path('/');
$rootScope.$digest();
var instruction = $rootRouter.generate(['/Home']);
expect($rootRouter.currentInstruction).toEqual(instruction);
});
});
it('should provide the root level router', function() {
registerComponent('homeCmp', {
template: 'Home ({{homeCmp.isAdmin}})',
providers: {
$router: '<'
}
});
registerComponent('app', {
template: '<div ng-outlet></div>',
$routeConfig: [
{ path: '/', component: 'homeCmp', name: 'Home' }
]
});
module('testMod');
inject(function($rootScope, $rootRouter, $location) {
compileApp();
$location.path('/');
$rootScope.$digest();
var homeElement = elt.find('home-cmp');
expect(homeElement.isolateScope().$ctrl.$router.root).toEqual($rootRouter);
});
});
function registerComponent(name, options) {
var definition = {
providers: options.providers,
controller: getController(options)
};
if (options.template) definition.template = options.template;
if (options.templateUrl) definition.templateUrl = options.templateUrl;
applyStaticProperties(definition.controller, options);
angular.module('testMod').component(name, definition);
}
function compileApp() {
inject(function($compile, $rootScope) {
elt = $compile('<div><app></app</div>')($rootScope);
$rootScope.$digest();
});
return elt;
}
function getController(options) {
var controller = options.controller || function () {};
[
'$routerOnActivate', '$routerOnDeactivate',
'$routerOnReuse', '$routerCanReuse',
'$routerCanDeactivate'
].forEach(function (hookName) {
if (options[hookName]) {
controller.prototype[hookName] = options[hookName];
}
});
return controller;
}
function applyStaticProperties(target, options) {
['$canActivate', '$routeConfig'].forEach(function(property) {
if (options[property]) {
target[property] = options[property];
}
});
}
});
| modules/angular1_router/test/integration/router_spec.js | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017865315021481365,
0.00017490317986812443,
0.0001714078534860164,
0.00017476924404036254,
0.0000019578906176320743
]
|
{
"id": 4,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"import {global} from '@angular/common/src/facade/lang';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | {
"name": "@angular/platform-webworker-dynamic",
"version": "0.0.0-PLACEHOLDER",
"description": "Angular 2 platform-webworker-dynamic",
"main": "bundles/platform-webworker-dynamic.umd.js",
"module": "index.js",
"typings": "index.d.ts",
"author": "angular",
"license": "MIT",
"peerDependencies": {
"@angular/core": "0.0.0-PLACEHOLDER",
"@angular/compiler": "0.0.0-PLACEHOLDER",
"@angular/platform-browser": "0.0.0-PLACEHOLDER",
"@angular/platform-webworker": "0.0.0-PLACEHOLDER"
},
"repository": {
"type": "git",
"url": "https://github.com/angular/angular.git"
}
}
| modules/@angular/platform-webworker-dynamic/package.json | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.0001782007748261094,
0.0001725768088363111,
0.0001686381147010252,
0.00017089152242988348,
0.000004081768111063866
]
|
{
"id": 4,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"import {global} from '@angular/common/src/facade/lang';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "add",
"edit_start_line_idx": 8
} | #!/usr/bin/env bash
set -ex -o pipefail
cd `dirname $0`
cd ../..
export NODE_PATH=${NODE_PATH}:$(pwd)/dist-packages/
DEST_DIR=./dist/trees-shaking-test
rm -rf ${DEST_DIR}
for PACKAGE in \
core \
compiler \
common \
platform-browser \
platform-server \
http \
router \
upgrade
do
echo "======= Tree-shaking TEST: ${SRCDIR} ====="
TEST_DIR=${DEST_DIR}/${PACKAGE}
TEST_ENTRY_POINT=${TEST_DIR}/test.js
mkdir -p ${TEST_DIR}
cp ./tools/tree-shaking-test/rollup.config.js ${TEST_DIR}/
echo "import * as x from '@angular/${PACKAGE}'" > ${TEST_ENTRY_POINT}
(
cd ${TEST_DIR}
$(npm bin)/rollup --config rollup.config.js --output ${PACKAGE}.bundle.js
)
done
| tools/tree-shaking-test/test.sh | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00028541451320052147,
0.0002018048253376037,
0.00017008520080707967,
0.00017585980822332203,
0.000048336303734686226
]
|
{
"id": 5,
"code_window": [
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n",
"import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"import {afterEach, beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /**
* @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 {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
function mockSystem(module: string, contents: any) {
return {
'import': (target: string) => {
expect(target).toBe(module);
return Promise.resolve(contents);
}
};
}
export function main() {
describe('SystemJsNgModuleLoader', () => {
it('loads a default factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});
loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
}));
it('loads a named factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () =>
mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
it('loads a named factory with a configured prefix and suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler(), {
factoryPathPrefix: 'prefixed/',
factoryPathSuffix: '/suffixed',
});
loader._system = () =>
mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
});
};
| modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.014374388381838799,
0.006143626756966114,
0.0001737797720124945,
0.0021155946888029575,
0.0063091786578297615
]
|
{
"id": 5,
"code_window": [
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n",
"import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"import {afterEach, beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /**
* @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 {CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata, CompileTypeMetadata} from '@angular/compiler/src/compile_metadata';
import {CompilerConfig} from '@angular/compiler/src/config';
import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
import {ResourceLoader} from '@angular/compiler/src/resource_loader';
import {MockResourceLoader} from '@angular/compiler/testing/resource_loader_mock';
import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/testing/test_bindings';
import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {TestBed} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {SpyResourceLoader} from './spies';
export function main() {
describe('DirectiveNormalizer', () => {
var dirType: CompileTypeMetadata;
var dirTypeWithHttpUrl: CompileTypeMetadata;
beforeEach(() => { TestBed.configureCompiler({providers: TEST_COMPILER_PROVIDERS}); });
beforeEach(() => {
dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'});
dirTypeWithHttpUrl =
new CompileTypeMetadata({moduleUrl: 'http://some/module/a.js', name: 'SomeComp'});
});
describe('normalizeDirective', () => {
it('should throw if no template was specified',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
expect(() => normalizer.normalizeDirective(new CompileDirectiveMetadata({
type: dirType,
isComponent: true,
template:
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []})
}))).toThrowError('No template specified for component SomeComp');
}));
});
describe('normalizeTemplateSync', () => {
it('should store the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template = normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: 'a',
templateUrl: null,
styles: [],
styleUrls: []
}));
expect(template.template).toEqual('a');
expect(template.templateUrl).toEqual('package:some/module/a.js');
}));
it('should resolve styles on the annotation against the moduleUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template = normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}));
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should resolve styles in the template against the moduleUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template =
normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '<style>@import test.css</style>',
templateUrl: null,
styles: [],
styleUrls: []
}));
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should use ViewEncapsulation.Emulated by default',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template = normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}));
expect(template.encapsulation).toEqual(ViewEncapsulation.Emulated);
}));
it('should use default encapsulation provided by CompilerConfig',
inject(
[CompilerConfig, DirectiveNormalizer],
(config: CompilerConfig, normalizer: DirectiveNormalizer) => {
config.defaultEncapsulation = ViewEncapsulation.None;
let template =
normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}));
expect(template.encapsulation).toEqual(ViewEncapsulation.None);
}));
});
describe('templateUrl', () => {
it('should load a template from a url that is resolved against moduleUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/sometplurl.html', 'a');
normalizer
.normalizeTemplateAsync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: null,
templateUrl: 'sometplurl.html',
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.template).toEqual('a');
expect(template.templateUrl).toEqual('package:some/module/sometplurl.html');
async.done();
});
resourceLoader.flush();
}));
it('should resolve styles on the annotation against the moduleUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/tpl/sometplurl.html', '');
normalizer
.normalizeTemplateAsync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
async.done();
});
resourceLoader.flush();
}));
it('should resolve styles in the template against the templateUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect(
'package:some/module/tpl/sometplurl.html', '<style>@import test.css</style>');
normalizer
.normalizeTemplateAsync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: []
}))
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']);
async.done();
});
resourceLoader.flush();
}));
});
describe('normalizeExternalStylesheets', () => {
beforeEach(() => {
TestBed.configureCompiler(
{providers: [{provide: ResourceLoader, useClass: SpyResourceLoader}]});
});
it('should load an external stylesheet',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: SpyResourceLoader) => {
programResourceLoaderSpy(resourceLoader, {'package:some/module/test.css': 'a'});
normalizer
.normalizeExternalStylesheets(new CompileTemplateMetadata({
template: '',
templateUrl: '',
styleUrls: ['package:some/module/test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.externalStylesheets.length).toBe(1);
expect(template.externalStylesheets[0]).toEqual(new CompileStylesheetMetadata({
moduleUrl: 'package:some/module/test.css',
styles: ['a'],
styleUrls: []
}));
async.done();
});
}));
it('should load stylesheets referenced by external stylesheets',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: SpyResourceLoader) => {
programResourceLoaderSpy(resourceLoader, {
'package:some/module/test.css': 'a@import "test2.css"',
'package:some/module/test2.css': 'b'
});
normalizer
.normalizeExternalStylesheets(new CompileTemplateMetadata({
template: '',
templateUrl: '',
styleUrls: ['package:some/module/test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.externalStylesheets.length).toBe(2);
expect(template.externalStylesheets[0]).toEqual(new CompileStylesheetMetadata({
moduleUrl: 'package:some/module/test.css',
styles: ['a'],
styleUrls: ['package:some/module/test2.css']
}));
expect(template.externalStylesheets[1]).toEqual(new CompileStylesheetMetadata({
moduleUrl: 'package:some/module/test2.css',
styles: ['b'],
styleUrls: []
}));
async.done();
});
}));
});
describe('caching', () => {
it('should work for templateUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/cmp.html', 'a');
var templateMeta = new CompileTemplateMetadata({
templateUrl: 'cmp.html',
});
Promise
.all([
normalizer.normalizeTemplateAsync(dirType, templateMeta),
normalizer.normalizeTemplateAsync(dirType, templateMeta)
])
.then((templates: CompileTemplateMetadata[]) => {
expect(templates[0].template).toEqual('a');
expect(templates[1].template).toEqual('a');
async.done();
});
resourceLoader.flush();
}));
});
describe('normalizeLoadedTemplate', () => {
it('should store the viewEncapsulationin the result',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var viewEncapsulation = ViewEncapsulation.Native;
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: viewEncapsulation, styles: [], styleUrls: []}),
'', 'package:some/module/');
expect(template.encapsulation).toBe(viewEncapsulation);
}));
it('should keep the template as html',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}), 'a',
'package:some/module/');
expect(template.template).toEqual('a');
}));
it('should collect ngContent',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<ng-content select="a"></ng-content>', 'package:some/module/');
expect(template.ngContentSelectors).toEqual(['a']);
}));
it('should normalize ngContent wildcard selector',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<ng-content></ng-content><ng-content select></ng-content><ng-content select="*"></ng-content>',
'package:some/module/');
expect(template.ngContentSelectors).toEqual(['*', '*', '*']);
}));
it('should collect top level styles in the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<style>a</style>', 'package:some/module/');
expect(template.styles).toEqual(['a']);
}));
it('should collect styles inside in elements',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div><style>a</style></div>', 'package:some/module/');
expect(template.styles).toEqual(['a']);
}));
it('should collect styleUrls in the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<link rel="stylesheet" href="aUrl">', 'package:some/module/');
expect(template.styleUrls).toEqual(['package:some/module/aUrl']);
}));
it('should collect styleUrls in elements',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div><link rel="stylesheet" href="aUrl"></div>', 'package:some/module/');
expect(template.styleUrls).toEqual(['package:some/module/aUrl']);
}));
it('should ignore link elements with non stylesheet rel attribute',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<link href="b" rel="a">', 'package:some/module/');
expect(template.styleUrls).toEqual([]);
}));
it('should ignore link elements with absolute urls but non package: scheme',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<link href="http://some/external.css" rel="stylesheet">', 'package:some/module/');
expect(template.styleUrls).toEqual([]);
}));
it('should extract @import style urls into styleAbsUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: null, styles: ['@import "test.css";'], styleUrls: []}),
'', 'package:some/module/id');
expect(template.styles).toEqual(['']);
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should not resolve relative urls in inline styles',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata({
encapsulation: null,
styles: ['.foo{background-image: url(\'double.jpg\');'],
styleUrls: []
}),
'', 'package:some/module/id');
expect(template.styles).toEqual(['.foo{background-image: url(\'double.jpg\');']);
}));
it('should resolve relative style urls in styleUrls',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: null, styles: [], styleUrls: ['test.css']}),
'', 'package:some/module/id');
expect(template.styles).toEqual([]);
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should resolve relative style urls in styleUrls with http directive url',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirTypeWithHttpUrl, new CompileTemplateMetadata(
{encapsulation: null, styles: [], styleUrls: ['test.css']}),
'', 'http://some/module/id');
expect(template.styles).toEqual([]);
expect(template.styleUrls).toEqual(['http://some/module/test.css']);
}));
it('should normalize ViewEncapsulation.Emulated to ViewEncapsulation.None if there are no styles nor stylesheets',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: ViewEncapsulation.Emulated, styles: [], styleUrls: []}),
'', 'package:some/module/id');
expect(template.encapsulation).toEqual(ViewEncapsulation.None);
}));
it('should ignore ng-content in elements with ngNonBindable',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div ngNonBindable><ng-content select="a"></ng-content></div>',
'package:some/module/');
expect(template.ngContentSelectors).toEqual([]);
}));
it('should still collect <style> in elements with ngNonBindable',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div ngNonBindable><style>div {color:red}</style></div>', 'package:some/module/');
expect(template.styles).toEqual(['div {color:red}']);
}));
});
});
}
function programResourceLoaderSpy(spy: SpyResourceLoader, results: {[key: string]: string}) {
spy.spy('get').andCallFake((url: string): Promise<any> => {
var result = results[url];
if (result) {
return Promise.resolve(result);
} else {
return Promise.reject(`Unknown mock url ${url}`);
}
});
}
| modules/@angular/compiler/test/directive_normalizer_spec.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.004241937771439552,
0.0003612981818150729,
0.00016259851690847427,
0.00016972539015114307,
0.0007067478145472705
]
|
{
"id": 5,
"code_window": [
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n",
"import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"import {afterEach, beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /**
* @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 {MessageBus} from '@angular/platform-webworker/src/web_workers/shared/message_bus';
import {PostMessageBus, PostMessageBusSink, PostMessageBusSource} from '@angular/platform-webworker/src/web_workers/shared/post_message_bus';
/*
* Returns a PostMessageBus thats sink is connected to its own source.
* Useful for testing the sink and source.
*/
export function createConnectedMessageBus(): MessageBus {
var mockPostMessage = new MockPostMessage();
var source = new PostMessageBusSource(<any>mockPostMessage);
var sink = new PostMessageBusSink(mockPostMessage);
return new PostMessageBus(sink, source);
}
class MockPostMessage {
private _listener: EventListener;
addEventListener(type: string, listener: EventListener, useCapture?: boolean): void {
if (type === 'message') {
this._listener = listener;
}
}
postMessage(data: any, transfer?: [ArrayBuffer]): void { this._listener(<any>{data: data}); }
}
| modules/@angular/platform-webworker/test/web_workers/shared/message_bus_util.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00017492438200861216,
0.0001722211018204689,
0.00016912829596549273,
0.00017241589375771582,
0.000002123206058968208
]
|
{
"id": 5,
"code_window": [
"import {Compiler, SystemJsNgModuleLoader} from '@angular/core';\n",
"import {async, tick} from '@angular/core/testing';\n",
"import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"import {afterEach, beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /**
* @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 function setTemplateCache(cache: any /** TODO #9100 */): void {
(<any>window).$templateCache = cache;
}
| modules/@angular/platform-browser-dynamic/test/resource_loader/resource_loader_cache_setter.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.0001781205937732011,
0.00017566001042723656,
0.00017319944163318723,
0.00017566001042723656,
0.000002460576070006937
]
|
{
"id": 6,
"code_window": [
"\n",
"function mockSystem(module: string, contents: any) {\n",
" return {\n",
" 'import': (target: string) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"function mockSystem(modules: {[module: string]: any}) {\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /**
* @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 {Injectable, Optional} from '../di';
import {Compiler} from './compiler';
import {NgModuleFactory} from './ng_module_factory';
import {NgModuleFactoryLoader} from './ng_module_factory_loader';
const _SEPARATOR = '#';
const FACTORY_CLASS_SUFFIX = 'NgFactory';
/**
* Configuration for SystemJsNgModuleLoader.
* token.
*
* @experimental
*/
export abstract class SystemJsNgModuleLoaderConfig {
/**
* Prefix to add when computing the name of the factory module for a given module name.
*/
factoryPathPrefix: string;
/**
* Suffix to add when computing the name of the factory module for a given module name.
*/
factoryPathSuffix: string;
}
const DEFAULT_CONFIG: SystemJsNgModuleLoaderConfig = {
factoryPathPrefix: '',
factoryPathSuffix: '.ngfactory',
};
/**
* NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory
* @experimental
*/
@Injectable()
export class SystemJsNgModuleLoader implements NgModuleFactoryLoader {
private _config: SystemJsNgModuleLoaderConfig;
/**
* @internal
*/
_system: any;
constructor(private _compiler: Compiler, @Optional() config?: SystemJsNgModuleLoaderConfig) {
this._system = () => System;
this._config = config || DEFAULT_CONFIG;
}
load(path: string): Promise<NgModuleFactory<any>> {
const offlineMode = this._compiler instanceof Compiler;
return offlineMode ? this.loadFactory(path) : this.loadAndCompile(path);
}
private loadAndCompile(path: string): Promise<NgModuleFactory<any>> {
let [module, exportName] = path.split(_SEPARATOR);
if (exportName === undefined) exportName = 'default';
return this._system()
.import(module)
.then((module: any) => module[exportName])
.then((type: any) => checkNotEmpty(type, module, exportName))
.then((type: any) => this._compiler.compileModuleAsync(type));
}
private loadFactory(path: string): Promise<NgModuleFactory<any>> {
let [module, exportName] = path.split(_SEPARATOR);
let factoryClassSuffix = FACTORY_CLASS_SUFFIX;
if (exportName === undefined) {
exportName = 'default';
factoryClassSuffix = '';
}
return this._system()
.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)
.then((module: any) => module[exportName + factoryClassSuffix])
.then((factory: any) => checkNotEmpty(factory, module, exportName));
}
}
function checkNotEmpty(value: any, modulePath: string, exportName: string): any {
if (!value) {
throw new Error(`Cannot find '${exportName}' in '${modulePath}'`);
}
return value;
}
| modules/@angular/core/src/linker/system_js_ng_module_factory_loader.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.9895456433296204,
0.2765193581581116,
0.0001696079270914197,
0.0013947396073490381,
0.4234631061553955
]
|
{
"id": 6,
"code_window": [
"\n",
"function mockSystem(module: string, contents: any) {\n",
" return {\n",
" 'import': (target: string) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"function mockSystem(modules: {[module: string]: any}) {\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /**
* @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 {isPresent, scheduleMicroTask} from '../facade/lang';
import {AnimationPlayer, NoOpAnimationPlayer} from './animation_player';
export class AnimationSequencePlayer implements AnimationPlayer {
private _currentIndex: number = 0;
private _activePlayer: AnimationPlayer;
private _onDoneFns: Function[] = [];
private _onStartFns: Function[] = [];
private _finished = false;
private _started: boolean = false;
public parentPlayer: AnimationPlayer = null;
constructor(private _players: AnimationPlayer[]) {
this._players.forEach(player => { player.parentPlayer = this; });
this._onNext(false);
}
private _onNext(start: boolean) {
if (this._finished) return;
if (this._players.length == 0) {
this._activePlayer = new NoOpAnimationPlayer();
scheduleMicroTask(() => this._onFinish());
} else if (this._currentIndex >= this._players.length) {
this._activePlayer = new NoOpAnimationPlayer();
this._onFinish();
} else {
var player = this._players[this._currentIndex++];
player.onDone(() => this._onNext(true));
this._activePlayer = player;
if (start) {
player.play();
}
}
}
private _onFinish() {
if (!this._finished) {
this._finished = true;
if (!isPresent(this.parentPlayer)) {
this.destroy();
}
this._onDoneFns.forEach(fn => fn());
this._onDoneFns = [];
}
}
init(): void { this._players.forEach(player => player.init()); }
onStart(fn: () => void): void { this._onStartFns.push(fn); }
onDone(fn: () => void): void { this._onDoneFns.push(fn); }
hasStarted() { return this._started; }
play(): void {
if (!isPresent(this.parentPlayer)) {
this.init();
}
if (!this.hasStarted()) {
this._onStartFns.forEach(fn => fn());
this._onStartFns = [];
this._started = true;
}
this._activePlayer.play();
}
pause(): void { this._activePlayer.pause(); }
restart(): void {
if (this._players.length > 0) {
this.reset();
this._players[0].restart();
}
}
reset(): void { this._players.forEach(player => player.reset()); }
finish(): void {
this._onFinish();
this._players.forEach(player => player.finish());
}
destroy(): void {
this._onFinish();
this._players.forEach(player => player.destroy());
}
setPosition(p: any /** TODO #9100 */): void { this._players[0].setPosition(p); }
getPosition(): number { return this._players[0].getPosition(); }
}
| modules/@angular/core/src/animation/animation_sequence_player.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00026834028540179133,
0.00018845194426830858,
0.00016993589815683663,
0.00017488334560766816,
0.0000278660863841651
]
|
{
"id": 6,
"code_window": [
"\n",
"function mockSystem(module: string, contents: any) {\n",
" return {\n",
" 'import': (target: string) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"function mockSystem(modules: {[module: string]: any}) {\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /**
* @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 FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
type ProxyZoneSpec = {
setDelegate(delegateSpec: ZoneSpec): void; getDelegate(): ZoneSpec; resetDelegate(): void;
};
const ProxyZoneSpec: {get(): ProxyZoneSpec; assertPresent: () => ProxyZoneSpec} =
(Zone as any)['ProxyZoneSpec'];
let _fakeAsyncTestZoneSpec: any = null;
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @experimental
*/
export function resetFakeAsyncZone() {
_fakeAsyncTestZoneSpec = null;
ProxyZoneSpec.assertPresent().resetDelegate();
}
let _inFakeAsyncCall = false;
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* Can be used to wrap inject() calls.
*
* ## Example
*
* {@example testing/ts/fake_async.ts region='basic'}
*
* @param fn
* @returns {Function} The function wrapped to be executed in the fakeAsync zone
*
* @experimental
*/
export function fakeAsync(fn: Function): (...args: any[]) => any {
return function(...args: any[]) {
const proxyZoneSpec = ProxyZoneSpec.assertPresent();
if (_inFakeAsyncCall) {
throw new Error('fakeAsync() calls can not be nested');
}
_inFakeAsyncCall = true;
try {
if (!_fakeAsyncTestZoneSpec) {
if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
throw new Error('fakeAsync() calls can not be nested');
}
_fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
}
let res: any;
const lastProxyZoneSpec = proxyZoneSpec.getDelegate();
proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
try {
res = fn(...args);
flushMicrotasks();
} finally {
proxyZoneSpec.setDelegate(lastProxyZoneSpec);
}
if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
throw new Error(
`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
`periodic timer(s) still in the queue.`);
}
if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
throw new Error(
`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
}
return res;
} finally {
_inFakeAsyncCall = false;
resetFakeAsyncZone();
}
};
}
function _getFakeAsyncZoneSpec(): any {
if (_fakeAsyncTestZoneSpec == null) {
throw new Error('The code should be running in the fakeAsync zone to call this function');
}
return _fakeAsyncTestZoneSpec;
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* ## Example
*
* {@example testing/ts/fake_async.ts region='basic'}
*
* @experimental
*/
export function tick(millis: number = 0): void {
_getFakeAsyncZoneSpec().tick(millis);
}
/**
* Discard all remaining periodic tasks.
*
* @experimental
*/
export function discardPeriodicTasks(): void {
let zoneSpec = _getFakeAsyncZoneSpec();
let pendingTimers = zoneSpec.pendingPeriodicTimers;
zoneSpec.pendingPeriodicTimers.length = 0;
}
/**
* Flush any pending microtasks.
*
* @experimental
*/
export function flushMicrotasks(): void {
_getFakeAsyncZoneSpec().flushMicrotasks();
}
| modules/@angular/core/testing/fake_async.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.002562951995059848,
0.0006243856623768806,
0.00016623678675387055,
0.00018183016800321639,
0.0008311685523949564
]
|
{
"id": 6,
"code_window": [
"\n",
"function mockSystem(module: string, contents: any) {\n",
" return {\n",
" 'import': (target: string) => {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"function mockSystem(modules: {[module: string]: any}) {\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /**
* @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 {ChangeDetectorRef} from '@angular/core/src/change_detection/change_detector_ref';
import {SpyObject, proxy} from '@angular/core/testing/testing_internal';
export class SpyChangeDetectorRef extends SpyObject {
constructor() {
super(ChangeDetectorRef);
this.spy('markForCheck');
}
}
export class SpyNgControl extends SpyObject {}
export class SpyValueAccessor extends SpyObject { writeValue: any; }
| modules/@angular/forms/test/spies.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.0016270502237603068,
0.0006643366068601608,
0.0001747808128129691,
0.0001911788567667827,
0.0006807742174714804
]
|
{
"id": 7,
"code_window": [
" return {\n",
" 'import': (target: string) => {\n",
" expect(target).toBe(module);\n",
" return Promise.resolve(contents);\n",
" }\n",
" };\n",
"}\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(modules[target]).not.toBe(undefined);\n",
" return Promise.resolve(modules[target]);\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /**
* @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 {Compiler, SystemJsNgModuleLoader} from '@angular/core';
import {async, tick} from '@angular/core/testing';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
function mockSystem(module: string, contents: any) {
return {
'import': (target: string) => {
expect(target).toBe(module);
return Promise.resolve(contents);
}
};
}
export function main() {
describe('SystemJsNgModuleLoader', () => {
it('loads a default factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () => mockSystem('test.ngfactory', {'default': 'test module factory'});
loader.load('test').then(contents => { expect(contents).toBe('test module factory'); });
}));
it('loads a named factory by appending the factory suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler());
loader._system = () =>
mockSystem('test.ngfactory', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
it('loads a named factory with a configured prefix and suffix', async(() => {
let loader = new SystemJsNgModuleLoader(new Compiler(), {
factoryPathPrefix: 'prefixed/',
factoryPathSuffix: '/suffixed',
});
loader._system = () =>
mockSystem('prefixed/test/suffixed', {'NamedNgFactory': 'test module factory'});
loader.load('test#Named').then(contents => {
expect(contents).toBe('test module factory');
});
}));
});
};
| modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts | 1 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.973831057548523,
0.19492343068122864,
0.00016620304086245596,
0.00019146471458952874,
0.38945379853248596
]
|
{
"id": 7,
"code_window": [
" return {\n",
" 'import': (target: string) => {\n",
" expect(target).toBe(module);\n",
" return Promise.resolve(contents);\n",
" }\n",
" };\n",
"}\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(modules[target]).not.toBe(undefined);\n",
" return Promise.resolve(modules[target]);\n"
],
"file_path": "modules/@angular/core/test/linker/system_ng_module_factory_loader_spec.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /**
* @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 {ResourceLoader} from '@angular/compiler';
import {Component} from '@angular/core';
import {TestBed, async, fakeAsync, inject, tick} from '@angular/core/testing';
import {ResourceLoaderImpl} from '../src/resource_loader/resource_loader_impl';
// Components for the tests.
class FancyService {
value: string = 'real value';
getAsyncValue() { return Promise.resolve('async value'); }
getTimeoutValue() {
return new Promise(
(resolve, reject) => { setTimeout(() => { resolve('timeout value'); }, 10); });
}
}
@Component({
selector: 'external-template-comp',
templateUrl: '/base/modules/@angular/platform-browser/test/static_assets/test.html'
})
class ExternalTemplateComp {
}
@Component({selector: 'bad-template-comp', templateUrl: 'non-existant.html'})
class BadTemplateUrl {
}
// Tests for angular2/testing bundle specific to the browser environment.
// For general tests, see test/testing/testing_public_spec.ts.
export function main() {
describe('test APIs for the browser', () => {
describe('using the async helper', () => {
var actuallyDone: boolean;
beforeEach(() => { actuallyDone = false; });
afterEach(() => { expect(actuallyDone).toEqual(true); });
it('should run async tests with ResourceLoaders', async(() => {
var resourceLoader = new ResourceLoaderImpl();
resourceLoader
.get('/base/modules/@angular/platform-browser/test/static_assets/test.html')
.then(() => { actuallyDone = true; });
}),
10000); // Long timeout here because this test makes an actual ResourceLoader.
});
describe('using the test injector with the inject helper', () => {
describe('setting up Providers', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{providers: [{provide: FancyService, useValue: new FancyService()}]});
});
it('provides a real ResourceLoader instance',
inject([ResourceLoader], (resourceLoader: ResourceLoader) => {
expect(resourceLoader instanceof ResourceLoaderImpl).toBeTruthy();
}));
it('should allow the use of fakeAsync',
fakeAsync(inject([FancyService], (service: any /** TODO #9100 */) => {
var value: any /** TODO #9100 */;
service.getAsyncValue().then(function(val: any /** TODO #9100 */) { value = val; });
tick();
expect(value).toEqual('async value');
})));
});
});
describe('errors', () => {
var originalJasmineIt: any;
var patchJasmineIt = () => {
var resolve: (result: any) => void;
var reject: (error: any) => void;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
originalJasmineIt = jasmine.getEnv().it;
jasmine.getEnv().it = (description: string, fn: any /** TODO #9100 */) => {
var done = () => { resolve(null); };
(<any>done).fail = (err: any /** TODO #9100 */) => { reject(err); };
fn(done);
return null;
};
return promise;
};
var restoreJasmineIt = () => { jasmine.getEnv().it = originalJasmineIt; };
it('should fail when an ResourceLoader fails', (done: any /** TODO #9100 */) => {
var itPromise = patchJasmineIt();
it('should fail with an error from a promise', async(() => {
TestBed.configureTestingModule({declarations: [BadTemplateUrl]});
TestBed.compileComponents();
}));
itPromise.then(
() => { done.fail('Expected test to fail, but it did not'); },
(err: any) => {
expect(err.message)
.toEqual('Uncaught (in promise): Failed to load non-existant.html');
done();
});
restoreJasmineIt();
}, 10000);
});
describe('TestBed createComponent', function() {
it('should allow an external templateUrl', async(() => {
TestBed.configureTestingModule({declarations: [ExternalTemplateComp]});
TestBed.compileComponents().then(() => {
let componentFixture = TestBed.createComponent(ExternalTemplateComp);
componentFixture.detectChanges();
expect(componentFixture.debugElement.nativeElement.textContent)
.toEqual('from external template\n');
});
}),
10000); // Long timeout here because this test makes an actual ResourceLoader request, and
// is slow
// on Edge.
});
});
}
| modules/@angular/platform-browser-dynamic/test/testing_public_browser_spec.ts | 0 | https://github.com/angular/angular/commit/d26a82749473803fbcbd735da46736779367521c | [
0.00042699192999862134,
0.0002050199982477352,
0.0001673160877544433,
0.0001729897630866617,
0.0000803568254923448
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.