<commit_before>var exports,console,process$,empty;//IGNORE
function Comparison(x){}//IGNORE
function Entry(a,b){}//IGNORE
function Singleton(x){}//IGNORE
function SequenceBuilder(){}//IGNORE
function String$(f,x){}//IGNORE

var larger = Comparison("larger");
function getLarger() { return larger }
var smaller = Comparison("smaller");
function getSmaller() { return smaller }
var equal = Comparison("equal");
function getEqual() { return equal }

exports.getLarger=getLarger;
exports.getSmaller=getSmaller;
exports.getEqual=getEqual;

//These are operators for handling nulls
function exists(value) {
    return value !== null && value !== undefined;
}
function nonempty(value) {
    return value !== null && value !== undefined && !value.empty;
}

function isOfType(obj, type) {
    if (type && type.t) {
        if (type.t == 'i' || type.t == 'u') {
            return isOfTypes(obj, type);
        }
        if (obj === null) {
            return type.t===Null || type.t===Anything;
        }
        if (obj === undefined || obj.getT$all === undefined) { return false; }
        var typeName = type.t.$$.T$name;
        if (obj.getT$all && typeName in obj.getT$all()) {
            if (type.a && obj.$$targs$$) {
                for (var i=0; i<type.a.length; i++) {
                    if (!extendsType(obj.$$targs$$[i], type.a[i])) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
    return false;
}
function isOfTypes(obj, types) {
    if (obj===null) {
        for (var i=0; i < types.l.length; i++) {
            if(types.l[i].t===Null || types.l[i].t===Anything) return true;
            else if (types.l[i].t==='u') {
                if (isOfTypes(null, types.l[i])) return true;
            }
        }
        return false;
    }
    if (obj === undefined || obj.getT$all === undefined) { return false; }
    var unions = false;
    var inters = true;
    var _ints=false;
    var objTypes = obj.getT$all();
    for (var i = 0; i < types.l.length; i++) {
        var t = types.l[i];
        var partial = isOfType(obj, t);
        if (types.t==='u') {
            unions = partial || unions;
        } else {
            inters = partial && inters;
            _ints=true;
        }
    }
    return _ints ? inters||unions : unions;
}
function extendsType(t1, t2) {
    if (t1.t === 'u' || t1.t === 'i') {
        var unions = false;
        var inters = true;
        var _ints = false;
        for (var i = 0; i < t1.l.length; i++) {
            var partial = extendsType(t1.l[i], t2);
            if (t1.t==='u') {
                unions = partial||unions;
            } else {
                inters = partial&&inters;
                _ints=true;
            }
        }
        return _ints ? inters||unions : unions;
    }
    if (t2.t == 'u' || t2.t == 'i') {
        var unions = false;
        var inters = true;
        var _ints = false;
        for (var i = 0; i < t2.l.length; i++) {
            var partial = extendsType(t1, t2.l[i]);
            if (t2.t==='u') {
                unions = partial||unions;
            } else {
                inters = partial&&inters;
                _ints=true;
            }
        }
        return _ints ? inters||unions : unions;
    }
    for (t in t1.t.$$.T$all) {
        if (t === t2.t.$$.T$name || t === 'ceylon.language::Nothing') {
            return true;
        }
    }
    return false;
}

function className(obj) {
    function _typename(t) {
        if (t.t==='i' || t.t==='u') {
            var _sep = t.t==='i'?'&':'|';
            var ct = '';
            for (var i=0; i < t.l.length; i++) {
                if (i>0) { ct+=_sep; }
                ct += _typename(t.l[i]);
            }
            return String$(ct);
        } else {
            var tn = t.t.$$.T$name;
            if (t.a) {
                tn += '<';
                for (var i = 0; i < t.a.length; i++) {
                    if (i>0) { tn += ','; }
                    tn += _typename(t.a[i]);
                }
                tn += '>';
            }
            return tn;
        }
    }
    if (obj === null) return String$('ceylon.language::Null');
    var tn = obj.getT$name();
    if (obj.$$targs$$) {
        /*tn += '<';
        for (var i=0; i < obj.$$targs$$.length; i++) {
            if (i>0) { tn += ','; }
            tn += _typename(obj.$$targs$$[i]);
        }
        tn += '>';*/
    }
    return String$(tn);
}

function identityHash(obj) {
    return obj.BasicID;
}

function set_type_args(obj, targs) {
    if (obj.$$targs$$ === undefined) {
        obj.$$targs$$=targs;
    } else {
        for (x in targs) {
            obj.$$targs$$[x] = targs[x];
        }
    }
}
function add_type_arg(obj, name, type) {
    if (obj.$$targs$$ === undefined) {
        obj.$$targs$$={};
    }
    obj.$$targs$$[name]=type;
}
function throwexc(msg) {
    throw Exception(msg.getT$all?msg:String$(msg));
}
exports.set_type_args=set_type_args;
exports.add_type_arg=add_type_arg;
exports.exists=exists;
exports.nonempty=nonempty;
exports.isOfType=isOfType;
exports.className=className;
exports.identityHash=identityHash;
exports.throwexc=throwexc;
<commit_msg>Work on ceylon/ceylon-js#188<commit_after>var exports,console,process$,empty;//IGNORE
function Comparison(x){}//IGNORE
function Entry(a,b){}//IGNORE
function Singleton(x){}//IGNORE
function SequenceBuilder(){}//IGNORE
function String$(f,x){}//IGNORE

var larger = Comparison("larger");
function getLarger() { return larger }
var smaller = Comparison("smaller");
function getSmaller() { return smaller }
var equal = Comparison("equal");
function getEqual() { return equal }

exports.getLarger=getLarger;
exports.getSmaller=getSmaller;
exports.getEqual=getEqual;

//These are operators for handling nulls
function exists(value) {
    return value !== null && value !== undefined;
}
function nonempty(value) {
    return value !== null && value !== undefined && !value.empty;
}

function isOfType(obj, type) {
    if (type && type.t) {
        if (type.t == 'i' || type.t == 'u') {
            return isOfTypes(obj, type);
        }
        if (obj === null) {
            return type.t===Null || type.t===Anything;
        }
        if (obj === undefined || obj.getT$all === undefined) { return false; }
        if (type.t.$$.T$name in obj.getT$all()) {
            if (type.a && obj.$$targs$$) {
                for (var i in type.a) {
                    if (!extendsType(obj.$$targs$$[i], type.a[i])) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
    return false;
}
function isOfTypes(obj, types) {
    if (obj===null) {
        for (var i=0; i < types.l.length; i++) {
            if(types.l[i].t===Null || types.l[i].t===Anything) return true;
            else if (types.l[i].t==='u') {
                if (isOfTypes(null, types.l[i])) return true;
            }
        }
        return false;
    }
    if (obj === undefined || obj.getT$all === undefined) { return false; }
    var unions = false;
    var inters = true;
    var _ints=false;
    var objTypes = obj.getT$all();
    for (var i = 0; i < types.l.length; i++) {
        var t = types.l[i];
        var partial = isOfType(obj, t);
        if (types.t==='u') {
            unions = partial || unions;
        } else {
            inters = partial && inters;
            _ints=true;
        }
    }
    return _ints ? inters||unions : unions;
}
function extendsType(t1, t2) {
    if (t1 === undefined) {
        return true;//t2 === undefined;
    } else if (t1 === null) {
        return t2.t === Null;
    }
    if (t1.t === 'u' || t1.t === 'i') {
        if (t1.t==='i')removeSupertypes(t1.l);
        var unions = false;
        var inters = true;
        var _ints = false;
        for (var i = 0; i < t1.l.length; i++) {
            var partial = extendsType(t1.l[i], t2);
            if (t1.t==='u') {
                unions = partial||unions;
            } else {
                inters = partial&&inters;
                _ints=true;
            }
        }
        return _ints ? inters||unions : unions;
    }
    if (t2.t === 'u' || t2.t === 'i') {
        if (t2.t==='i') removeSupertypes(t2.l);
        var unions = false;
        var inters = true;
        var _ints = false;
        for (var i = 0; i < t2.l.length; i++) {
            var partial = extendsType(t1, t2.l[i]);
            if (t2.t==='u') {
                unions = partial||unions;
            } else {
                inters = partial&&inters;
                _ints=true;
            }
        }
        return _ints ? inters||unions : unions;
    }
    for (t in t1.t.$$.T$all) {
        if (t === t2.t.$$.T$name || t === 'ceylon.language::Nothing') {
            return true;
        }
    }
    return false;
}
function removeSupertypes(list) {
    for (var i=0; i < list.length; i++) {
        for (var j=i; i < list.length; i++) {
            if (i!==j) {
                if (extendsType(list[i],list[j])) {
                    list[j]=list[i];
                } else if (extendsType(list[j],list[i])) {
                    list[i]=list[j];
                }
            }
        }
    }
}

function className(obj) {
    function _typename(t) {
        if (t.t==='i' || t.t==='u') {
            var _sep = t.t==='i'?'&':'|';
            var ct = '';
            for (var i=0; i < t.l.length; i++) {
                if (i>0) { ct+=_sep; }
                ct += _typename(t.l[i]);
            }
            return String$(ct);
        } else {
            var tn = t.t.$$.T$name;
            if (t.a) {
                tn += '<';
                for (var i = 0; i < t.a.length; i++) {
                    if (i>0) { tn += ','; }
                    tn += _typename(t.a[i]);
                }
                tn += '>';
            }
            return tn;
        }
    }
    if (obj === null) return String$('ceylon.language::Null');
    var tn = obj.getT$name();
    if (obj.$$targs$$) {
        /*tn += '<';
        for (var i=0; i < obj.$$targs$$.length; i++) {
            if (i>0) { tn += ','; }
            tn += _typename(obj.$$targs$$[i]);
        }
        tn += '>';*/
    }
    return String$(tn);
}

function identityHash(obj) {
    return obj.BasicID;
}

function set_type_args(obj, targs) {
    if (obj.$$targs$$ === undefined) {
        obj.$$targs$$=targs;
    } else {
        for (x in targs) {
            obj.$$targs$$[x] = targs[x];
        }
    }
}
function add_type_arg(obj, name, type) {
    if (obj.$$targs$$ === undefined) {
        obj.$$targs$$={};
    }
    obj.$$targs$$[name]=type;
}
function throwexc(msg) {
    throw Exception(msg.getT$all?msg:String$(msg));
}
exports.set_type_args=set_type_args;
exports.add_type_arg=add_type_arg;
exports.exists=exists;
exports.nonempty=nonempty;
exports.isOfType=isOfType;
exports.className=className;
exports.identityHash=identityHash;
exports.throwexc=throwexc;
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import DropdownSelect from 'src/DropdownSelect';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import Theme from 'src/Theme';

import PropTypeDescTable from '../PropTypeDescTable';
import DropdownSelectDoc from 'assets/propTypes/DropdownSelect.json';

import 'sass/containers/app/modules/fields/DropdownSelectExamples.scss';

export default class DropdownSelectExamples extends Component {

    constructor(props) {

        super(props);

        this.data = ['test0', 'test1', {
            text: 'test2',
            value: 2,
            desc: 'Here is test2.',
            onTouchTap() {
                console.log('test2 selected!');
            }
        }, 'test3', 'test4', 'test5', {
            text: 'test6',
            value: 6,
            desc: 'Here is test6.',
            onTouchTap() {
                console.log('test6 selected!');
            }
        }, 'test7', 'test8', 'test9'];

        this.groupedData = [{
            name: 'socialNetwork',
            children: [{
                iconCls: 'fa fa-facebook',
                text: 'Facebook',
                desc: 'Here is a Facebook Desc.'
            }, {
                iconCls: 'fa fa-twitter',
                text: 'Twitter',
                desc: 'Here is a Twitter Desc.'
            }, {
                iconCls: 'fa fa-google-plus',
                text: 'Google+',
                desc: 'Here is a Google+ Desc.'
            }]
        }, {
            name: 'device',
            children: [{
                iconCls: 'fa fa-android',
                text: 'Android',
                desc: 'Here is a Android Desc.'
            }, {
                iconCls: 'fa fa-apple',
                text: 'Apple',
                desc: 'Here is a Apple Desc.'
            }, {
                iconCls: 'fa fa-windows',
                text: 'Windows',
                desc: 'Here is a Windows Desc.'
            }]
        }];

        this.onChange = this::this.onChange;

    }

    onChange(value) {
        console.log(value);
    }

    render() {

        return (

Dropdown Select

                    Dropdown Select use to store operating elements. Click on the contact
                    and a drop-down menu will appear. You can select from the list and execute the appropriate command.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

Dropdown Select simple example.

                                    <DropdownSelect data={this.data}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="Self defined theme"/>

Set the autoClose property to false,the select list will not close when
                                    choose one item.

                                    <DropdownSelect theme={Theme.PRIMARY}
                                                    data={this.data}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With Filter"/>

Set the filter property to true,the DropdownSelect will have user
                                        search input.

                                    <DropdownSelect data={this.data}
                                                    useFilter={true}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With multi"/>

                                        Set the mod property to DropdownSelect.Mode.CHECKBOX,
                                        the DropdownSelect can be Multiselect.

                                    <DropdownSelect data={this.data}
                                                    autoClose={false}
                                                    mode={DropdownSelect.Mode.CHECKBOX}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With isGrouped"/>

Set the isGrouped property to true,the DropdownSelect will have
                                        group.

                                    <DropdownSelect style={{width: 240}}
                                                    popupStyle={{maxHeight: 300}}
                                                    data={this.groupedData}
                                                    autoClose={false}
                                                    multi={true}
                                                    isGrouped={true}
                                                    onChange={this.onChange}/>

                </Widget>

Properties

                <PropTypeDescTable data={DropdownSelectDoc}/>

        );
    }
};<commit_msg>update DropdownSelect examples<commit_after>import React, {Component} from 'react';

import DropdownSelect from 'src/DropdownSelect';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import Theme from 'src/Theme';

import PropTypeDescTable from '../PropTypeDescTable';
import DropdownSelectDoc from 'assets/propTypes/DropdownSelect.json';

import 'sass/containers/app/modules/fields/DropdownSelectExamples.scss';

export default class DropdownSelectExamples extends Component {

    constructor(props) {

        super(props);

        this.data = ['test0', 'test1', {
            text: 'test2',
            value: 2,
            desc: 'Here is test2.',
            onTouchTap() {
                console.log('test2 selected!');
            }
        }, 'test3', 'test4', 'test5', {
            text: 'test6',
            value: 6,
            desc: 'Here is test6.',
            onTouchTap() {
                console.log('test6 selected!');
            }
        }, 'test7', 'test8', 'test9'];

        this.groupedData = [{
            name: 'socialNetwork',
            children: [{
                iconCls: 'fa fa-facebook',
                text: 'Facebook',
                desc: 'Here is a Facebook Desc.'
            }, {
                iconCls: 'fa fa-twitter',
                text: 'Twitter',
                desc: 'Here is a Twitter Desc.'
            }, {
                iconCls: 'fa fa-google-plus',
                text: 'Google+',
                desc: 'Here is a Google+ Desc.'
            }]
        }, {
            name: 'device',
            children: [{
                iconCls: 'fa fa-android',
                text: 'Android',
                desc: 'Here is a Android Desc.'
            }, {
                iconCls: 'fa fa-apple',
                text: 'Apple',
                desc: 'Here is a Apple Desc.'
            }, {
                iconCls: 'fa fa-windows',
                text: 'Windows',
                desc: 'Here is a Windows Desc.'
            }]
        }];

        this.onChange = this::this.onChange;

    }

    onChange(value) {
        console.log(value);
    }

    render() {

        return (

Dropdown Select

                    Dropdown Select use to store operating elements. Click on the contact
                    and a drop-down menu will appear. You can select from the list and execute the appropriate command.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

Dropdown Select simple example.

                                    <DropdownSelect data={this.data}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="Self defined theme"/>

Set the autoClose property to false,the select list will not close when
                                    choose one item.

                                    <DropdownSelect theme={Theme.PRIMARY}
                                                    data={this.data}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With Filter"/>

Set the filter property to true,the DropdownSelect will have user
                                        search input.

                                    <DropdownSelect data={this.data}
                                                    useFilter={true}
                                                    useSelectAll={true}
                                                    mode={DropdownSelect.Mode.CHECKBOX}
                                                    autoClose={false}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With multi"/>

                                        Set the mod property to DropdownSelect.Mode.CHECKBOX,
                                        the DropdownSelect can be Multiselect.

                                    <DropdownSelect data={this.data}
                                                    autoClose={false}
                                                    mode={DropdownSelect.Mode.CHECKBOX}
                                                    onChange={this.onChange}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With isGrouped"/>

Set the isGrouped property to true,the DropdownSelect will have
                                        group.

                                    <DropdownSelect style={{width: 240}}
                                                    popupStyle={{maxHeight: 300}}
                                                    data={this.groupedData}
                                                    autoClose={false}
                                                    multi={true}
                                                    isGrouped={true}
                                                    onChange={this.onChange}/>

                </Widget>

Properties

                <PropTypeDescTable data={DropdownSelectDoc}/>

        );
    }
};<|endoftext|>


<commit_before>//From a runtime metamodel, get the model definition by following the path into the module's model.
function get_model(mm) {
  var map=mm.mod;
  var path=mm.d;
  for (var i=0; i < path.length; i++) {
    map = map[path[i]];
  }
  return map;
}

function type$meta(x,$$targs$$) {
  if (x === null) {
    return getNothingType$meta$model();
  }
  if (x.$$metamodel$$) {
    //Could be an object (or a callable)
    if (typeof(x.$$metamodel$$)==='function') {
      x.$$metamodel$$=x.$$metamodel$$();
    }
    if (x.$$metamodel$$.$t) //it's an object
      return AppliedValue(undefined,x.$$metamodel$$.$t.t, {Type:x.$$metamodel$$.$t});
  }
  return AppliedClass($$targs$$.Type.t, {Type:$$targs$$.Type, Arguments:{t:Sequential,a:{Element:{t:Anything}}}});
}
type$meta.$$metamodel$$={$ps:[{t:Anything}],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language.meta','type']};
exports.type$meta=type$meta;

function typeLiteral$meta($$targs$$) {
  if ($$targs$$ === undefined || $$targs$$.Type === undefined) {
    throw Exception("Missing type argument 'Type' " + /*require('util').inspect(*/$$targs$$);
  } else if ($$targs$$.Type.$$metamodel$$ == undefined) {
    //closed type
    var t = $$targs$$.Type.t
    if (t === undefined) {
      throw Exception("'Type' argument should be an open or closed type");
    } else if (t === 'u' || t === 'i') {
      return t === 'u' ? applyUnionType($$targs$$.Type) : applyIntersectionType($$targs$$.Type);
    } else if (t.$$metamodel$$ === undefined) {
      throw Exception("JS Interop not supported / incomplete metamodel for " + /*require('util').inspect(*/t);
    } else {
      var mm = t.$$metamodel$$;
      if (typeof(mm)==='function') {
        mm=mm();
        t.$$metamodel$$=mm;
      }
      var mdl = get_model(mm);
      if (mdl['$mt'] === 'cls') {
        return AppliedClass(t,{Type:$$targs$$.Type,Arguments:{t:Sequential,a:{Element:{t:Anything}}}});
      } else if (mdl['$mt'] === 'ifc') {
        return AppliedInterface(t,$$targs$$);
      } else if (mdl['$mt'] === 'mthd') {
        return AppliedFunction(t,{Type:$$targs$$.Type,Arguments:{t:Sequential,a:{Element:{t:Anything}}}});
      } else if (mdl['$mt'] === 'attr' || mdl['$mt'] === 'gttr' || mdl['$mt'] === 'obj') {
        return AppliedValue(undefined,t,{Container:{t:mm.$cont},Type:mm.$t});
      } else {
        console.log("WTF is a metatype " + mdl['$mt'] + " on a closed type???????");
      }
      console.log("typeLiteral<" + t.getT$name() + "> (closed type)");
    }
  } else {
    //open type
    var t = $$targs$$.Type;
    var mm = t.$$metamodel$$;
    if (typeof(mm)==='function') {
      mm=mm();
      t.$$metamodel$$=mm;
    }
    var mdl = get_model(mm);
    //We need the module
    var _mod = getModules$meta().find(mm.mod['$mod-name'],mm.mod['$mod-version']);
    var _pkg = _mod.findPackage(mm.d[0]);
    if (mdl.$mt==='cls' || mdl.$mt==='obj') {
      return OpenClass(_pkg, t);
    } else if (mdl['$mt'] === 'ifc') {
      return OpenInterface(_pkg, t);
    } else if (mdl['$mt'] === 'mthd') {
      return OpenFunction(_pkg, t);
    } else if (mdl['$mt'] === 'attr' || mdl['$mt'] === 'gttr') {
      return OpenValue(_pkg, t);
    } else {
      console.log("WTF is a metatype " + mdl['$mt'] + " on an open type???????");
    }
    console.log("typeLiteral<" + t.getT$name() + "> (open type)");
  }
  throw Exception("typeLiteral UNIMPLEMENTED for " + /*require('util').inspect(*/$$targs$$);
}
typeLiteral$meta.$$metamodel$$={$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language.meta','typeLiteral']};
exports.typeLiteral$meta=typeLiteral$meta;

function pushTypes(list, types) {
  for (var i=0; i<types.length; i++) {
    var t = types[i];
    if (t.t === 'u') {
      list.push(applyUnionType(t, t.l));
    } else if (t.t === 'i') {
      list.push(applyIntersectionType(t, t.l));
    } else {
      list.push(typeLiteral$meta({Type:t}));
    }
  }
  return list;
}

function applyUnionType(ut) { //return AppliedUnionType
  var cases = [];
  pushTypes(cases, ut.l);
  return AppliedUnionType(ut, cases.reifyCeylonType({Absent:{t:Null},Element:{t:Type$meta$model}}), {Union:{t:Anything}});
}
function applyIntersectionType(it) { //return AppliedIntersectionType
  var sats = [];
  pushTypes(sats, it.l);
  return AppliedIntersectionType(it, sats.reifyCeylonType({Absent:{t:Null},Element:{t:Type$meta$model}}), {Union:{t:Anything}});
}
<commit_msg>pass type arguments to AppliedClass/Interface<commit_after>//From a runtime metamodel, get the model definition by following the path into the module's model.
function get_model(mm) {
  var map=mm.mod;
  var path=mm.d;
  for (var i=0; i < path.length; i++) {
    map = map[path[i]];
  }
  return map;
}

function type$meta(x,$$targs$$) {
  if (x === null) {
    return getNothingType$meta$model();
  }
  if (x.$$metamodel$$) {
    //Could be an object (or a callable)
    if (typeof(x.$$metamodel$$)==='function') {
      x.$$metamodel$$=x.$$metamodel$$();
    }
    if (x.$$metamodel$$.$t) //it's an object
      return AppliedValue(undefined,x.$$metamodel$$.$t.t, {Type:x.$$metamodel$$.$t});
  }
  var c=AppliedClass($$targs$$.Type.t, {Type:$$targs$$.Type, Arguments:{t:Sequential,a:{Element:{t:Anything}}}});
  if ($$targs$$.Type.a)c.$targs=$$targs$$.Type.a;
  return c;
}
type$meta.$$metamodel$$={$ps:[{t:Anything}],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language.meta','type']};
exports.type$meta=type$meta;

function typeLiteral$meta($$targs$$) {
  if ($$targs$$ === undefined || $$targs$$.Type === undefined) {
    throw Exception("Missing type argument 'Type' " + /*require('util').inspect(*/$$targs$$);
  } else if ($$targs$$.Type.$$metamodel$$ == undefined) {
    //closed type
    var t = $$targs$$.Type.t
    if (t === undefined) {
      throw Exception("'Type' argument should be an open or closed type");
    } else if (t === 'u' || t === 'i') {
      return t === 'u' ? applyUnionType($$targs$$.Type) : applyIntersectionType($$targs$$.Type);
    } else if (t.$$metamodel$$ === undefined) {
      throw Exception("JS Interop not supported / incomplete metamodel for " + /*require('util').inspect(*/t);
    } else {
      var mm = t.$$metamodel$$;
      if (typeof(mm)==='function') {
        mm=mm();
        t.$$metamodel$$=mm;
      }
      var mdl = get_model(mm);
      if (mdl['$mt'] === 'cls') {
        var r=AppliedClass(t,{Type:$$targs$$.Type,Arguments:{t:Sequential,a:{Element:{t:Anything}}}});
        if ($$targs$$.Type.a)r.$targs=$$targs$$.Type.a;
        return r;
      } else if (mdl['$mt'] === 'ifc') {
        var r=AppliedInterface(t,$$targs$$);
        if ($$targs$$.Type.a)r.$targs=$$targs$$.Type.a;
        return r;
      } else if (mdl['$mt'] === 'mthd') {
        return AppliedFunction(t,{Type:$$targs$$.Type,Arguments:{t:Sequential,a:{Element:{t:Anything}}}});
      } else if (mdl['$mt'] === 'attr' || mdl['$mt'] === 'gttr' || mdl['$mt'] === 'obj') {
        return AppliedValue(undefined,t,{Container:{t:mm.$cont},Type:mm.$t});
      } else {
        console.log("WTF is a metatype " + mdl['$mt'] + " on a closed type???????");
      }
      console.log("typeLiteral<" + t.getT$name() + "> (closed type)");
    }
  } else {
    //open type
    var t = $$targs$$.Type;
    var mm = t.$$metamodel$$;
    if (typeof(mm)==='function') {
      mm=mm();
      t.$$metamodel$$=mm;
    }
    var mdl = get_model(mm);
    //We need the module
    var _mod = getModules$meta().find(mm.mod['$mod-name'],mm.mod['$mod-version']);
    var _pkg = _mod.findPackage(mm.d[0]);
    if (mdl.$mt==='cls' || mdl.$mt==='obj') {
      return OpenClass(_pkg, t);
    } else if (mdl['$mt'] === 'ifc') {
      return OpenInterface(_pkg, t);
    } else if (mdl['$mt'] === 'mthd') {
      return OpenFunction(_pkg, t);
    } else if (mdl['$mt'] === 'attr' || mdl['$mt'] === 'gttr') {
      return OpenValue(_pkg, t);
    } else {
      console.log("WTF is a metatype " + mdl['$mt'] + " on an open type???????");
    }
    console.log("typeLiteral<" + t.getT$name() + "> (open type)");
  }
  throw Exception("typeLiteral UNIMPLEMENTED for " + /*require('util').inspect(*/$$targs$$);
}
typeLiteral$meta.$$metamodel$$={$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language.meta','typeLiteral']};
exports.typeLiteral$meta=typeLiteral$meta;

function pushTypes(list, types) {
  for (var i=0; i<types.length; i++) {
    var t = types[i];
    if (t.t === 'u') {
      list.push(applyUnionType(t, t.l));
    } else if (t.t === 'i') {
      list.push(applyIntersectionType(t, t.l));
    } else {
      list.push(typeLiteral$meta({Type:t}));
    }
  }
  return list;
}

function applyUnionType(ut) { //return AppliedUnionType
  var cases = [];
  pushTypes(cases, ut.l);
  return AppliedUnionType(ut, cases.reifyCeylonType({Absent:{t:Null},Element:{t:Type$meta$model}}), {Union:{t:Anything}});
}
function applyIntersectionType(it) { //return AppliedIntersectionType
  var sats = [];
  pushTypes(sats, it.l);
  return AppliedIntersectionType(it, sats.reifyCeylonType({Absent:{t:Null},Element:{t:Type$meta$model}}), {Union:{t:Anything}});
}
<|endoftext|>


<commit_before>/**
 * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {AmpAdXOriginIframeHandler} from '../amp-ad-xorigin-iframe-handler';
import {BaseElement} from '../../../../src/base-element';
import {Signals} from '../../../../src/utils/signals';
import {ampdocServiceFor} from '../../../../src/ampdoc';
import {
  createIframeWithMessageStub,
  expectPostMessage,
} from '../../../../testing/iframe';
import {AmpAdUIHandler} from '../amp-ad-ui';
import {timerFor} from '../../../../src/timer';
import * as sinon from 'sinon';

describe('amp-ad-xorigin-iframe-handler', () => {
  let sandbox;
  let adImpl;
  let signals;
  let renderStartedSpy;
  let iframeHandler;
  let iframe;
  let testIndex = 0;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    const ampdocService = ampdocServiceFor(window);
    const ampdoc = ampdocService.getAmpDoc();
    const adElement = document.createElement('container-element');
    adElement.getAmpDoc = () => ampdoc;
    adElement.isBuilt = () => {
      return true;
    };
    signals = new Signals();
    adElement.signals = () => signals;
    renderStartedSpy = sandbox.spy();
    adElement.renderStarted = () => {
      renderStartedSpy();
      signals.signal('render-start');
    };
    adImpl = new BaseElement(adElement);
    adImpl.getFallback = () => {
      return null;
    };
    document.body.appendChild(adElement);
    adImpl.uiHandler = new AmpAdUIHandler(adImpl);
    iframeHandler = new AmpAdXOriginIframeHandler(adImpl);
    testIndex++;

    iframe = createIframeWithMessageStub(window);
    iframe.setAttribute('data-amp-3p-sentinel', 'amp3ptest' + testIndex);
    iframe.name = 'test_nomaster';
  });

  afterEach(() => {
    sandbox.restore();
    document.body.removeChild(adImpl.element);
  });

  describe('init() returned promise', () => {
    let initPromise;

    describe('if render-start is implemented', () => {

      let noContentSpy;

      beforeEach(() => {
        adImpl.config = {renderStartImplemented: true};
        sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
          return Promise.resolve({
            success: true,
            newWidth: 114,
            newHeight: 217,
          });
        });
        noContentSpy =
            sandbox.spy/*OK*/(iframeHandler, 'freeXOriginIframe');

        initPromise = iframeHandler.init(iframe);
      });

      it('should resolve on iframe.onload', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        return initPromise.then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.not.be.called;
          expect(signals.get('render-start')).to.be.null;
        });
      });

      it('should resolve on message "render-start"', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'render-start',
        });
        const renderStartPromise = signals.whenSignal('render-start');
        return Promise.all([renderStartPromise, initPromise]).then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.be.calledOnce;
        }).then(() => {
          const message = {
            sentinel: 'amp3ptest' + testIndex,
            type: 'no-content',
          };
          const promise = expectPostMessage(
              iframe.contentWindow, window, message);
          iframe.postMessageToParent(message);
          return promise.then(() => {
            expect(noContentSpy).to.not.been.called;
          });
        });
      });

      it('should resolve and resize on message "render-start" w/ size', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          width: 114,
          height: '217',  // should be tolerant to string number
          type: 'render-start',
          sentinel: 'amp3ptest' + testIndex,
        });
        const expectResponsePromise = iframe.expectMessageFromParent(
            'amp-' + JSON.stringify({
              requestedWidth: 114,
              requestedHeight: 217,
              type: 'embed-size-changed',
              sentinel: 'amp3ptest' + testIndex,
            }));
        const renderStartPromise = signals.whenSignal('render-start');
        return Promise.all([renderStartPromise, initPromise]).then(() => {
          return initPromise;
        }).then(() => {
          expect(iframe.style.visibility).to.equal('');
          return expectResponsePromise;
        });
      });

      it('should resolve on message "no-content" ' +
          'and remove non-master iframe', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'no-content',
        });
        return initPromise.then(() => {
          expect(noContentSpy).to.be.calledWith(false);
          expect(iframeHandler.iframe).to.be.null;
        });
      });

      it('should NOT remove master iframe on message "no-content"', () => {
        iframe.name = 'test_master';
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'no-content',
        });
        return initPromise.then(() => {
          expect(noContentSpy).to.be.calledOnce;
          expect(noContentSpy).to.be.calledWith(true);
        });
      });

      it('should NOT resolve on message "bootstrap-loaded"', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'bootstrap-loaded',
        });

        return expectPostMessage(iframe.contentWindow, window, {
          sentinel: 'amp3ptest' + testIndex,
          type: 'bootstrap-loaded',
        }).then(() => {
          const clock = sandbox.useFakeTimers();
          clock.tick(0);
          const timeoutPromise =
              timerFor(window).timeoutPromise(2000, initPromise);
          clock.tick(2001);
          return expect(timeoutPromise).to.eventually
              .be.rejectedWith(/timeout/);
        });
      });

      it('should not update "ini-load" signal implicitly', () => {
        return initPromise.then(() => {
          expect(signals.get('ini-load')).to.be.null;
        });
      });

      it('should update "ini-load" signal on message', () => {
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'ini-load',
        });
        return initPromise.then(() => {
          expect(signals.get('ini-load')).to.be.ok;
        });
      });
    });

    // TODO(amphtml): Unskip when #8386 is fixed.
    it.skip('should trigger render-start on message "bootstrap-loaded" if' +
       ' render-start is NOT implemented', done => {
      initPromise = iframeHandler.init(iframe);
      iframe.onload = () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'bootstrap-loaded',
        });
        initPromise.then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.be.calledOnce;
          done();
        });
      };
    });

    it('should trigger visibility on timeout', done => {
      const clock = sandbox.useFakeTimers();
      iframe.name = 'test_master';
      initPromise = iframeHandler.init(iframe);
      iframe.onload = () => {
        clock.tick(10000);
        initPromise.then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.not.be.called;
          done();
        });
      };
    });

    it('should resolve directly if it is A4A', () => {
      return iframeHandler.init(iframe, true).then(() => {
        expect(iframe.style.visibility).to.equal('');
        expect(iframe.readyState).to.equal('complete');
      });
    });
  });

  describe('Initialized iframe', () => {

    beforeEach(() => {
      iframeHandler.init(iframe);
    });

    it('should be able to use embed-state API', () => {
      iframe.postMessageToParent({
        type: 'send-embed-state',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        inViewport: false,
        pageHidden: false,
        type: 'embed-state',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });

    it('should be able to use embed-size API, change size deny', () => {
      sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
        return Promise.resolve({
          success: false,
          newWidth: 114,
          newHeight: 217,
        });
      });
      iframe.postMessageToParent({
        width: 114,
        height: 217,
        type: 'embed-size',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        requestedWidth: 114,
        requestedHeight: 217,
        type: 'embed-size-denied',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });

    it('should be able to use embed-size API, change size succeed', () => {
      sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
        return Promise.resolve({
          success: true,
          newWidth: 114,
          newHeight: 217,
        });
      });
      iframe.postMessageToParent({
        width: 114,
        height: '217',  // should be tolerant to string number
        type: 'embed-size',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        requestedWidth: 114,
        requestedHeight: 217,
        type: 'embed-size-changed',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });

    it('should be able to use embed-size API to resize height only', () => {
      sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
        return Promise.resolve({
          success: true,
          newWidth: undefined,
          newHeight: 217,
        });
      });
      iframe.postMessageToParent({
        height: 217,
        type: 'embed-size',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        requestedWidth: undefined,
        requestedHeight: 217,
        type: 'embed-size-changed',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });
  });
});
<commit_msg>Fix flaky amp-ad-xorigin-iframe-handler test (#8363)<commit_after>/**
 * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {AmpAdXOriginIframeHandler} from '../amp-ad-xorigin-iframe-handler';
import {BaseElement} from '../../../../src/base-element';
import {Signals} from '../../../../src/utils/signals';
import {ampdocServiceFor} from '../../../../src/ampdoc';
import {
  createIframeWithMessageStub,
  expectPostMessage,
} from '../../../../testing/iframe';
import {AmpAdUIHandler} from '../amp-ad-ui';
import {timerFor} from '../../../../src/timer';
import * as sinon from 'sinon';

describe('amp-ad-xorigin-iframe-handler', () => {
  let sandbox;
  let adImpl;
  let signals;
  let renderStartedSpy;
  let iframeHandler;
  let iframe;
  let testIndex = 0;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    const ampdocService = ampdocServiceFor(window);
    const ampdoc = ampdocService.getAmpDoc();
    const adElement = document.createElement('container-element');
    adElement.getAmpDoc = () => ampdoc;
    adElement.isBuilt = () => {
      return true;
    };
    signals = new Signals();
    adElement.signals = () => signals;
    renderStartedSpy = sandbox.spy();
    adElement.renderStarted = () => {
      renderStartedSpy();
      signals.signal('render-start');
    };
    adImpl = new BaseElement(adElement);
    adImpl.getFallback = () => {
      return null;
    };
    document.body.appendChild(adElement);
    adImpl.uiHandler = new AmpAdUIHandler(adImpl);
    iframeHandler = new AmpAdXOriginIframeHandler(adImpl);
    testIndex++;

    iframe = createIframeWithMessageStub(window);
    iframe.setAttribute('data-amp-3p-sentinel', 'amp3ptest' + testIndex);
    iframe.name = 'test_nomaster';
  });

  afterEach(() => {
    sandbox.restore();
    document.body.removeChild(adImpl.element);
  });

  describe('init() returned promise', () => {
    let initPromise;

    describe('if render-start is implemented', () => {

      let noContentSpy;

      beforeEach(() => {
        adImpl.config = {renderStartImplemented: true};
        sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
          return Promise.resolve({
            success: true,
            newWidth: 114,
            newHeight: 217,
          });
        });
        noContentSpy =
            sandbox.spy/*OK*/(iframeHandler, 'freeXOriginIframe');

        initPromise = iframeHandler.init(iframe);
      });

      it('should resolve on iframe.onload', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        return initPromise.then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.not.be.called;
          expect(signals.get('render-start')).to.be.null;
        });
      });

      it('should resolve on message "render-start"', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'render-start',
        });
        const renderStartPromise = signals.whenSignal('render-start');
        return Promise.all([renderStartPromise, initPromise]).then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.be.calledOnce;
        }).then(() => {
          const message = {
            sentinel: 'amp3ptest' + testIndex,
            type: 'no-content',
          };
          const promise = expectPostMessage(
              iframe.contentWindow, window, message);
          iframe.postMessageToParent(message);
          return promise.then(() => {
            expect(noContentSpy).to.not.been.called;
          });
        });
      });

      it('should resolve and resize on message "render-start" w/ size', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          width: 114,
          height: '217',  // should be tolerant to string number
          type: 'render-start',
          sentinel: 'amp3ptest' + testIndex,
        });
        const expectResponsePromise = iframe.expectMessageFromParent(
            'amp-' + JSON.stringify({
              requestedWidth: 114,
              requestedHeight: 217,
              type: 'embed-size-changed',
              sentinel: 'amp3ptest' + testIndex,
            }));
        const renderStartPromise = signals.whenSignal('render-start');
        return Promise.all([renderStartPromise, initPromise]).then(() => {
          return initPromise;
        }).then(() => {
          expect(iframe.style.visibility).to.equal('');
          return expectResponsePromise;
        });
      });

      it('should resolve on message "no-content" ' +
          'and remove non-master iframe', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'no-content',
        });
        return initPromise.then(() => {
          expect(noContentSpy).to.be.calledWith(false);
          expect(iframeHandler.iframe).to.be.null;
        });
      });

      it('should NOT remove master iframe on message "no-content"', () => {
        iframe.name = 'test_master';
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'no-content',
        });
        return initPromise.then(() => {
          expect(noContentSpy).to.be.calledOnce;
          expect(noContentSpy).to.be.calledWith(true);
        });
      });

      it('should NOT resolve on message "bootstrap-loaded"', () => {
        expect(iframe.style.visibility).to.equal('hidden');
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'bootstrap-loaded',
        });

        return expectPostMessage(iframe.contentWindow, window, {
          sentinel: 'amp3ptest' + testIndex,
          type: 'bootstrap-loaded',
        }).then(() => {
          const clock = sandbox.useFakeTimers();
          clock.tick(0);
          const timeoutPromise =
              timerFor(window).timeoutPromise(2000, initPromise);
          clock.tick(2001);
          return expect(timeoutPromise).to.eventually
              .be.rejectedWith(/timeout/);
        });
      });

      it('should not update "ini-load" signal implicitly', () => {
        return initPromise.then(() => {
          expect(signals.get('ini-load')).to.be.null;
        });
      });

      it('should update "ini-load" signal on message', () => {
        iframe.postMessageToParent({
          sentinel: 'amp3ptest' + testIndex,
          type: 'ini-load',
        });
        return initPromise.then(() => {
          expect(signals.get('ini-load')).to.be.ok;
        });
      });
    });

    it('should trigger render-start on message "bootstrap-loaded" if' +
       ' render-start is NOT implemented', done => {
      initPromise = iframeHandler.init(iframe);
      iframe.postMessageToParent({
        sentinel: 'amp3ptest' + testIndex,
        type: 'bootstrap-loaded',
      });
      const renderStartPromise = signals.whenSignal('render-start');
      renderStartPromise.then(() => {
        expect(renderStartedSpy).to.be.calledOnce;
        done();
      });
    });

    it('should trigger visibility on timeout', done => {
      const clock = sandbox.useFakeTimers();
      iframe.name = 'test_master';
      initPromise = iframeHandler.init(iframe);
      iframe.onload = () => {
        clock.tick(10000);
        initPromise.then(() => {
          expect(iframe.style.visibility).to.equal('');
          expect(renderStartedSpy).to.not.be.called;
          done();
        });
      };
    });

    it('should resolve directly if it is A4A', () => {
      return iframeHandler.init(iframe, true).then(() => {
        expect(iframe.style.visibility).to.equal('');
        expect(iframe.readyState).to.equal('complete');
      });
    });
  });

  describe('Initialized iframe', () => {

    beforeEach(() => {
      iframeHandler.init(iframe);
    });

    it('should be able to use embed-state API', () => {
      iframe.postMessageToParent({
        type: 'send-embed-state',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        inViewport: false,
        pageHidden: false,
        type: 'embed-state',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });

    it('should be able to use embed-size API, change size deny', () => {
      sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
        return Promise.resolve({
          success: false,
          newWidth: 114,
          newHeight: 217,
        });
      });
      iframe.postMessageToParent({
        width: 114,
        height: 217,
        type: 'embed-size',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        requestedWidth: 114,
        requestedHeight: 217,
        type: 'embed-size-denied',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });

    it('should be able to use embed-size API, change size succeed', () => {
      sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
        return Promise.resolve({
          success: true,
          newWidth: 114,
          newHeight: 217,
        });
      });
      iframe.postMessageToParent({
        width: 114,
        height: '217',  // should be tolerant to string number
        type: 'embed-size',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        requestedWidth: 114,
        requestedHeight: 217,
        type: 'embed-size-changed',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });

    it('should be able to use embed-size API to resize height only', () => {
      sandbox.stub(adImpl.uiHandler, 'updateSize', () => {
        return Promise.resolve({
          success: true,
          newWidth: undefined,
          newHeight: 217,
        });
      });
      iframe.postMessageToParent({
        height: 217,
        type: 'embed-size',
        sentinel: 'amp3ptest' + testIndex,
      });
      return iframe.expectMessageFromParent('amp-' + JSON.stringify({
        requestedWidth: undefined,
        requestedHeight: 217,
        type: 'embed-size-changed',
        sentinel: 'amp3ptest' + testIndex,
      }));
    });
  });
});
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Accounts } from 'meteor/accounts-base';
import { ProcessLauncher } from '../../process_launcher/process_launcher.js';
import '../../single_use_auth/single_use_auth.js';
import { Adventures } from '../adventures.js';
import { AdventureCommands } from '../adventure_commands.js';
import { AdventureStates } from '../adventure_states.js';
import { AdventureSteps } from '../adventure_steps.js';
import { Nodes } from '../../nodes/nodes.js';
import { NodeCheckTypes } from '../../nodes/node_check_types.js';
import { AdventureStatus } from '../adventure_status.js';
import { AdventureStepStatus } from '../adventure_step_status.js';
var childProcess = require("child_process");

