<commit_before>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
     alert( localStorage.numGroupe).val());
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);

    var logo = new Image();

    alert(localStorage.numGroupe);

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){
              var cont = 1;
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                if(group != localStorage.numGroup){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                if(group != localStorage.numGroup){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }

        pdf.output("dataurlnewwindow");

}
<commit_msg>Update dynamic_carousel.js<commit_after>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
     alert( localStorage.numGroupe);
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);

    var logo = new Image();

    alert(localStorage.numGroupe);

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){
              var cont = 1;
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                if(group != localStorage.numGroup){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                if(group != localStorage.numGroup){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                if(group != localStorage.numGroup){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }

        pdf.output("dataurlnewwindow");

}
<|endoftext|>


<commit_before>var test = require('tape')
var dop = require('../.proxy').create()
var dopClient1 = require('../.proxy').create()
var dopClient2 = require('../.proxy').create()
var transportName = process.argv[2] || 'local'
var transportListen = require('dop-transports').listen[transportName]
var transportConnect = require('dop-transports').connect[transportName]

dop.env = 'SERVER'
dop.data.object_inc = 25
dopClient1.env = 'CLIENT1'
dopClient2.env = 'CLIENT2'

test('BROADCAST TESTS', function(tt) {
    var test = function(name, cb) {
        tt.test(name, {}, cb)
    }

    var server = dop.listen({ transport: transportListen })
    var client1 = dopClient1.connect({
        transport: transportConnect,
        listener: server
    })
    var client2 = dopClient2.connect({
        transport: transportConnect,
        listener: server
    })

    var objServer = {
        number: 1,
        subobject: {}
    }
    dop.register(objServer)
    dop.setBroadcastFunction(objServer.subobject, 'broadcast')
    dop.onSubscribe(function() {
        return objServer
    })

    // setBroadcastFunction(object, 'namefunction')

    test('BROADCASTING TO CLIENTS', function(t) {
        client1
            .subscribe()
            .into({
                subobject: {
                    broadcast: function(a, b) {
                        return a + b
                    }
                }
            })
            .then(function(obj) {
                return client2.subscribe().into({
                    subobject: {
                        broadcast: function(a, b) {
                            return a * b
                        }
                    }
                })
            })
            .then(function(obj) {
                var promises = objServer.subobject.broadcast(2, 5)
                t.equal(Array.isArray(promises), true, 'Promises is array')
                t.equal(promises.length, 2, 'Promises are two promises')
                t.equal(
                    promises[0] instanceof Promise,
                    true,
                    'First promise is instanceof Promise'
                )
                Promise.all(promises).then(function(values) {
                    t.equal(values[0], 7, 'First value must be 2+5=7')
                    t.equal(values[0], 7, 'Second value must be 2*5=10')
                    // try {
                    server.listener.close()
                    // client1.socket.close();
                    // client2.socket.close();
                    // } catch(e) {
                    // console.log( e );
                    // process.exit();
                    // }
                    t.end()
                })
                // .catch(function(err){
                //     console.log( err );
                // })
            })
    })

    // More test todo
    tt.end()
})
<commit_msg>Improved broadcast test<commit_after>var test = require('tape')
var dop = require('../.proxy').create()
var dopClient1 = require('../.proxy').create()
var dopClient2 = require('../.proxy').create()
var transportName = process.argv[2] || 'local'
var transportListen = require('dop-transports').listen[transportName]
var transportConnect = require('dop-transports').connect[transportName]

dop.env = 'SERVER'
dop.data.object_inc = 25
dopClient1.env = 'CLIENT1'
dopClient2.env = 'CLIENT2'

test('BROADCAST TESTS', function(tt) {
    var test = function(name, cb) {
        tt.test(name, {}, cb)
    }

    var server = dop.listen({ transport: transportListen })
    var client1 = dopClient1.connect({
        transport: transportConnect,
        listener: server
    })
    var client2 = dopClient2.connect({
        transport: transportConnect,
        listener: server
    })

    var objServer = {
        number: 1,
        subobject: {}
    }
    var objClient1 = {
        subobject: {
            broadcastFunction: function(a, b) {
                return a + b
            }
        }
    }
    var objClient2 = {
        subobject: {
            broadcastFunction: function(a, b) {
                return a * b
            }
        }
    }

    dop.register(objServer)
    dop.setBroadcastFunction(objServer.subobject, 'broadcastFunction')
    dop.onSubscribe(function() {
        return objServer
    })

    tt.equal(
        typeof objServer.subobject.broadcastFunction,
        'function',
        'broadcastFunction is a function'
    )

    test('BROADCASTING TO CLIENTS', function(t) {
        client1
            .subscribe()
            .into(objClient1)
            .then(function(obj) {
                return client2.subscribe().into(objClient2)
            })
            .then(function(obj) {
                var promises = objServer.subobject.broadcastFunction(2, 5)
                t.equal(Array.isArray(promises), true, 'Promises is array')
                t.equal(promises.length, 2, 'Promises are two promises')
                t.equal(
                    promises[0] instanceof Promise,
                    true,
                    'First promise is instanceof Promise'
                )
                return Promise.all(promises)
                // .catch(function(err){
                //     console.log( err );
                // })
            })
            .then(function(values) {
                t.equal(values[0], 7, 'First value must be 2+5=7')
                t.equal(values[1], 10, 'Second value must be 2*5=10')

                objClient1.subobject.broadcastFunction = function(a, b) {
                    return a / b
                }

                return Promise.all(objServer.subobject.broadcastFunction(10, 2))
            })
            .then(function(values) {
                t.equal(values[0], 5, 'First value must be 10/2=5')
                t.equal(values[1], 20, 'Second value must be 10*2=20')
                server.listener.close()
                // client1.socket.close();
                // client2.socket.close();
                t.end()
            })
    })

    // More test todo
    tt.end()
})
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. 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.
 */

CLASS({
  package: 'foam.u2.md',
  name: 'Input',
  extends: 'foam.u2.View',

  requires: [ 'foam.u2.Input' ],
  imports: [ 'dynamic' ],

  properties: [
    ['nodeName', 'div'],
    {
      name: 'showLabel',
      attribute: true,
      defaultValueFn: function() {
        return ! this.inline;
      }
    },
    {
      model_: 'BooleanProperty',
      name: 'inline',
      attribute: true,
      defaultValue: false
    },
    {
      name: 'label',
      attribute: true
    },
    {
      name: 'placeholder',
      attribute: true,
      documentation: 'Ignored when $$DOC{ref:".showLabel"} is true, but used ' +
          'as an inline placeholder when it\'s false.',
    },
    {
      model_: 'BooleanProperty',
      name: 'focused_'
    },
  ],

  methods: [
    function init() {
      this.SUPER();
      var self = this;
      this.cls(this.myCls());
      if (this.showLabel) {
        this.start('label')
            .cls(this.myCls('label'))
            .cls(this.dynamic(function() {
              return (typeof self.data !== 'undefined' && self.data !== '') ||
                  self.focused_ ? self.myCls('label-offset') : '';
            }, this.data$, this.focused_$))
            .add(this.label$)
            .end();
      } else {
        this.cls(this.myCls('no-label'));
      }

      var input = this.start('input')
          .attrs({ type: 'text' })
          .on('focus', function() { self.focused_ = true; })
          .on('blur', function() { self.focused_ = false; });
      if (!this.showLabel && this.placeholder)
        input.attrs({ placeholder: this.placeholder });
      input.data$ = this.data$;
      input.end();
    },
    function fromProperty(prop) {
      this.label = this.label || prop.label;
      return this.SUPER(prop);
    }
  ],

  templates: [
    function CSS() {/*
      $ {
        align-items: center;
        display: flex;
        margin: 8px;
        padding: 32px 8px 8px 8px;
        position: relative;
      }
      $-label {
        color: #999;
        flex-grow: 1;
        font-size: 14px;
        font-weight: 500;
        position: absolute;
        top: 32px;
        transition: font-size 0.5s, top 0.5s;
        z-index: 0;
      }
      $-label-offset {
        font-size: 85%;
        top: 8px;
      }
      $-no-label {
        padding-top: 8px;
      }
      $ input {
        background: transparent;
        border-bottom: 1px solid #e0e0e0;
        border-left: none;
        border-top: none;
        border-right: none;
        color: #444;
        flex-grow: 1;
        font-family: inherit;
        font-size: inherit;
        margin-bottom: -8px;
        padding: 0 0 7px 0;
        resize: none;
        z-index: 1;
      }
      $ input:focus {
        border-bottom: 2px solid #4285f4;
        padding: 0 0 6px 0;
        outline: none;
      }
    */}
  ]
});
<commit_msg>U2 MD Input: Port to dynamic.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. 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.
 */

CLASS({
  package: 'foam.u2.md',
  name: 'Input',
  extends: 'foam.u2.View',

  requires: [ 'foam.u2.Input' ],
  imports: [ 'dynamic' ],

  properties: [
    ['nodeName', 'div'],
    {
      name: 'showLabel',
      attribute: true,
      defaultValueFn: function() {
        return ! this.inline;
      }
    },
    {
      model_: 'BooleanProperty',
      name: 'inline',
      attribute: true,
      defaultValue: false
    },
    {
      name: 'label',
      attribute: true
    },
    {
      name: 'placeholder',
      attribute: true,
      documentation: 'Ignored when $$DOC{ref:".showLabel"} is true, but used ' +
          'as an inline placeholder when it\'s false.',
    },
    {
      model_: 'BooleanProperty',
      name: 'focused_'
    },
  ],

  methods: [
    function initE() {
      var self = this;
      this.cls(this.myCls());
      if (this.showLabel) {
        this.start('label')
            .cls(this.myCls('label'))
            .cls(this.dynamic(function(data, focused_) {
              return (typeof data !== 'undefined' && data !== '') ||
                  focused_ ? self.myCls('label-offset') : '';
            }, this.data$, this.focused_$))
            .add(this.label$)
            .end();
      } else {
        this.cls(this.myCls('no-label'));
      }

      var input = this.start('input')
          .attrs({ type: 'text' })
          .on('focus', function() { self.focused_ = true; })
          .on('blur', function() { self.focused_ = false; });
      if (!this.showLabel && this.placeholder)
        input.attrs({ placeholder: this.placeholder });
      input.data$ = this.data$;
      input.end();
    },
    function fromProperty(prop) {
      this.label = this.label || prop.label;
      return this.SUPER(prop);
    }
  ],

  templates: [
    function CSS() {/*
      $ {
        align-items: center;
        display: flex;
        margin: 8px;
        padding: 32px 8px 8px 8px;
        position: relative;
      }
      $-label {
        color: #999;
        flex-grow: 1;
        font-size: 14px;
        font-weight: 500;
        position: absolute;
        top: 32px;
        transition: font-size 0.5s, top 0.5s;
        z-index: 0;
      }
      $-label-offset {
        font-size: 85%;
        top: 8px;
      }
      $-no-label {
        padding-top: 8px;
      }
      $ input {
        background: transparent;
        border-bottom: 1px solid #e0e0e0;
        border-left: none;
        border-top: none;
        border-right: none;
        color: #444;
        flex-grow: 1;
        font-family: inherit;
        font-size: inherit;
        margin-bottom: -8px;
        padding: 0 0 7px 0;
        resize: none;
        z-index: 1;
      }
      $ input:focus {
        border-bottom: 2px solid #4285f4;
        padding: 0 0 6px 0;
        outline: none;
      }
    */}
  ]
});
<|endoftext|>


<commit_before>// ID of the (hidden) form field used to store the JSON representation of the
// object being edited in this page
var sJsonFieldId = 'json_object';

// The memory representation of the object
var oObj = {};

// Mapping between the fields of the form and the attribute of the current object
// If aFieldsMap[2] contains 'foo' it means that oObj.foo corresponds to the field
// of Id 'att_2' in the form
var aFieldsMap = new Array;

// Update the whole object from the form and also update its
// JSON (serialized) representation in the (hidden) field
function UpdateObjectFromForm(aFieldsMap, oObj)
{
	for(i=0; i<aFieldsMap.length; i++)
	{
		var oElement = document.getElementById('att_'+i);
		var sFieldName = aFieldsMap[i];
		oObj['m_aCurrValues'][sFieldName] = oElement.value;
		sJSON = JSON.stringify(oObj);
		var oJSON = document.getElementById(sJsonFieldId);
		oJSON.value = sJSON;
	}
	return oObj;
}

// Update the specified field from the current object
function UpdateFieldFromObject(idField, aFieldsMap, oObj)
{
	var oElement = document.getElementById('att_'+idField);
	oElement.value = oObj['m_aCurrValues'][aFieldsMap[idField]];
}
// Update all the fields of the Form from the current object
function UpdateFormFromObject(aFieldsMap, oObj)
{
	for(i=0; i<aFieldsMap.length; i++)
	{
		UpdateFieldFromForm(i, aFieldsMap, oObj);
	}
}

// This function is meant to be called from the AJAX page
// It reloads the object (oObj) from the JSON representation
// and also updates the form field that contains the JSON
// representation of the object
function ReloadObjectFromServer(sJSON)
{
	//console.log('JSON value:', sJSON);
	var oJSON = document.getElementById(sJsonFieldId);
	oJSON.value = sJSON;
	oObj = JSON.parse( '(' + sJSON + ')' );
	return oObj;
}

function GoToStep(iCurrentStep, iNextStep)
{
	var oCurrentStep = document.getElementById('wizStep'+iCurrentStep);
	if (iNextStep > iCurrentStep)
	{
		// Check the values when moving forward
		if (CheckMandatoryFields('wizStep'+iCurrentStep))
		{
			oCurrentStep.style.display = 'none';
			ActivateStep(iNextStep);
		}
	}
	else
	{
		oCurrentStep.style.display = 'none';
		ActivateStep(iNextStep);
	}
}

function ActivateStep(iTargetStep)
{
	UpdateObjectFromForm(aFieldsMap, oObj);
	var oNextStep = document.getElementById('wizStep'+(iTargetStep));
	window.location.href='#step'+iTargetStep;
	// If a handler for entering this step exists, call it
	if (typeof(this['OnEnterStep'+iTargetStep]) == 'function')
	{
		eval( 'OnEnterStep'+iTargetStep+'();');
	}
	oNextStep.style.display = '';
	G_iCurrentStep = iTargetStep;
	$('#wizStep'+(iTargetStep)).block({ message: null });
}

function AjaxGetValuesDef(oObj, sClass, sAttCode, iFieldId)
{
	var oJSON = document.getElementById(sJsonFieldId);
	$.get('ajax.render.php?class=' + sClass + '&json_obj=' + oJSON.value + '&att_code=' + sAttCode,
	   { operation: "allowed_values" },
	   function(data){
		 //$('#field_'+iFieldId).html(data);
		}
	);
}

function AjaxGetDefaultValue(oObj, sClass, sAttCode, iFieldId)
{
	// Asynchronously call the server to provide a default value if the field is
	// empty
	if (oObj['m_aCurrValues'][sAttCode] == '')
	{
		var oJSON = document.getElementById(sJsonFieldId);
		$.get('ajax.render.php?class=' + sClass + '&json_obj=' + oJSON.value + '&att_code=' + sAttCode,
		   { operation: "default_value" },
		   function(json_data){
			 var oObj = ReloadObjectFromServer(json_data);
			 UpdateFieldFromObject(iFieldId, aFieldsMap, oObj)
			}
		);
	}
}

function CheckMandatoryFields(sFormId)
{
	$('#'+sFormId+' :submit').attr('disable', 'disabled');
	$('#'+sFormId+' :button[type=submit]').attr('disable', 'disabled');
	firstErrorId = '';

	var iErrorsCount = 0;
	$('#'+sFormId+' :input.mandatory').each( function() {
		if (( this.value == '') || (this.value == 0))
		{
			this.style.background = '#fcc';
			iErrorsCount++;
			if (iErrorsCount == 1)
			{
				firstErrorId = this.id;
			}
		}
		else
		{
			this.style.background = '#fff';
		}
	}
	);
	if(iErrorsCount > 0)
	{
		alert('Please fill-in all mandatory fields before continuing.');
		$('#'+sFormId+' :submit').attr('disable', '');
		$('#'+sFormId+' :button[type=submit]').attr('disable', '');
		if (firstErrorId != '')
		{
			$('#'+firstErrorId).focus();
		}
	}
	return(iErrorsCount == 0);
}
<commit_msg>Field validation now preserves background images<commit_after>// ID of the (hidden) form field used to store the JSON representation of the
// object being edited in this page
var sJsonFieldId = 'json_object';

// The memory representation of the object
var oObj = {};

// Mapping between the fields of the form and the attribute of the current object
// If aFieldsMap[2] contains 'foo' it means that oObj.foo corresponds to the field
// of Id 'att_2' in the form
var aFieldsMap = new Array;

// Update the whole object from the form and also update its
// JSON (serialized) representation in the (hidden) field
function UpdateObjectFromForm(aFieldsMap, oObj)
{
	for(i=0; i<aFieldsMap.length; i++)
	{
		var oElement = document.getElementById('att_'+i);
		var sFieldName = aFieldsMap[i];
		oObj['m_aCurrValues'][sFieldName] = oElement.value;
		sJSON = JSON.stringify(oObj);
		var oJSON = document.getElementById(sJsonFieldId);
		oJSON.value = sJSON;
	}
	return oObj;
}

// Update the specified field from the current object
function UpdateFieldFromObject(idField, aFieldsMap, oObj)
{
	var oElement = document.getElementById('att_'+idField);
	oElement.value = oObj['m_aCurrValues'][aFieldsMap[idField]];
}
// Update all the fields of the Form from the current object
function UpdateFormFromObject(aFieldsMap, oObj)
{
	for(i=0; i<aFieldsMap.length; i++)
	{
		UpdateFieldFromForm(i, aFieldsMap, oObj);
	}
}

// This function is meant to be called from the AJAX page
// It reloads the object (oObj) from the JSON representation
// and also updates the form field that contains the JSON
// representation of the object
function ReloadObjectFromServer(sJSON)
{
	//console.log('JSON value:', sJSON);
	var oJSON = document.getElementById(sJsonFieldId);
	oJSON.value = sJSON;
	oObj = JSON.parse( '(' + sJSON + ')' );
	return oObj;
}

function GoToStep(iCurrentStep, iNextStep)
{
	var oCurrentStep = document.getElementById('wizStep'+iCurrentStep);
	if (iNextStep > iCurrentStep)
	{
		// Check the values when moving forward
		if (CheckMandatoryFields('wizStep'+iCurrentStep))
		{
			oCurrentStep.style.display = 'none';
			ActivateStep(iNextStep);
		}
	}
	else
	{
		oCurrentStep.style.display = 'none';
		ActivateStep(iNextStep);
	}
}

function ActivateStep(iTargetStep)
{
	UpdateObjectFromForm(aFieldsMap, oObj);
	var oNextStep = document.getElementById('wizStep'+(iTargetStep));
	window.location.href='#step'+iTargetStep;
	// If a handler for entering this step exists, call it
	if (typeof(this['OnEnterStep'+iTargetStep]) == 'function')
	{
		eval( 'OnEnterStep'+iTargetStep+'();');
	}
	oNextStep.style.display = '';
	G_iCurrentStep = iTargetStep;
	$('#wizStep'+(iTargetStep)).block({ message: null });
}

function AjaxGetValuesDef(oObj, sClass, sAttCode, iFieldId)
{
	var oJSON = document.getElementById(sJsonFieldId);
	$.get('ajax.render.php?class=' + sClass + '&json_obj=' + oJSON.value + '&att_code=' + sAttCode,
	   { operation: "allowed_values" },
	   function(data){
		 //$('#field_'+iFieldId).html(data);
		}
	);
}

function AjaxGetDefaultValue(oObj, sClass, sAttCode, iFieldId)
{
	// Asynchronously call the server to provide a default value if the field is
	// empty
	if (oObj['m_aCurrValues'][sAttCode] == '')
	{
		var oJSON = document.getElementById(sJsonFieldId);
		$.get('ajax.render.php?class=' + sClass + '&json_obj=' + oJSON.value + '&att_code=' + sAttCode,
		   { operation: "default_value" },
		   function(json_data){
			 var oObj = ReloadObjectFromServer(json_data);
			 UpdateFieldFromObject(iFieldId, aFieldsMap, oObj)
			}
		);
	}
}

function CheckMandatoryFields(sFormId)
{
	$('#'+sFormId+' :submit').attr('disable', 'disabled');
	$('#'+sFormId+' :button[type=submit]').attr('disable', 'disabled');
	firstErrorId = '';

	var iErrorsCount = 0;
	$('#'+sFormId+' :input.mandatory').each( function() {
		if (( this.value == '') || (this.value == 0))
		{
			this.style.backgroundColor = '#fcc';
			iErrorsCount++;
			if (iErrorsCount == 1)
			{
				firstErrorId = this.id;
			}
		}
		else
		{
			this.style.backgroundColor = '#fff';
		}
	}
	);
	if(iErrorsCount > 0)
	{
		alert('Please fill-in all mandatory fields before continuing.');
		$('#'+sFormId+' :submit').attr('disable', '');
		$('#'+sFormId+' :button[type=submit]').attr('disable', '');
		if (firstErrorId != '')
		{
			$('#'+firstErrorId).focus();
		}
	}
	return(iErrorsCount == 0);
}
<|endoftext|>


<commit_before>import Orbit from 'orbit';
import { RecordNotFoundException, RecordAlreadyExistsException } from 'orbit_common/lib/exceptions';
import attr from 'ember_orbit/attr';
import Context from 'ember_orbit/context';
import Store from 'ember_orbit/store';
import Model from 'ember_orbit/model';
import { createStore } from 'test_helper';

var get = Ember.get,
    set = Ember.set;

var Planet,
    store,
    context;

module("Unit - Context", {
  setup: function() {
    Orbit.Promise = Ember.RSVP.Promise;

    Planet = Model.extend({
      name: attr('string'),
    });

    store = createStore({
      models: {
        planet: Planet
      }
    });

    context = Context.create({
      store: store
    });
  },

  teardown: function() {
    Orbit.Promise = null;
    Planet = null;
    store = null;
    context = null;
  }
});

test("it exists", function() {
  ok(context);
});

test("it has a properly defined schema", function() {
  var schema = context.get('schema');
  ok(schema, 'it has a schema');
  ok(schema._schema.models.planet, 'models are defined');
});

test("#add will add a new instance of a model", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      ok(get(planet, 'clientid'), 'assigned clientid');
      equal(planet.get('name'), 'Earth');
    });
  });
});

test("#find will asynchronously return a record when called with a `type` and a single `id`", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      context.find('planet', planet.get('clientid')).then(function(foundPlanet) {
        strictEqual(foundPlanet, planet);
      });
    });
  });
});

test("#find will asynchronously fail if a record can't be found", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      context.find('planet', 'bogus').then(function(foundPlanet) {
        ok(false);
      }, function(e) {
        ok(e instanceof RecordNotFoundException);
      });
    });
  });
});

test("#find will asynchronously return an array of records when called with a `type` and an array of `ids`", function() {
  expect(3);

  Ember.run(function() {
    var planets = [],
        ids = [];

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));
      return context.add('planet', {name: 'Jupiter'});

    }).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));

    }).then(function() {
      context.find('planet', ids).then(function(foundPlanets) {
        equal(foundPlanets.length, planets.length, 'same number of planets created and found');

        for (var i = 0; i < planets.length; i++) {
          strictEqual(foundPlanets[i], planets[i], 'found planet matches created planet');
        }
      });
    });
  });
});

test("#find will asynchronously return an array of all records when called with just a `type`", function() {
  expect(3);

  Ember.run(function() {
    var planets = [],
        ids = [];

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));
      return context.add('planet', {name: 'Jupiter'});

    }).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));

    }).then(function() {
      context.find('planet').then(function(foundPlanets) {
        equal(foundPlanets.length, planets.length, 'same number of planets created and found');

        for (var i = 0; i < planets.length; i++) {
          strictEqual(foundPlanets[i], planets[i], 'found planet matches created planet');
        }
      });
    });
  });
});