// Collections

// Enums

Meteor.methods({
  /**
   * prepareAdventure
   * @param adventureId
   */
  launchAdventure(adventureId) {
    console.debug("launchAdventure:", adventureId);
    if (!adventureId) {
      throw new Meteor.Error("launchAdventure failed: no adventureId specified")
    }

    // Load the adventure Record
    var adventure = Adventures.findOne(adventureId);
    if (!adventure) {
      throw new Meteor.Error("launchAdventure failed: adventure [" + adventureId + "] not found")
    }

    // Queue the adventure
    Adventures.update(adventureId, { $set: { status: AdventureStatus.staged } });
    AdventureSteps.update({ adventureId: adventureId }, { $set: { status: AdventureStepStatus.staged } });

    // Generate the authentication token and launch the process
    var token   = Accounts.singleUseAuth.generate({ expires: { seconds: 5 } }, Meteor.user()),
        command = [ ProcessLauncher.adventureScript, "--adventureId", adventureId, "--token", token ].join(" "),
        logFile = [ "adventure_", adventureId, ".log" ].join(""),
        proc    = ProcessLauncher.launchAutomation(command, logFile, (code) => {
          console.debug("Adventure Exit: " + adventure._id + ", " + code);
          Adventures.update(adventure._id, { $unset: { pid: "" } });
          if (code) {
            Adventures.update(adventure._id, { $set: { status: AdventureStatus.failed } });
          } else {
            Adventures.update({
              _id   : adventure._id,
              status: { $nin: [ AdventureStatus.failed ] }
            }, { $set: { status: AdventureStatus.complete } });
          }
        });

    // Store the PID
    Adventures.update(adventureId, { $set: { pid: proc.pid } });
    console.info("launchAdventure launched: " + adventureId + " as " + proc.pid + " > " + logFile);
  },

  /**
   * abortAdventure
   * @param adventureId
   */
  abortAdventure(adventureId) {
    console.debug("abortAdventure:", adventureId);
    check(adventureId, String);

    var adventure = Adventures.findOne(adventureId);
    if (adventure) {
      Adventures.update({ _id: adventure._id }, { $set: { status: AdventureStatus.complete, abort: true } });

      // give it a few seconds, but make sure the process ends
      if (adventure.pid) {
        Meteor.setTimeout(() => {
          // get the updated record
          adventure = Adventures.findOne(adventureId);

          // check to see if the process has exited
          if (adventure.pid) {
            console.debug("Looks like adventure " + adventure._id + " may still be alive as pid " + adventure.pid);

            // make sure it's dead
            console.debug("Killing adventure " + adventure._id + ", " + adventure.pid);
            childProcess.exec("kill " + adventure.pid, (error, stdout, stderr) => {
              if (error) {
                console.error("Killing adventure failed: ", error);
              } else {
                console.log("Adventure killed:");
                console.log("stdout: ", stdout.toString());
                console.log("stderr: ", stderr.toString());
              }
            });
          } else {
            console.debug("Adventure abort watchdog: adventure " + adventure._id + " looks dead");
          }
        }, 10000);
      } else {
        console.error("Abort Adventure: No PID for adventure " + adventureId);
      }
    } else {
      console.error("Adventure not found: " + adventureId);
    }
  },

  /**
   * pauseAdventure
   * @param adventureId
   */
  pauseAdventure(adventureId) {
    console.debug("pauseAdventure: ", adventureId);
    check(adventureId, String);

    Adventures.update(adventureId, { $set: { status: AdventureStatus.paused } })
  },

  /**
   * Send the adventure status enum to the clients
   * @returns {AdventureStatus|*}
   */
  loadAdventureEnums() {
    return {
      AdventureStatus    : AdventureStatus,
      AdventureStepStatus: AdventureStepStatus,
      NodeCheckTypes     : NodeCheckTypes
    };
  },

  /**
   * Set the status of an adventure
   * @param adventureId
   * @param status
   */
  setAdventureStatus(adventureId, status) {
    console.debug("setAdventureStatus:", adventureId, status);
    check(adventureId, String);
    check(status, Number);

    var adventure = Adventures.findOne({ _id: adventureId });
    Adventures.update({ _id: adventure._id }, { $set: { status: status } });
  },

  /**
   * Store the current state of an adventure
   * @param adventureId
   * @param state
   */
  saveAdventureState(adventureId, state) {
    console.debug("saveAdventureState: " + adventureId);
    check(adventureId, String);
    check(state, Object);
    AdventureStates.upsert({ adventureId: adventureId }, { $set: state });
  },

  /**
   * Set the known location of an adventure
   * @param adventureId
   * @param nodeId
   */
  setAdventureLocation(adventureId, nodeId) {
    console.debug("setAdventureLocation:", adventureId, nodeId);
    check(adventureId, String);
    check(nodeId, String);

    var adventure = Adventures.findOne({ _id: adventureId });
    Adventures.update({ _id: adventure._id }, { $set: { lastKnownNode: nodeId } });
  },

  /**
   * Set the log file path for an adventure
   * @param adventureId
   * @param path
   */
  setAdventureLogFile(adventureId, path) {
    console.debug("setAdventureLogFile:", adventureId, path);
    check(adventureId, String);
    check(path, String);

    Adventures.update({ _id: adventureId }, { $set: { logFile: path } });
  },

  /**
   * Set the status of an adventure step
   * @param stepId
   * @param status
   */
  setAdventureStepStatus(stepId, status) {
    console.debug("setAdventureStepStatus:", stepId, status);
    check(stepId, String);
    check(status, Number);

    var step = AdventureSteps.findOne({ _id: stepId });
    AdventureSteps.update({ _id: step._id }, { $set: { status: status } });
  },

  /**
   * Save a result from an adventure step
   * @param stepId
   * @param result
   */
  saveAdventureStepResult(stepId, result) {
    console.debug("saveAdventureStepResult:", stepId);
    check(stepId, String);
    check(result, Object);

    AdventureSteps.update({ _id: stepId }, { $set: { result: result } });
  },

  /**
   * Set the status of an adventure command
   * @param commandId
   * @param status
   * @param result
   */
  setCommandStatus(commandId, status, result) {
    console.debug("setCommandStatus:", commandId, status);
    check(commandId, String);
    check(status, Number);

    // Load the command
    var command = AdventureCommands.findOne({ _id: commandId });

    // Don't write the result unless it exists to prevent losing an existing result
    if (result) {
      // force the result to an object
      var saveResult = result;
      if (_.isArray(result) || !_.isObject(saveResult)) {
        saveResult = {
          result: result
        };
      }

      AdventureCommands.update({ _id: command._id }, { $set: { status: status, result: saveResult } });
    } else {
      AdventureCommands.update({ _id: command._id }, { $set: { status: status } });
    }
  },

  /**
   * Return a single static record of a node
   * @param staticId
   * @param projectVersionId
   */
  loadNode(staticId, projectVersionId) {
    console.debug("loadNode:", staticId, projectVersionId);
    return Nodes.findOne({ staticId: staticId, projectVersionId: projectVersionId });
  },

  /**
   * Respond to a heartbeat request keeping the DDP connection alive
   */
  heartbeat() {
    return "ACK";
  }
});
<commit_msg>Increased the temporary password time period<commit_after>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Accounts } from 'meteor/accounts-base';
import { ProcessLauncher } from '../../process_launcher/process_launcher.js';
import '../../single_use_auth/single_use_auth.js';
import { Adventures } from '../adventures.js';
import { AdventureCommands } from '../adventure_commands.js';
import { AdventureStates } from '../adventure_states.js';
import { AdventureSteps } from '../adventure_steps.js';
import { Nodes } from '../../nodes/nodes.js';
import { NodeCheckTypes } from '../../nodes/node_check_types.js';
import { AdventureStatus } from '../adventure_status.js';
import { AdventureStepStatus } from '../adventure_step_status.js';
var childProcess = require("child_process");

// Collections

// Enums

Meteor.methods({
  /**
   * prepareAdventure
   * @param adventureId
   */
  launchAdventure(adventureId) {
    console.debug("launchAdventure:", adventureId);
    if (!adventureId) {
      throw new Meteor.Error("launchAdventure failed: no adventureId specified")
    }

    // Load the adventure Record
    var adventure = Adventures.findOne(adventureId);
    if (!adventure) {
      throw new Meteor.Error("launchAdventure failed: adventure [" + adventureId + "] not found")
    }

    // Queue the adventure
    Adventures.update(adventureId, { $set: { status: AdventureStatus.staged } });
    AdventureSteps.update({ adventureId: adventureId }, { $set: { status: AdventureStepStatus.staged } });

    // Generate the authentication token and launch the process
    var token   = Accounts.singleUseAuth.generate({ expires: { seconds: 30 } }, Meteor.user()),
        command = [ ProcessLauncher.adventureScript, "--adventureId", adventureId, "--token", token ].join(" "),
        logFile = [ "adventure_", adventureId, ".log" ].join(""),
        proc    = ProcessLauncher.launchAutomation(command, logFile, (code) => {
          console.debug("Adventure Exit: " + adventure._id + ", " + code);
          Adventures.update(adventure._id, { $unset: { pid: "" } });
          if (code) {
            Adventures.update(adventure._id, { $set: { status: AdventureStatus.failed } });
          } else {
            Adventures.update({
              _id   : adventure._id,
              status: { $nin: [ AdventureStatus.failed ] }
            }, { $set: { status: AdventureStatus.complete } });
          }
        });

    // Store the PID
    Adventures.update(adventureId, { $set: { pid: proc.pid } });
    console.info("launchAdventure launched: " + adventureId + " as " + proc.pid + " > " + logFile);
  },

  /**
   * abortAdventure
   * @param adventureId
   */
  abortAdventure(adventureId) {
    console.debug("abortAdventure:", adventureId);
    check(adventureId, String);

    var adventure = Adventures.findOne(adventureId);
    if (adventure) {
      Adventures.update({ _id: adventure._id }, { $set: { status: AdventureStatus.complete, abort: true } });

      // give it a few seconds, but make sure the process ends
      if (adventure.pid) {
        Meteor.setTimeout(() => {
          // get the updated record
          adventure = Adventures.findOne(adventureId);

          // check to see if the process has exited
          if (adventure.pid) {
            console.debug("Looks like adventure " + adventure._id + " may still be alive as pid " + adventure.pid);

            // make sure it's dead
            console.debug("Killing adventure " + adventure._id + ", " + adventure.pid);
            childProcess.exec("kill " + adventure.pid, (error, stdout, stderr) => {
              if (error) {
                console.error("Killing adventure failed: ", error);
              } else {
                console.log("Adventure killed:");
                console.log("stdout: ", stdout.toString());
                console.log("stderr: ", stderr.toString());
              }
            });
          } else {
            console.debug("Adventure abort watchdog: adventure " + adventure._id + " looks dead");
          }
        }, 10000);
      } else {
        console.error("Abort Adventure: No PID for adventure " + adventureId);
      }
    } else {
      console.error("Adventure not found: " + adventureId);
    }
  },

  /**
   * pauseAdventure
   * @param adventureId
   */
  pauseAdventure(adventureId) {
    console.debug("pauseAdventure: ", adventureId);
    check(adventureId, String);

    Adventures.update(adventureId, { $set: { status: AdventureStatus.paused } })
  },

  /**
   * Send the adventure status enum to the clients
   * @returns {AdventureStatus|*}
   */
  loadAdventureEnums() {
    return {
      AdventureStatus    : AdventureStatus,
      AdventureStepStatus: AdventureStepStatus,
      NodeCheckTypes     : NodeCheckTypes
    };
  },

  /**
   * Set the status of an adventure
   * @param adventureId
   * @param status
   */
  setAdventureStatus(adventureId, status) {
    console.debug("setAdventureStatus:", adventureId, status);
    check(adventureId, String);
    check(status, Number);

    var adventure = Adventures.findOne({ _id: adventureId });
    Adventures.update({ _id: adventure._id }, { $set: { status: status } });
  },

  /**
   * Store the current state of an adventure
   * @param adventureId
   * @param state
   */
  saveAdventureState(adventureId, state) {
    console.debug("saveAdventureState: " + adventureId);
    check(adventureId, String);
    check(state, Object);
    AdventureStates.upsert({ adventureId: adventureId }, { $set: state });
  },

  /**
   * Set the known location of an adventure
   * @param adventureId
   * @param nodeId
   */
  setAdventureLocation(adventureId, nodeId) {
    console.debug("setAdventureLocation:", adventureId, nodeId);
    check(adventureId, String);
    check(nodeId, String);

    var adventure = Adventures.findOne({ _id: adventureId });
    Adventures.update({ _id: adventure._id }, { $set: { lastKnownNode: nodeId } });
  },

  /**
   * Set the log file path for an adventure
   * @param adventureId
   * @param path
   */
  setAdventureLogFile(adventureId, path) {
    console.debug("setAdventureLogFile:", adventureId, path);
    check(adventureId, String);
    check(path, String);

    Adventures.update({ _id: adventureId }, { $set: { logFile: path } });
  },

  /**
   * Set the status of an adventure step
   * @param stepId
   * @param status
   */
  setAdventureStepStatus(stepId, status) {
    console.debug("setAdventureStepStatus:", stepId, status);
    check(stepId, String);
    check(status, Number);

    var step = AdventureSteps.findOne({ _id: stepId });
    AdventureSteps.update({ _id: step._id }, { $set: { status: status } });
  },

  /**
   * Save a result from an adventure step
   * @param stepId
   * @param result
   */
  saveAdventureStepResult(stepId, result) {
    console.debug("saveAdventureStepResult:", stepId);
    check(stepId, String);
    check(result, Object);

    AdventureSteps.update({ _id: stepId }, { $set: { result: result } });
  },

  /**
   * Set the status of an adventure command
   * @param commandId
   * @param status
   * @param result
   */
  setCommandStatus(commandId, status, result) {
    console.debug("setCommandStatus:", commandId, status);
    check(commandId, String);
    check(status, Number);

    // Load the command
    var command = AdventureCommands.findOne({ _id: commandId });

    // Don't write the result unless it exists to prevent losing an existing result
    if (result) {
      // force the result to an object
      var saveResult = result;
      if (_.isArray(result) || !_.isObject(saveResult)) {
        saveResult = {
          result: result
        };
      }

      AdventureCommands.update({ _id: command._id }, { $set: { status: status, result: saveResult } });
    } else {
      AdventureCommands.update({ _id: command._id }, { $set: { status: status } });
    }
  },

  /**
   * Return a single static record of a node
   * @param staticId
   * @param projectVersionId
   */
  loadNode(staticId, projectVersionId) {
    console.debug("loadNode:", staticId, projectVersionId);
    return Nodes.findOne({ staticId: staticId, projectVersionId: projectVersionId });
  },

  /**
   * Respond to a heartbeat request keeping the DDP connection alive
   */
  heartbeat() {
    return "ACK";
  }
});
<|endoftext|>