test("#find will asynchronously return an array of records when called with a `type` and a query object", function() {
  expect(2);

  Ember.run(function() {
    var planets = [],
        ids = [];

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));
      return context.add('planet', {name: 'Jupiter'});

    }).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));

    }).then(function() {
      context.find('planet', {name: 'Jupiter'}).then(function(foundPlanets) {
        equal(foundPlanets.length, 1, 'only one planet is named "Jupiter"');

        strictEqual(foundPlanets[0], planets[1], 'found planet matches created planet');
      });
    });
  });
});

test("#remove will asynchronously remove a record when called with a `type` and a single `id`", function() {
  expect(2);

  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      var id = planet.get('clientid');

      strictEqual(context.retrieve('planet', id), planet);

      context.remove('planet', id).then(function() {
        strictEqual(context.retrieve('planet', id), undefined);
      });
    });
  });
});

test("#remove will asynchronously remove a record when called with a single model instance", function() {
  expect(2);

  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      var id = planet.get('clientid');

      strictEqual(context.retrieve('planet', id), planet);

      context.remove(planet).then(function() {
        strictEqual(context.retrieve('planet', id), undefined);
      });
    });
  });
});

test("#retrieve can synchronously retrieve a record by id", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      var planet2 = context.retrieve('planet', planet.get('clientid'));
      strictEqual(planet2, planet);
    });
  });
});