<commit_before>var fs = require("q-io/fs"); // https://github.com/kriskowal/q-io
var request = require('request');

var paths = {
  features: 'features',
  public: 'public/test-feature-files/'
};

module.exports = function () {

  this.Given(/^a set of specifications exists$/, function (callback) {
    /**
     * Copy this repo's features files to a public directory for serving.
     */

    // Remove old files.
    fs.removeTree(paths.public)
      .catch(function(err) {
        // Ignore failure to unlink missing directory.
        if (err.code !== 'ENOENT') throw err;
      })

      // Make the target directory for static feature files
      // in the static assets 'public' directory.
      .then(function() {
        return fs.makeTree(paths.public);
      })
      // Copy over the feature files.
      .then(function() {
        return fs.copyTree(paths.features, paths.public);
      })

      // We are done.
      .then(function() {
          callback();
      })

      // Pass unhandled errors to the test framework.
      .catch(function(err) {
        callback(err);
      });
  });

  this.When(/^an interested party attempts to view them$/, function (callback) {
    // the World variable is passed around the step defs as `this`.
    var world = this;

    // Get a list of feature files.
    fs.listTree(paths.public, function guard(path, stat) {
      return /\.feature$/.test(path);
    })

    .then(function(featureFiles) {
      // Request the contents of the first file.
      var featureFile = featureFiles[0];
      request
        .get('http://localhost:3000/' + featureFile, function(error, response, body) {
          if (error) {
            callback(error);
            return;
          }

          // Store the relevant information on the world object for testing.
          world.statusCode = response.statusCode;
          world.body = body;

          // We're done.
          callback();
        });
      })
      .catch(function(err) {
        callback(err);
      });
  });

  this.Then(/^the specifications should be visible$/, function (callback) {

    // If the request succeeded and the body
    // has the word 'feature' in it the test
    // passes.
    if (this.statusCode === 200 && /feature/i.test(this.body)) {
      callback();
    } else {
      callback("Got response: status code: " + this.statusCode + ". Body: " + this.body);
    }
  });
}
<commit_msg>Linting fixes for step def files.<commit_after>"use strict";
/* eslint new-cap: 0 */