test("#retrieve will return undefined if the record does not exist", function() {
  Ember.run(function() {
    var foundPlanet = context.retrieve('planet', 'bogusId');
    strictEqual(foundPlanet, undefined);
  });
});

test("#retrieve can synchronously retrieve all records of a particular type", function() {
  Ember.run(function() {
    Ember.RSVP.all([
      context.add('planet', {name: 'Earth'}),
      context.add('planet', {name: 'Jupiter'})
    ]).then(function() {
      var planets = context.retrieve('planet');
      equal(planets.length, 2);
      equal(get(planets.objectAt(0), 'name'), 'Earth');
      equal(get(planets.objectAt(1), 'name'), 'Jupiter');
    });
  });
});

test("#all returns a live RecordArray that stays in sync with records of one type", function() {
  expect(4);

  Ember.run(function() {
    var planets = context.all('planet');

    equal(get(planets, 'length'), 0, 'no records have been added yet');

    context.add('planet', {name: 'Earth'}).then(function(earth) {
      equal(get(planets, 'length'), 1, 'one record has been added');

      context.add('planet', {name: 'Jupiter'}).then(function(jupiter) {
        equal(get(planets, 'length'), 2, 'two records have been added');

        context.remove(earth).then(function() {
          equal(get(planets, 'length'), 1, 'one record is left');
        });
      });
    });
  });
});

test("#then resolves when all transforms have completed", function() {
  stop();
  Ember.run(function() {
    context.add('planet', {name: 'Earth'});
    context.add('planet', {name: 'Jupiter'});

    context.then(function() {
      start();
      ok(true, 'finished processing transforms');
    });
  });
});<commit_msg>Context test cleanup<commit_after>import Orbit from 'orbit';
import { RecordNotFoundException, RecordAlreadyExistsException } from 'orbit_common/lib/exceptions';
import attr from 'ember_orbit/attr';
import Context from 'ember_orbit/context';
import Store from 'ember_orbit/store';
import Model from 'ember_orbit/model';
import { createStore } from 'test_helper';

var get = Ember.get,
    set = Ember.set;

var Planet,
    store,
    context;

module("Unit - Context", {
  setup: function() {
    Orbit.Promise = Ember.RSVP.Promise;

    Planet = Model.extend({
      name: attr('string'),
    });

    store = createStore({
      models: {
        planet: Planet
      }
    });

    context = Context.create({
      store: store
    });
  },

  teardown: function() {
    Orbit.Promise = null;
    Planet = null;
    store = null;
    context = null;
  }
});

test("it exists", function() {
  ok(context);
});

test("it has a properly defined schema", function() {
  var schema = context.get('schema');
  ok(schema, 'it has a schema');
  ok(schema._schema.models.planet, 'models are defined');
});

test("#add will add a new instance of a model", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      ok(get(planet, 'clientid'), 'assigned clientid');
      equal(planet.get('name'), 'Earth');
    });
  });
});

test("#find will asynchronously return a record when called with a `type` and a single `id`", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      context.find('planet', planet.get('clientid')).then(function(foundPlanet) {
        strictEqual(foundPlanet, planet);
      });
    });
  });
});

test("#find will asynchronously fail if a record can't be found", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      context.find('planet', 'bogus').then(function(foundPlanet) {
        ok(false);
      }, function(e) {
        ok(e instanceof RecordNotFoundException);
      });
    });
  });
});

test("#find will asynchronously return an array of records when called with a `type` and an array of `ids`", function() {
  expect(3);

  Ember.run(function() {
    var planets = [],
        ids = [];

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));
      return context.add('planet', {name: 'Jupiter'});

    }).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));

    }).then(function() {
      context.find('planet', ids).then(function(foundPlanets) {
        equal(foundPlanets.length, planets.length, 'same number of planets created and found');

        for (var i = 0; i < planets.length; i++) {
          strictEqual(foundPlanets[i], planets[i], 'found planet matches created planet');
        }
      });
    });
  });
});

test("#find will asynchronously return an array of all records when called with just a `type`", function() {
  expect(3);

  Ember.run(function() {
    var planets = [],
        ids = [];

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));
      return context.add('planet', {name: 'Jupiter'});

    }).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));

    }).then(function() {
      context.find('planet').then(function(foundPlanets) {
        equal(foundPlanets.length, planets.length, 'same number of planets created and found');

        for (var i = 0; i < planets.length; i++) {
          strictEqual(foundPlanets[i], planets[i], 'found planet matches created planet');
        }
      });
    });
  });
});

test("#find will asynchronously return an array of records when called with a `type` and a query object", function() {
  expect(2);

  Ember.run(function() {
    var planets = [],
        ids = [];

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));
      return context.add('planet', {name: 'Jupiter'});

    }).then(function(planet) {
      planets.push(planet);
      ids.push(planet.get('clientid'));

    }).then(function() {
      context.find('planet', {name: 'Jupiter'}).then(function(foundPlanets) {
        equal(foundPlanets.length, 1, 'only one planet is named "Jupiter"');

        strictEqual(foundPlanets[0], planets[1], 'found planet matches created planet');
      });
    });
  });
});

test("#remove will asynchronously remove a record when called with a `type` and a single `id`", function() {
  expect(2);

  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      var id = planet.get('clientid');

      strictEqual(context.retrieve('planet', id), planet);

      context.remove('planet', id).then(function() {
        strictEqual(context.retrieve('planet', id), undefined);
      });
    });
  });
});

test("#remove will asynchronously remove a record when called with a single model instance", function() {
  expect(2);

  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      var id = planet.get('clientid');
      strictEqual(context.retrieve('planet', id), planet);

      context.remove(planet).then(function() {
        strictEqual(context.retrieve('planet', id), undefined);
      });
    });
  });
});

test("#retrieve can synchronously retrieve a record by id", function() {
  Ember.run(function() {
    context.add('planet', {name: 'Earth'}).then(function(planet) {
      var planet2 = context.retrieve('planet', planet.get('clientid'));
      strictEqual(planet2, planet);
    });
  });
});

test("#retrieve will return undefined if the record does not exist", function() {
  Ember.run(function() {
    var foundPlanet = context.retrieve('planet', 'bogusId');
    strictEqual(foundPlanet, undefined);
  });
});

test("#retrieve can synchronously retrieve all records of a particular type", function() {
  expect(3);

  Ember.run(function() {
    Ember.RSVP.all([
      context.add('planet', {name: 'Earth'}),
      context.add('planet', {name: 'Jupiter'})

    ]).then(function() {
      var planets = context.retrieve('planet');
      equal(planets.length, 2);
      equal(get(planets.objectAt(0), 'name'), 'Earth');
      equal(get(planets.objectAt(1), 'name'), 'Jupiter');
    });
  });
});

test("#all returns a live RecordArray that stays in sync with records of one type", function() {
  expect(4);

  Ember.run(function() {
    var planets = context.all('planet'), earth;
    equal(get(planets, 'length'), 0, 'no records have been added yet');

    context.add('planet', {name: 'Earth'}).then(function(planet) {
      earth = planet;
      equal(get(planets, 'length'), 1, 'one record has been added');

    }).then(function() {
      return context.add('planet', {name: 'Jupiter'});

    }).then(function() {
      equal(get(planets, 'length'), 2, 'two records have been added');

    }).then(function() {
      return context.remove(earth);

    }).then(function() {
      equal(get(planets, 'length'), 1, 'one record is left');
    });
  });
});

test("#then resolves when all transforms have completed", function() {
  expect(2);

  Ember.run(function() {
    context.add('planet', {name: 'Earth'});
    context.add('planet', {name: 'Jupiter'});

    context.then(function() {
      ok(true, 'finished processing transforms');
      equal(get(context.all('planet'), 'length'), 2, 'two records have been added');
    });
  });
});<|endoftext|>


<commit_before>// vim: set ts=2 sw=2 et colorcolumn=100 :

/**
 * Namespace
 * @namespace
 */
var geochart_geojson = {};

(function(context) {

/**
 * Create a GeoChart with GeoJSON support
 * @class
 *
 * These charts are very similar to the Google Charts geochart, but with GeoJSON support.
 *
 * Code based on many Google Charts and Google Maps API guides and references.
 *
 * See:
 *
 * - https://developers.google.com/chart/interactive/docs/dev/
 * - https://developers.google.com/chart/interactive/docs/gallery/geochart
 * - https://developers.google.com/chart/interactive/docs/datatables_dataviews
 * - https://developers.google.com/chart/interactive/docs/reference
 * - https://developers.google.com/maps/documentation/javascript/
 *
 * @param {object} container - The HTML container for the chart.
 */
context.GeoChart = function(container) {
  this.container = container;

  this.data_ = null;
  this.options_ = null;
  // The inner Google Maps map object
  // This object will hold the GeoJSON map (in its overlay layer), the tooltip overlay and the
  // legend control.
  // Optionally, it will also handle the underlying map layer (map, satellite or simple map) and
  // the map control (zoom, map drag). These features are disabled by default, so the
  this.maps_map_ = null;
  this.tooltip_ = null;
  this.legend_ = null;
  // Min and max values of the DataTable rows
  // Used in the gradient color generation.
  this.min_ = 0;
  this.max_ = 0;
  // Feature selected by the user
  this.feature_selected_ = null;
}

context.GeoChart.prototype.CONSTANTS = {
  // zIndex of selected or highlighted features
  // The selected (click) and highlighted (hover) features must have a zIndex higher than
  // the other features.
  selectedZIndex: 999,
  highlightedZIndex: 1000
}

context.GeoChart.prototype.DEFAULT_OPTIONS = {
  mapsBackground: "none",
  mapsControl: false,
  featuresStyle: {
    fillColor: "#f5f5f5",
    strokeColor: '#dddddd',
    fillOpacity: 1,
    strokeWeight: 1,
    cursor: "default"
  },
  featuresHighlightedStyle: {
    strokeWeight: 3,
    strokeOpacity: 1,
  },
  featuresGradientColors: ["#efe6dc", "#109618"],
  featuresGradientStrokeColors: ["#d7cfc6", "0e8716"]
}

// TODO Implement other `mapsBackground` and `mapsControl` options
context.GeoChart.prototype.getMapsOptions_ = function() {
  var maps_options = this.options_.mapsOptions;

  if (this.options_.mapsBackground === "none") {
    maps_options["styles"] = [{
      "stylers": [{"visibility": "off"}]
    }];
    maps_options["backgroundColor"] = "none";
  } else {
    throw "Invalid `mapsBackground` option";
  }

  if (this.options_.mapsControl === false) {
    maps_options["disableDefaultUI"] = true;
    maps_options["scrollwheel"] = false;
    maps_options["draggable"] = false;
    maps_options["disableDoubleClickZoom"] = true;
  } else {
    throw "Invalid `mapsControl` option";
  }

  return maps_options;
}

context.GeoChart.prototype.draw = function(data, options) {
  this.data_ = data;
  // XXX This doesn't run a deep copy. So, if someday `DEFAULT_OPTIONS` has objects in its values,
  // the line above won't work anymore.
  // See: https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
  var merged_options = Object.assign({}, context.GeoChart.prototype.DEFAULT_OPTIONS, options);
  this.options_ = merged_options;

  var this_ = this;

  // Create the Google Maps object
  var maps_options = this.getMapsOptions_();
  // TODO We could implement custom zooming when mapsBackground = 'none' using custom
  // projections.
  // See: https://groups.google.com/forum/#!topic/google-maps-js-api-v3/AbOHZlLQLCg
  this.map_ = new google.maps.Map(this.container, maps_options);

  // Load the GeoJSON data
  this.map_.data.loadGeoJson(
      this.options_.geoJson, this.options_.geoJsonOptions,
      function(features) {
        var min = Number.MAX_VALUE;
        var max = -Number.MAX_VALUE;

        // Populate the feature "data-" properties
        for (var row = 0; row < data.getNumberOfRows(); row++) {
          var id = data.getValue(row, 0);
          var value = data.getValue(row, 1);
          var feature = this_.map_.data.getFeatureById(id);

          // Keep track of min and max values
          if (value < min) {
            min = value;
          }
          if (value > max) {
            max = value;
          }
          feature.setProperty("data-row", row);
          feature.setProperty("data-value", value);
        }
        this_.min_ = min;
        this_.max_ = max;

        // Trigger the ready event
        // See: https://developers.google.com/chart/interactive/docs/dev/events#the-ready-event
        google.visualization.events.trigger(this_, 'ready', null);
      }
  );

  // Define the feature styles
  this.map_.data.setStyle(function(feature) {
    // Default style
    var style = Object.assign({}, this_.DEFAULT_OPTIONS.featuresStyle);

    // Feature with data style
    // Colorize the features with data (using the gradient colors)
    if (feature.getProperty("data-value") !== undefined) {
      var fill_color_arr = [];
      var stroke_color_arr = [];

      var gradient_colors_arr = [
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientColors[0]),
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientColors[1])
      ];
      var gradient_stroke_colors_arr = [
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientStrokeColors[0]),
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientStrokeColors[1])
      ];
      var relative_value = this_.getRelativeValue_(feature.getProperty("data-value"));

      for (var i = 0; i < 3; i++) {
        fill_color_arr[i] =
            (gradient_colors_arr[1][i] - gradient_colors_arr[0][i]) * relative_value +
            gradient_colors_arr[0][i];
        stroke_color_arr[i] =
            ((gradient_stroke_colors_arr[1][i] - gradient_stroke_colors_arr[0][i]) *
            relative_value) + gradient_stroke_colors_arr[0][i];
      }

      style = Object.assign(style, {
        fillColor: 'rgb(' + fill_color_arr[0] + ',' + fill_color_arr[1] + ',' +
            fill_color_arr[2] + ')',
        strokeColor: 'rgb(' + stroke_color_arr[0] + ',' + stroke_color_arr[1] + ',' +
            stroke_color_arr[2] + ')'
      });

      // Selected feature style
      if (feature.getProperty("data-selected") === true) {
        style = Object.assign(
            style, this_.DEFAULT_OPTIONS.featuresHighlightedStyle,
            {zIndex: this_.CONSTANTS.selectedZIndex}
        );
      }
    }

    return style;
  });

  this.map_.data.addListener('mouseover', function(event) {
    var highlight_style = Object.assign(
        {}, this_.DEFAULT_OPTIONS.featuresHighlightedStyle,
        {zIndex: this_.CONSTANTS.highlightedZIndex});

    if (event.feature !== this_.feature_selected_) {
        this_.map_.data.revertStyle();
        this_.map_.data.overrideStyle(event.feature, highlight_style);
    }
  });

  this.map_.data.addListener('mouseout', function(event) {
    if (event.feature !== this_.feature_selected_) {
        this_.map_.data.revertStyle();
    }
  });

}