var fs = require("q-io/fs"); // https://github.com/kriskowal/q-io
var request = require('request');

var paths = {
  features: 'features',
  public: 'public/test-feature-files/'
};

module.exports = function () {

  this.Given(/^a set of specifications exists$/, function (callback) {
    /**
     * Copy this repo's features files to a public directory for serving.
     */

    // Remove old files.
    fs.removeTree(paths.public)
      .catch(function(err) {
        // Ignore failure to unlink missing directory.
        if (err.code !== 'ENOENT') {
          throw err;
        }
      })

      // Make the target directory for static feature files
      // in the static assets 'public' directory.
      .then(function() {
        return fs.makeTree(paths.public);
      })
      // Copy over the feature files.
      .then(function() {
        return fs.copyTree(paths.features, paths.public);
      })

      // We are done.
      .then(function() {
          callback();
      })

      // Pass unhandled errors to the test framework.
      .catch(function(err) {
        callback(err);
      });
  });

  this.When(/^an interested party attempts to view them$/, function (callback) {
    // the World variable is passed around the step defs as `this`.
    var world = this;

    // Get a list of feature files.
    fs.listTree(paths.public, function guard(path) {
      return /\.feature$/.test(path);
    })

    .then(function(featureFiles) {
      // Request the contents of the first file.
      var featureFile = featureFiles[0];
      request
        .get('http://localhost:3000/' + featureFile, function(error, response, body) {
          if (error) {
            callback(error);
            return;
          }

          // Store the relevant information on the world object for testing.
          world.statusCode = response.statusCode;
          world.body = body;

          // We're done.
          callback();
        });
      })
      .catch(function(err) {
        callback(err);
      });
  });

  this.Then(/^the specifications should be visible$/, function (callback) {

    // If the request succeeded and the body
    // has the word 'feature' in it the test
    // passes.
    if (this.statusCode === 200 && /feature/i.test(this.body)) {
      callback();
    } else {
      callback("Got response: status code: " + this.statusCode + ". Body: " + this.body);
    }
  });
};
<|endoftext|>