// Based on: https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
context.GeoChart.prototype.getColorArray_ = function(color) {
  var short_regex = /^#?([\da-f])([\da-f])([\da-f])$/i;
  var regex = /^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;

  var color_array = null;

  color = color.replace(short_regex, function(m, r, g, b) {
    return "#" + r + r + g + g + b + b;
  });
  var result = regex.exec(color);
  if (! result) {
    throw "Invalid color string";
  }
  color_array = [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];

  return color_array;
}

context.GeoChart.prototype.getRelativeValue_ = function(value) {
  return (value - this.min_) / (this.max_ - this.min_);
}

// Entry selected by the user
// See: https://developers.google.com/chart/interactive/docs/reference#getselection
context.GeoChart.prototype.getSelection = function() {
  if (! this.feature_selected_) {
    return [];
  } else {
    return [{row: this.feature_selected_.getProperty("data-row"), column: null}];
  }
}

context.GeoChart.prototype.setSelection = function(selection) {
  var id = "";
  var feature = null;

  // Implemented only for a single row selection
  if (Array.isArray(selection) && selection.length === 1) {
      id = this.data_.getValue(selection[0].row, 0);
      feature = this.map_.data.getFeatureById(id);
      this.selectFeature_(feature);
  }
}

context.GeoChart.prototype.selectFeature_ = function(feature) {
  this.feature_selected_ = feature;
  this.feature_selected_.setProperty("data-selected", true);
}

})(geochart_geojson);
<commit_msg>Adding the select event handlers (mouse click)<commit_after>// vim: set ts=2 sw=2 et colorcolumn=100 :

/**
 * Namespace
 * @namespace
 */
var geochart_geojson = {};

(function(context) {

/**
 * Create a GeoChart with GeoJSON support
 * @class
 *
 * These charts are very similar to the Google Charts geochart, but with GeoJSON support.
 *
 * Code based on many Google Charts and Google Maps API guides and references.
 *
 * See:
 *
 * - https://developers.google.com/chart/interactive/docs/dev/
 * - https://developers.google.com/chart/interactive/docs/gallery/geochart
 * - https://developers.google.com/chart/interactive/docs/datatables_dataviews
 * - https://developers.google.com/chart/interactive/docs/reference
 * - https://developers.google.com/maps/documentation/javascript/
 *
 * @param {object} container - The HTML container for the chart.
 */
context.GeoChart = function(container) {
  this.container = container;

  this.data_ = null;
  this.options_ = null;
  // The inner Google Maps map object
  // This object will hold the GeoJSON map (in its overlay layer), the tooltip overlay and the
  // legend control.
  // Optionally, it will also handle the underlying map layer (map, satellite or simple map) and
  // the map control (zoom, map drag). These features are disabled by default, so the
  this.maps_map_ = null;
  this.tooltip_ = null;
  this.legend_ = null;
  // Min and max values of the DataTable rows
  // Used in the gradient color generation.
  this.min_ = 0;
  this.max_ = 0;
  // Feature selected by the user
  this.feature_selected_ = null;
}

context.GeoChart.prototype.CONSTANTS = {
  // zIndex of selected or highlighted features
  // The selected (click) and highlighted (hover) features must have a zIndex higher than
  // the other features.
  selectedZIndex: 999,
  highlightedZIndex: 1000
}

context.GeoChart.prototype.DEFAULT_OPTIONS = {
  mapsBackground: "none",
  mapsControl: false,
  featuresStyle: {
    fillColor: "#f5f5f5",
    strokeColor: '#dddddd',
    fillOpacity: 1,
    strokeWeight: 1,
    cursor: "default"
  },
  featuresHighlightedStyle: {
    strokeWeight: 3,
    strokeOpacity: 1,
  },
  featuresGradientColors: ["#efe6dc", "#109618"],
  featuresGradientStrokeColors: ["#d7cfc6", "0e8716"]
}

// TODO Implement other `mapsBackground` and `mapsControl` options
context.GeoChart.prototype.getMapsOptions_ = function() {
  var maps_options = this.options_.mapsOptions;

  if (this.options_.mapsBackground === "none") {
    maps_options["styles"] = [{
      "stylers": [{"visibility": "off"}]
    }];
    maps_options["backgroundColor"] = "none";
  } else {
    throw "Invalid `mapsBackground` option";
  }

  if (this.options_.mapsControl === false) {
    maps_options["disableDefaultUI"] = true;
    maps_options["scrollwheel"] = false;
    maps_options["draggable"] = false;
    maps_options["disableDoubleClickZoom"] = true;
  } else {
    throw "Invalid `mapsControl` option";
  }

  return maps_options;
}

context.GeoChart.prototype.draw = function(data, options) {
  this.data_ = data;
  // XXX This doesn't run a deep copy. So, if someday `DEFAULT_OPTIONS` has objects in its values,
  // the line above won't work anymore.
  // See: https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
  var merged_options = Object.assign({}, context.GeoChart.prototype.DEFAULT_OPTIONS, options);
  this.options_ = merged_options;

  var this_ = this;

  // Create the Google Maps object
  var maps_options = this.getMapsOptions_();
  // TODO We could implement custom zooming when mapsBackground = 'none' using custom
  // projections.
  // See: https://groups.google.com/forum/#!topic/google-maps-js-api-v3/AbOHZlLQLCg
  this.map_ = new google.maps.Map(this.container, maps_options);

  // Load the GeoJSON data
  this.map_.data.loadGeoJson(
      this.options_.geoJson, this.options_.geoJsonOptions,
      function(features) {
        var min = Number.MAX_VALUE;
        var max = -Number.MAX_VALUE;

        // Populate the feature "data-" properties
        for (var row = 0; row < data.getNumberOfRows(); row++) {
          var id = data.getValue(row, 0);
          var value = data.getValue(row, 1);
          var feature = this_.map_.data.getFeatureById(id);

          // Keep track of min and max values
          if (value < min) {
            min = value;
          }
          if (value > max) {
            max = value;
          }
          feature.setProperty("data-row", row);
          feature.setProperty("data-value", value);
        }
        this_.min_ = min;
        this_.max_ = max;

        // Trigger the ready event
        // See: https://developers.google.com/chart/interactive/docs/dev/events#the-ready-event
        google.visualization.events.trigger(this_, 'ready', null);
      }
  );

  // Define the feature styles
  this.map_.data.setStyle(function(feature) {
    // Default style
    var style = Object.assign({}, this_.DEFAULT_OPTIONS.featuresStyle);

    // Feature with data style
    // Colorize the features with data (using the gradient colors)
    if (feature.getProperty("data-value") !== undefined) {
      var fill_color_arr = [];
      var stroke_color_arr = [];

      var gradient_colors_arr = [
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientColors[0]),
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientColors[1])
      ];
      var gradient_stroke_colors_arr = [
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientStrokeColors[0]),
          this_.getColorArray_(this_.DEFAULT_OPTIONS.featuresGradientStrokeColors[1])
      ];
      var relative_value = this_.getRelativeValue_(feature.getProperty("data-value"));

      for (var i = 0; i < 3; i++) {
        fill_color_arr[i] =
            (gradient_colors_arr[1][i] - gradient_colors_arr[0][i]) * relative_value +
            gradient_colors_arr[0][i];
        stroke_color_arr[i] =
            ((gradient_stroke_colors_arr[1][i] - gradient_stroke_colors_arr[0][i]) *
            relative_value) + gradient_stroke_colors_arr[0][i];
      }

      style = Object.assign(style, {
        fillColor: 'rgb(' + fill_color_arr[0] + ',' + fill_color_arr[1] + ',' +
            fill_color_arr[2] + ')',
        strokeColor: 'rgb(' + stroke_color_arr[0] + ',' + stroke_color_arr[1] + ',' +
            stroke_color_arr[2] + ')'
      });

      // Selected feature style
      if (feature.getProperty("data-selected") === true) {
        style = Object.assign(
            style, this_.DEFAULT_OPTIONS.featuresHighlightedStyle,
            {zIndex: this_.CONSTANTS.selectedZIndex}
        );
      }
    }

    return style;
  });

  // Mouse event handlers

  this.map_.data.addListener("mouseover", function(event) {
    var highlighted_style = Object.assign(
        {}, this_.DEFAULT_OPTIONS.featuresHighlightedStyle,
        {zIndex: this_.CONSTANTS.highlightedZIndex});

    if (event.feature !== this_.feature_selected_) {
        this_.map_.data.revertStyle();
        this_.map_.data.overrideStyle(event.feature, highlighted_style);
    }
  });

  this.map_.data.addListener("mouseout", function(event) {
    if (event.feature !== this_.feature_selected_) {
        this_.map_.data.revertStyle();
    }
  });

  this.map_.data.addListener("click", function(event) {
    this_.map_.data.revertStyle();
    if (event.feature !== this_.feature_selected_) {
      if (event.feature.getProperty("data-value") !== undefined) {
        this_.selectFeature_(event.feature);
      } else {
        this_.unselectFeature_(event.feature);
      }
    }
  });

  this.map_.addListener("click", function(event) {
    this_.map_.data.revertStyle();
    this_.unselectFeature_(event.feature);
  });

}

// Based on: https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
context.GeoChart.prototype.getColorArray_ = function(color) {
  var short_regex = /^#?([\da-f])([\da-f])([\da-f])$/i;
  var regex = /^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i;

  var color_array = null;

  color = color.replace(short_regex, function(m, r, g, b) {
    return "#" + r + r + g + g + b + b;
  });
  var result = regex.exec(color);
  if (! result) {
    throw "Invalid color string";
  }
  color_array = [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];

  return color_array;
}

context.GeoChart.prototype.getRelativeValue_ = function(value) {
  return (value - this.min_) / (this.max_ - this.min_);
}

// Entry selected by the user
// See: https://developers.google.com/chart/interactive/docs/reference#getselection
context.GeoChart.prototype.getSelection = function() {
  if (! this.feature_selected_) {
    return [];
  } else {
    return [{row: this.feature_selected_.getProperty("data-row"), column: null}];
  }
}

context.GeoChart.prototype.setSelection = function(selection) {
  var id = "";
  var feature = null;

  // Implemented only for zero and single row selections
  if (! selection.length) {
    this.unselectFeature_();
  } else if (selection.length === 1) {
      id = this.data_.getValue(selection[0].row, 0);
      feature = this.map_.data.getFeatureById(id);
      this.selectFeature_(feature);
  }
}

context.GeoChart.prototype.selectFeature_ = function(feature) {
  this.unselectFeature_();
  this.feature_selected_ = feature;
  this.feature_selected_.setProperty("data-selected", true);
}

context.GeoChart.prototype.unselectFeature_ = function() {
  if (this.feature_selected_) {
    this.feature_selected_.removeProperty("data-selected");
    this.feature_selected_ = null;
  }
}

})(geochart_geojson);
<|endoftext|>