<commit_before>wn.pages['data-import-tool'].onload = function(wrapper) {
	wrapper.app_page = wn.ui.make_app_page({
		parent: wrapper,
		title: "Data Import Tool",
		icon: "data-import-tool"
	});

	$(wrapper).find('.layout-main-section').append('
1. Download Template
\

\

Download a template for importing a table.
\

\
				<select style="width: 200px" name="dit-doctype">\
				</select>

\
				<input type="checkbox" name="dit-with-data" style="margin-top: -3px">\
				 Download with data\

\

\

\

\

2. Import Data
\

Attach .csv file to import data
\

\

\

\
		');

	$(wrapper).find('.layout-side-section').append('
Help
\

Importing non-English data:
\

While uploading non English files ensure that the encoding is UTF-8.
\

Microsoft Excel Users:\

\

In Excel, save the file in CSV (Comma Delimited) format
\

Open this saved file in Notepad
\

Click on File -> Save As
\

File Name: <your filename>.csv
\
				Save as type: Text Documents (*.txt)
\
				Encoding: UTF-8\

\

Click on Save
\

\

')

	$select = $(wrapper).find('[name="dit-doctype"]');

	wn.messages.waiting($(wrapper).find(".dit-progress-area").toggle(false),
		"Performing hardcore import process....", 100);

	// load doctypes
	wn.call({
		method:'core.page.data_import_tool.data_import_tool.get_doctypes',
		callback: function(r) {
			$select.add_options(['Select...'].concat(r.message));
			wrapper.doctypes = r.message;
			wrapper.set_route_options();
		}
	});

	wrapper.set_route_options = function() {
		if(wn.route_options
			&& wn.route_options.doctype
			&& in_list(wrapper.doctypes, wn.route_options.doctype)) {
				$select.val(wn.route_options.doctype).change();
				wn.route_options = null;
		}
	}

	// load options
	$select.change(function() {
		var val = $(this).val()
		if(val!='Select...') {
			$('#dit-download').empty();

			// get options
			wn.call({
				method:'core.page.data_import_tool.data_import_tool.get_doctype_options',
				args: {doctype: val},
				callback: function(r) {
					$('
Select Template:
').appendTo('#dit-download');
					var with_data = $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No';
					// download link
					$.each(r.message, function(i, v) {
						if(i==0)
							$('Main Table:
').appendTo('#dit-download');
						if(i==1)
							$('
Child Tables:
').appendTo('#dit-download');
						$('')
							.html(v)
							.data('doctype', v)
							.click(function() {
								window.location.href = repl(wn.request.url
									+ '?cmd=%(cmd)s&doctype=%(doctype)s'
									+ '&parent_doctype=%(parent_doctype)s&with_data=%(with_data)s',
									{
										cmd: 'core.page.data_import_tool.data_import_tool.get_template',
										doctype: $(this).data('doctype'),
										parent_doctype: $('[name="dit-doctype"]').val(),
										with_data: $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No'
									});
							})
							.appendTo('#dit-download');
						$('#dit-download').append('
');
					})
				}
			})
		}
	});

	write_messages = function(r) {
		$(wrapper).find(".dit-progress-area").toggle(false);
		$("#dit-output").empty();

		$.each(r.messages, function(i, v) {
			var $p = $('
').html(v).appendTo('#dit-output');
			if(v.substr(0,5)=='Error') {
				$p.css('color', 'red');
			} else if(v.substr(0,8)=='Inserted') {
				$p.css('color', 'green');
			} else if(v.substr(0,7)=='Updated') {
				$p.css('color', 'green');
			} else if(v.substr(0,5)=='Valid') {
				$p.css('color', '#777');
			}
		});
	}

	// upload
	wn.upload.make({
		parent: $('#dit-upload-area'),
		args: {
			method: 'core.page.data_import_tool.data_import_tool.upload'
		},
		onerror: function(r) {
			r.messages = $.map(r.message.messages, function(v) {
				var msg = v.replace("Inserted", "Valid")
					.replace("Updated", "Valid").split("<");
				if (msg.length > 1) {
					v = msg[0] + (msg[1].split(">").slice(-1)[0]);
				} else {
					v = msg[0];
				}
				return v;
			});

			r.messages = ["
Import Failed!
"]
				.concat(r.messages);

			write_messages(r);
		},
		callback: function(r) {
			// replace links if error has occured
			r.messages = ["
Import Successful!
"].
				concat(r.messages)

			write_messages(r);
		}
	});

	// add overwrite option
	var $submit_btn = $('#dit-upload-area input[type="submit"]');
	$('<input type="checkbox" name="overwrite" style="margin-top: -3px">\
		 Overwrite\

If you are uploading a child table (for example Item Price), the all the entries of that table will be deleted (for that parent record) and new entries will be made.

')
		.insertBefore($submit_btn);

	// add submit option
	$('<input type="checkbox" name="_submit" style="margin-top: -3px">\
		 Submit\

If you are inserting new records (overwrite not checked) \
			and if you have submit permission, the record will be submitted.

')
		.insertBefore($submit_btn);

	// add ignore option
	$('<input type="checkbox" name="ignore_encoding_errors" style="margin-top: -3px">\
		 Ignore Encoding Errors

')
		.insertBefore($submit_btn);

	// rename button
	$('#dit-upload-area form input[type="submit"]')
		.attr('value', 'Upload and Import')
		.click(function() {
			$('#dit-output').empty();
			$(wrapper).find(".dit-progress-area").toggle(true);
		});
}

wn.pages['data-import-tool'].onshow = function(wrapper) {
	wrapper.set_route_options && wrapper.set_route_options();
}<commit_msg>[fix] [minor] upload callback arguments changed<commit_after>wn.pages['data-import-tool'].onload = function(wrapper) {
	wrapper.app_page = wn.ui.make_app_page({
		parent: wrapper,
		title: "Data Import Tool",
		icon: "data-import-tool"
	});

	$(wrapper).find('.layout-main-section').append('
1. Download Template
\

\

Download a template for importing a table.
\

\
				<select style="width: 200px" name="dit-doctype">\
				</select>

\
				<input type="checkbox" name="dit-with-data" style="margin-top: -3px">\
				 Download with data\

\

\

\

\

2. Import Data
\

Attach .csv file to import data
\

\

\

\
		');

	$(wrapper).find('.layout-side-section').append('
Help
\

Importing non-English data:
\

While uploading non English files ensure that the encoding is UTF-8.
\

Microsoft Excel Users:\

\

In Excel, save the file in CSV (Comma Delimited) format
\

Open this saved file in Notepad
\

Click on File -> Save As
\

File Name: <your filename>.csv
\
				Save as type: Text Documents (*.txt)
\
				Encoding: UTF-8\

\

Click on Save
\

\

')

	$select = $(wrapper).find('[name="dit-doctype"]');

	wn.messages.waiting($(wrapper).find(".dit-progress-area").toggle(false),
		"Performing hardcore import process....", 100);

	// load doctypes
	wn.call({
		method:'core.page.data_import_tool.data_import_tool.get_doctypes',
		callback: function(r) {
			$select.add_options(['Select...'].concat(r.message));
			wrapper.doctypes = r.message;
			wrapper.set_route_options();
		}
	});

	wrapper.set_route_options = function() {
		if(wn.route_options
			&& wn.route_options.doctype
			&& in_list(wrapper.doctypes, wn.route_options.doctype)) {
				$select.val(wn.route_options.doctype).change();
				wn.route_options = null;
		}
	}

	// load options
	$select.change(function() {
		var val = $(this).val()
		if(val!='Select...') {
			$('#dit-download').empty();

			// get options
			wn.call({
				method:'core.page.data_import_tool.data_import_tool.get_doctype_options',
				args: {doctype: val},
				callback: function(r) {
					$('
Select Template:
').appendTo('#dit-download');
					var with_data = $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No';
					// download link
					$.each(r.message, function(i, v) {
						if(i==0)
							$('Main Table:
').appendTo('#dit-download');
						if(i==1)
							$('
Child Tables:
').appendTo('#dit-download');
						$('')
							.html(v)
							.data('doctype', v)
							.click(function() {
								window.location.href = repl(wn.request.url
									+ '?cmd=%(cmd)s&doctype=%(doctype)s'
									+ '&parent_doctype=%(parent_doctype)s&with_data=%(with_data)s',
									{
										cmd: 'core.page.data_import_tool.data_import_tool.get_template',
										doctype: $(this).data('doctype'),
										parent_doctype: $('[name="dit-doctype"]').val(),
										with_data: $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No'
									});
							})
							.appendTo('#dit-download');
						$('#dit-download').append('
');
					})
				}
			})
		}
	});

	write_messages = function(r) {
		$(wrapper).find(".dit-progress-area").toggle(false);
		$("#dit-output").empty();

		$.each(r.messages, function(i, v) {
			var $p = $('
').html(v).appendTo('#dit-output');
			if(v.substr(0,5)=='Error') {
				$p.css('color', 'red');
			} else if(v.substr(0,8)=='Inserted') {
				$p.css('color', 'green');
			} else if(v.substr(0,7)=='Updated') {
				$p.css('color', 'green');
			} else if(v.substr(0,5)=='Valid') {
				$p.css('color', '#777');
			}
		});
	}

	// upload
	wn.upload.make({
		parent: $('#dit-upload-area'),
		args: {
			method: 'core.page.data_import_tool.data_import_tool.upload'
		},
		onerror: function(r) {
			r.messages = $.map(r.message.messages, function(v) {
				var msg = v.replace("Inserted", "Valid")
					.replace("Updated", "Valid").split("<");
				if (msg.length > 1) {
					v = msg[0] + (msg[1].split(">").slice(-1)[0]);
				} else {
					v = msg[0];
				}
				return v;
			});

			r.messages = ["
Import Failed!
"]
				.concat(r.messages);

			write_messages(r);
		},
		callback: function(fid, filename, r) {
			// replace links if error has occured
			r.messages = ["
Import Successful!
"].
				concat(r.message.messages)

			write_messages(r);
		}
	});

	// add overwrite option
	var $submit_btn = $('#dit-upload-area input[type="submit"]');
	$('<input type="checkbox" name="overwrite" style="margin-top: -3px">\
		 Overwrite\

If you are uploading a child table (for example Item Price), the all the entries of that table will be deleted (for that parent record) and new entries will be made.

')
		.insertBefore($submit_btn);

	// add submit option
	$('<input type="checkbox" name="_submit" style="margin-top: -3px">\
		 Submit\

If you are inserting new records (overwrite not checked) \
			and if you have submit permission, the record will be submitted.

')
		.insertBefore($submit_btn);

	// add ignore option
	$('<input type="checkbox" name="ignore_encoding_errors" style="margin-top: -3px">\
		 Ignore Encoding Errors

')
		.insertBefore($submit_btn);

	// rename button
	$('#dit-upload-area form input[type="submit"]')
		.attr('value', 'Upload and Import')
		.click(function() {
			$('#dit-output').empty();
			$(wrapper).find(".dit-progress-area").toggle(true);
		});
}

wn.pages['data-import-tool'].onshow = function(wrapper) {
	wrapper.set_route_options && wrapper.set_route_options();
}<|endoftext|>


<commit_before>var CustomError = require("../index.js").Custom;

describe("CustomError", function() {
    it("has a stack trace", function() {
        var e = new CustomError("pokemón gotta catch them all");
        expect(e.stack).toMatch(/^CustomError: pokemón gotta catch them all/);
    });

    it("has a type", function() {
        var e = new CustomError();
        expect(e.typeName).toEqual("Error");
    });
});
<commit_msg>Expect CustomError to have type CustomError<commit_after>var CustomError = require("../index.js").Custom;

describe("CustomError", function() {
    it("has a stack trace", function() {
        var e = new CustomError("pokemón gotta catch them all");
        expect(e.stack).toMatch(/^CustomError: pokemón gotta catch them all/);
    });

    it("has a type", function() {
        var e = new CustomError();
        expect(e.typeName).toEqual("CustomError");
    });
});
<|endoftext|>


<commit_before>/**
 * Wish.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

var Promise = require('bluebird');

module.exports = {

  attributes: {
    doneAt: {
      type: 'datetime'
    },

    MainWish: {
      model: 'CommunityWish',
      required: true
    },

    accepted: {
      type: 'boolean',
      defaultsTo: true
    },

    acceptedAt: {
      type: 'datetime'
    },

    private: {
      type: 'boolean',
      defaultsTo: false
    },

    suggestedBy: {
      model: 'Person'
    },

    owner: {
      model: 'Person',
      required: true
    },

    active: {
      type: 'boolean',
      defaultsTo: true
    }
  },

  beforeCreate: function (wish, cb) {
    // SET UP DATE (acceptedAt IF NEEDED)
    /*
     if(wish.suggestedBy != null)
     {
     wish.acceptedAt = new Date();
     }
     */
    cb();
  },

  afterCreate: function (createdWish, cb) {

    Promise.all([
      CommunityWish.findOne({id: createdWish.MainWish}),
      History.create({action: 'CREATED', date: createdWish.createdAt, owner: createdWish.owner, wish: createdWish.id})
    ])
      .then(function (cw) {
        if (createdWish.accepted) {

          Wish.find({MainWish: createdWish.MainWish, active: true, accepted: true})
            .then(function (res) {
              cw[0].numberOfWish = res.length;
              cw[0].save(function (err, user) {
              });
              cb();
            })
            .catch(function (err) {
              sails.log(err);
              cb();
            });
        }
        else {
          cb();
        }
      })
      .catch(function (err) {
        sails.log(err);
        sails.log("### ERRO BRUTAL ###");
        sails.log("#########################");
        cb();
      });
  }
};

<commit_msg>inserting history with suggestions<commit_after>/**
 * Wish.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

var Promise = require('bluebird');

function insertInHistoryAndUpdateCommunityWish(createdWish, cb, action) {
  Promise.all([
    CommunityWish.findOne({id: createdWish.MainWish}),
    History.create({action: action, date: createdWish.createdAt, owner: createdWish.owner, wish: createdWish.id})
  ])
    .then(function (cw) {
      if (createdWish.accepted) {

        Wish.find({MainWish: createdWish.MainWish, active: true, accepted: true})
          .then(function (res) {
            cw[0].numberOfWish = res.length;
            cw[0].save(function (err, user) {
            });
            cb();
          })
          .catch(function (err) {
            sails.log(err);
            cb();
          });
      }
      else {
        cb();
      }
    })
    .catch(function (err) {
      sails.log(err);
      sails.log("### ERRO BRUTAL ###");
      sails.log("#########################");
      cb();
    });
}
module.exports = {

  attributes: {
    doneAt: {
      type: 'datetime'
    },

    MainWish: {
      model: 'CommunityWish',
      required: true
    },

    accepted: {
      type: 'boolean',
      defaultsTo: true
    },

    acceptedAt: {
      type: 'datetime'
    },

    private: {
      type: 'boolean',
      defaultsTo: false
    },

    suggestedBy: {
      model: 'Person'
    },

    owner: {
      model: 'Person',
      required: true
    },

    active: {
      type: 'boolean',
      defaultsTo: true
    }
  },

  beforeCreate: function (wish, cb) {
    // SET UP DATE (acceptedAt IF NEEDED)
    /*
     if(wish.suggestedBy != null)
     {
     wish.acceptedAt = new Date();
     }
     */
    cb();
  },

  afterCreate: function (createdWish, cb) {
    if (createdWish.accepted) {
      insertInHistoryAndUpdateCommunityWish(createdWish, cb, 'CREATED');
    }
    else {
      insertInHistoryAndUpdateCommunityWish(createdWish, cb, 'SUGGESTED');
    }
  }
};

<|endoftext|>