<commit_before>describe('thymeleaf-fragment.js', function() {

	it('should include fragments by fragment name', function() {
		load('include-fragmentname.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should include fragments by fragment name with parameters', function() {
		load('include-fragmentparams.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should include fragments by explicit DOM selector', function() {
		load('include-domselector-explicit.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
y
' +
			'
'
		);
	});

	it('should include fragments by implicit DOM selector', function() {
		load('include-domselector-implicit.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
y
' +
			'
'
		);
	});

	it('should include templates', function() {
		load('include-template.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
z
' +
			'
'
		);
	});

	it('should include nested fragments', function() {
		load('include-nested.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
' +
					'
' +
						'
x
' +
					'
' +
				'
' +
			'
'
		);
	});

	it('should ignore whitespace in include fragment spec', function() {
		load('include-whitespace.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should replace fragments by fragment name', function() {
		load('replace-fragmentname.html');

		expect(getMainInnerHtml()).toEqual(
			'
x
'
		);
	});

	it('should replace fragments by fragment name with parameters', function() {
		load('replace-fragmentparams.html');

		expect(getMainInnerHtml()).toEqual(
			'
x
'
		);
	});

	it('should replace fragments by explicit DOM selector', function() {
		load('replace-domselector-explicit.html');

		expect(getMainInnerHtml()).toEqual(
			'
y
'
		);
	});

	it('should replace fragments by implicit DOM selector', function() {
		load('replace-domselector-implicit.html');

		expect(getMainInnerHtml()).toEqual(
			'
y
'
		);
	});

	it('should replace templates', function() {
		load('replace-template.html');

		expect(getMainInnerHtml()).toEqual(
			'
z
'
		);
	});

	it('should replace nested fragments', function() {
		load('replace-nested.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should ignore whitespace in replace fragment spec', function() {
		load('replace-whitespace.html');

		expect(getMainInnerHtml()).toEqual(
			'
x
'
		);
	});

	var load = function(file) {
		browser.driver.get('http://localhost:8080/test/' + file);
		browser.wait(untilElementPresent(by.css('body.loaded')), 1000);
	};

	var untilElementPresent = function(locator) {
		return function() {
			return browser.driver.findElements(locator).then(function(elements) {
				return !!elements.length;
			})
		}
	};

	var getMainInnerHtml = function() {
		return browser.driver.findElement(by.tagName('main')).getInnerHtml();
	};

});
<commit_msg>Formatting<commit_after>describe('thymeleaf-fragment.js', function() {

	it('should include fragments by fragment name', function() {
		load('include-fragmentname.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should include fragments by fragment name with parameters', function() {
		load('include-fragmentparams.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should include fragments by explicit DOM selector', function() {
		load('include-domselector-explicit.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
y
' +
			'
'
		);
	});

	it('should include fragments by implicit DOM selector', function() {
		load('include-domselector-implicit.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
y
' +
			'
'
		);
	});

	it('should include templates', function() {
		load('include-template.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
z
' +
			'
'
		);
	});

	it('should include nested fragments', function() {
		load('include-nested.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
' +
					'
' +
						'
x
' +
					'
' +
				'
' +
			'
'
		);
	});

	it('should ignore whitespace in include fragment spec', function() {
		load('include-whitespace.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should replace fragments by fragment name', function() {
		load('replace-fragmentname.html');

		expect(getMainInnerHtml()).toEqual('
x
');
	});

	it('should replace fragments by fragment name with parameters', function() {
		load('replace-fragmentparams.html');

		expect(getMainInnerHtml()).toEqual('
x
');
	});

	it('should replace fragments by explicit DOM selector', function() {
		load('replace-domselector-explicit.html');

		expect(getMainInnerHtml()).toEqual('
y
');
	});

	it('should replace fragments by implicit DOM selector', function() {
		load('replace-domselector-implicit.html');

		expect(getMainInnerHtml()).toEqual('
y
');
	});

	it('should replace templates', function() {
		load('replace-template.html');

		expect(getMainInnerHtml()).toEqual('
z
');
	});

	it('should replace nested fragments', function() {
		load('replace-nested.html');

		expect(getMainInnerHtml()).toEqual(
			'
' +
				'
x
' +
			'
'
		);
	});

	it('should ignore whitespace in replace fragment spec', function() {
		load('replace-whitespace.html');

		expect(getMainInnerHtml()).toEqual('
x
');
	});

	var load = function(file) {
		browser.driver.get('http://localhost:8080/test/' + file);
		browser.wait(untilElementPresent(by.css('body.loaded')), 1000);
	};

	var untilElementPresent = function(locator) {
		return function() {
			return browser.driver.findElements(locator).then(function(elements) {
				return !!elements.length;
			})
		}
	};

	var getMainInnerHtml = function() {
		return browser.driver.findElement(by.tagName('main')).getInnerHtml();
	};

});
<|endoftext|>


<commit_before>/*
* jQuery Mobile Framework : prototype for "tabs" plugin (based on code from Filament Group,Inc)
* Copyright (c) jQuery Project
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* Note: Code is in draft form and is subject to change
*/
(function($){
$.fn.globalnav = function(settings){
	return $(this).each(function(){ //there should only ever be one of these... is each necessary?

		//wrap it with footer classes
		var globalnav = $(this).wrap('

');

		//apply fixed footer markup to ui-footer
		$(document).fixHeaderFooter();

		//set up the nav tabs widths (currently evenly divided widths, to be improved later)
		var navtabs = globalnav.find('li');
		navtabs.width(100/navtabs.length+'%');

		//apply state on click and at load
		//NOTE: we'll need to find a way to highlight an active tab at load as well
		navtabs.find('a')
			.buttonMarkup({corners: false, iconPos: 'top', icon: 'arrow-u'})
			.bind('tap',function(){
				navtabs.find('.ui-btn-active').removeClass('ui-btn-active');
				$(this).addClass('ui-btn-active');
			});
	});
};
})(jQuery);<commit_msg>added option for fixedAs, which will allow for fixing a globalnav as header or footer<commit_after>/*
* jQuery Mobile Framework : prototype for "tabs" plugin (based on code from Filament Group,Inc)
* Copyright (c) jQuery Project
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* Note: Code is in draft form and is subject to change
*/
(function($){
$.fn.globalnav = function(settings){
	return $(this).each(function(){ //there should only ever be one of these... is each necessary?
		var o = $.extend({
			fixedAs: 'footer'
		},settings);

		//wrap it with footer classes
		var globalnav = $(this).wrap('

').addClass(o.fixedAs == 'footer' ? 'ui-footer' : 'ui-header');

		//apply fixed footer markup to ui-footer
		$(document).fixHeaderFooter();

		//set up the nav tabs widths (currently evenly divided widths, to be improved later)
		var navtabs = globalnav.find('li');
		navtabs.width(100/navtabs.length+'%');

		//apply state on click and at load
		//NOTE: we'll need to find a way to highlight an active tab at load as well
		navtabs.find('a')
			.buttonMarkup({corners: false, iconPos: 'top', icon: 'arrow-u'})
			.bind('tap',function(){
				navtabs.find('.ui-btn-active').removeClass('ui-btn-active');
				$(this).addClass('ui-btn-active');
			});
	});
};
})(jQuery);<|endoftext|>


<commit_before>const test = require('tape')
require('rewire-global')

function stubAzureStorage (createCsvFile) {
  const azureStorage = createCsvFile.__get__('azureStorage')
  azureStorage.cloudStoreTextToFile = () => Promise.resolve()
  azureStorage.cloudgetFile = () => Promise.resolve({name: 'a cloud file name'})
}

test('should only create the header when message has no members', t => {
  t.plan(1)
  const createCsvFile = require('../../messages/createCsvFile')
  stubAzureStorage(createCsvFile)
  const message = {
    _desc: {
      userType: 'students'
    },
    member: []
  }

  createCsvFile(message, 'SF1626VT171', '/tmp/', 'dev-lms-csv').then(result => {
    // TODO: should this really return the name from azure?
    t.deepEqual(result, {csvContent: 'course_id,user_id,role,status\n', csvFileName: '/tmp/a cloud file name'})
  })
})

test('should create the header and one more line when message has one member', t => {
  t.plan(1)
  const createCsvFile = require('../../messages/createCsvFile')

  stubAzureStorage(createCsvFile)

  const sisCourseCode = 'SF1626VT171'

  const message = {
    _desc: {
      userType: 'students'
    },
    member: ['abc123']
  }

  createCsvFile(message, sisCourseCode, '/tmp/', 'dev-lms-csv').then(result => {
    // TODO: should this really return the name from azure?
    const expectedCsvContent = `course_id,user_id,role,status
${sisCourseCode},abc123,students,active
`
    t.deepEqual(result, {csvContent: expectedCsvContent, csvFileName: '/tmp/a cloud file name'})
  })
})

test.skip('should create the file when sisCourseCode is an array', t => {
  t.plan(1)
  t.equal(1, 0)
})
<commit_msg>refactor test<commit_after>const test = require('tape')
require('rewire-global')

const createCsvFile = require('../../messages/createCsvFile')
const azureStorage = createCsvFile.__get__('azureStorage')
azureStorage.cloudStoreTextToFile = () => Promise.resolve()
azureStorage.cloudgetFile = () => Promise.resolve({name: 'a cloud file name'})

test('should only create the header when message has no members', t => {
  t.plan(1)
  const message = {
    _desc: {
      userType: 'students'
    },
    member: []
  }

  createCsvFile(message, 'SF1626VT171', '/tmp/', 'dev-lms-csv').then(result => {
    // TODO: should this really return the name from azure?
    t.deepEqual(result, {csvContent: 'course_id,user_id,role,status\n', csvFileName: '/tmp/a cloud file name'})
  })
})

test('should create the header and one more line when message has one member', t => {
  t.plan(1)

  const sisCourseCode = 'SF1626VT171'

  const message = {
    _desc: {
      userType: 'students'
    },
    member: ['abc123']
  }

  createCsvFile(message, sisCourseCode, '/tmp/', 'dev-lms-csv').then(({csvContent}) => {
    // TODO: should this really return the name from azure?
    const expectedCsvContent = `course_id,user_id,role,status
${sisCourseCode},abc123,students,active
`
    t.deepEqual(csvContent, expectedCsvContent)
  })
})

test.skip('should create the file with header and 10 courses for each member when sisCourseCode is an array', t => {
  t.plan(1)
  t.equal(1, 0)
})
<|endoftext|>